# Question
Title: Golf the Sequence whose Exponential Generating Function is tangent
Almost every function can be expressed as a polynomial with infinite terms.

For example, `e^x = 1 + x + x^2/2! + x^3/3! + x^4/4! + ...`

For example, `sin(x) = x - x^3/3! + x^5/5! - x^7/7! + ...`

The coefficients of the `n`-th terms form a sequence, and the corresponding function is called the **Generating Function** of the sequence.

The coefficients of the `n`-th terms form a sequence.

Often, the `n`-th term would have a denominator of `n!`. Therefore, we multiply the coefficient by `n!` to obtain another sequence, whose **Exponential Generating Function** would be the original function.

For example, the sequence whose **Exponential Generating Function** is `e^x` would be `1,1,1,1,...`.

For example, the sequence whose **Exponential Generating Function** is `sin(x)` would be `0,1,0,-1,0,1,0,-1,...`.

# Task

Your task is to find the `n`-th term of the sequence whose **Exponential Generating Function** is `tan(x)`.

# Testcases

```
n result
0 0
1 1
2 0
3 2
4 0
5 16
6 0
7 272
8 0
9 7936
10 0
11 353792
12 0
13 22368256
14 0
15 1903757312
16 0
17 209865342976
18 0
19 29088885112832
20 0
21 4951498053124096
22 0
23 1015423886506852352
24 0
25 246921480190207983616
26 0

```

(Copied from here.) (Warning: the `0`-th term is different)

# Example implementation

```
# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L16
def memoized(f):
    memo = {}
    def m_fun(*args):
        if args in memo:
            return memo[args]
        else:
            res = f(*args)
            memo[args] = res
            return res
    return m_fun

# copied from https://github.com/Mego/Seriously/blob/v2.0/SeriouslyCommands.py#L169
@memoized
def binomial(n,r):
    if r > n:
        return 0
    elif r==n:
        return 1
    res = 1
    i = 1
    while i<=r:
        res *= (n+1-i)
        res /= i
        i+=1
    return int(res)

# 2*u(n+1) = Sum_{k=0..n} binomial(n, k)*u(k)*u(n-k)
# from A000111
@memoized
def u(n):
    if n<0: return 0
    if n==0: return 1
    if n==1: return 1
    return sum([binomial(n-1,k)*u(k)*u(n-1-k) for k in range(n)])//2

def t(n):
    if n%2 == 0: return 0
    return u(n)

print('\n'.join([str(x) + ' ' + str(t(x)) for x in range(26)]))

```

Ideone it!

# References

# Answer
## CJam (33 32 27 26 23 20 bytes)

```
2,{ee::*_(@+.+}ri*0=

```

Online demo

### Dissection

This essentially implements the recurrence described by xnor.

```
2,        e# [0 1] represents the base case f(0,j) = j==1
{         e# Loop...
  ee::*   e#   Multiply each array element by its index
  _(@+.+  e#   Sum the array shifted left and the array shifted right
}ri*      e# ... n times
0=        e# Evaluate at j=0

```

---

Or with a rather different approach, for 23 bytes:

```
ri_1&a{{1$+}*]W%0+}@*0=

```

Online demo. Thanks to Dennis for 3 bytes.

### Dissection

```
1a         e# Push [1]
{          e# Repeat...
  {1$+}*]  e#   Compute array of partial sums
  W%0+     e#   Reverse and append 0
}qi:A*     e# ... A times, where A is the input value
0=A1&*     e# Result is first element if A odd, and 0 otherwise

```

---

Or with a very different approach, for 29 bytes:

```
qie!Ma-{W\+W+3ew{_$.=1=},!},,

```

Online demo

Unfortunately a special case is required for input `0`.

### Dissection

```
qi            e# Take an integer n from stdin
e!            e#   Compute all permutations of [0 ... n-1]
Ma-           e#   Special-case n=0
{             e#   Filter...
  W\+W+       e#     Prepend and postpend -1
  3ew         e#     Take slices of 3 consecutive elements
  {           e#     Filter...
    _$.=1=    e#       Test whether the middle element is the second largest
  },!         e#     ... and require no matches
},,           e#   ... and count

```

---

You may be thinking "WTF?! He's answering the wrong question." If so, that's understandable, but both approaches do indeed give the correct results.
> 10 votes

# Answer
# Julia, ~~40~~ ~~38~~ 32 bytes

```
!n=2(2*4^n-2^n-0^n)abs(zeta(-n))

```

Input and output is in form of `BigFloat`s. Try it online!

### Background

The Maclaurin series of the tangent function satisfies the identity

whenever **x** lies in its convergence radius, where **Bn** is a Bernoulli number.

Since **B2(n+1)** and **(-1)n** have the same sign, **B2n+1 = 0** if **n \> 0** and **B1 = 1/2**, we can rewrite the above as follows.

Furthermore, whenever **n** is a non-negative integer, we have

where **ζ** denotes the Riemann zeta function.

From this, with the convention **00 = 1**, it follows that

which is the formula the implementation uses.
> 7 votes

# Answer
## Python, 57 bytes

```
f=lambda i,j=0:~-j*f(i-1,j-1)-~j*f(i-1,j+1)if i else j==1

```

Less golfed:

```
f=lambda i,j=0:j==1 if i==0 else (j-1)*f(i-1,j-1)+(j+1)*f(i-1,j+1)

```

We can compute the `i`th coefficient of the exponential generating function by differentiating the tangent function `i` times and evaluating at `0`. Each derivative is a polynomial in `tan(x)`, and its value at 0 is its constant term.

We recursively express the coefficient of `tan(x)**j` in the `i`th derivative of `tan` with the function `f(i,j)`. The recursive expression comes from the relation `tan(x)' = 1 + tan(x)**2`.

So, the derivative of `tan(x)**j` is

```
j*tan(x)**(j-1)*(tan(x)**2+1), or equivalently
j*tan(x)**(j+1) + j*tan(x)**(j-1)

```

So, the contributors to `tan(x)**j` in the `i`th derivative are `tan(x)**(j-1)` and `tan(x)**(j+1)` in the `(i-1)`st derivative, each with coefficient equal to its power. This gives the recursive expression

```
f(i,j) = (j-1)*f(i-1,j-1) + (j+1)*f(i-1,j+1)

```

Note that we don't need to exclude negative exponents `j` because they evaluate to zero anyway and don't contribute because crossing `j=0` gives a multiplier of `0`.

The base case of `i==0` corresponds to `tan(x)` itself with `j==1`, and zero coefficients otherwise. The final evaluation happens at the constant term `j=0`, which is put in as a default value.
> 6 votes

# Answer
# Mathematica, 20 bytes

```
Tan@x~D~{x,#}/.x->0&

```

Straight-forward approach. Calculate the *n*th derivative of *tan(x)* and evaluate it at *x = 0*.

## Usage
> 5 votes

# Answer
## Haskell, 48 bytes

```
0%1=1
0%_=0
i%j=sum[k*(i-1)%k|k<-[j+1,j-1]]
(%0)

```

We can compute the `i`th coefficient of the exponential generating function by differentiating the tangent function `i` times and evaluating at `0`. Each derivative is a polynomial in `tan(x)`, and the value at 0 is its constant term.

We recursively express the coefficient of `tan(x)^j` in the `i`th derivative of `tan` with the function `i%j`. The recursive expression comes from the relation `tan(x)' = 1 + tan(x)^2`.

So, the derivative of `tan(x)^j` is

```
j*tan(x)^(j-1)*(tan(x)^2+1), or equivalently
j*tan(x)^(j+1) + j*tan(x)^(j-1)

```

So, the contributors to `tan(x)^j` in the `i`th derivative are `tan(x)^(j-1)` and `tan(x)^(j+1)` in the `(i-1)`st derivative, each with coefficient equal to its power.
> 3 votes

# Answer
## Sage, 26 bytes

```
lambda n:tan(x).diff(n)(0)

```

Like the other solutions in math-oriented languages, this function computes the `n`th derivative of `tan(x)` and evaluates it at `x = 0`.

Try it online
> 3 votes

# Answer
# Jelly, ~~12~~ 11 bytes

```
Ṛ+\;S
ḂÇ⁸¡Ḣ

```

Like Peter Taylor's CJam answer, this computes the **n**th term of Euler's up/down sequence if **n** is odd and special-cases even **n** as **0**.

Try it online! or verify all test cases.

### How it works

```
ḂÇ⁸¡Ḣ  Main link. Argument: n

Ḃ       Bit; yield n's parity.
 Ç⁸¡    Apply the helper link (Ç) n (⁸) times.
    Ḣ   Head; retrieve the first element of the resulting list.

Ṛ+\;S   Helper link. Argument: A (list or 1/0)

Ṛ       Cast A to list (if necessary) and reverse the result.
 +\     Take the cumulative sum.
   ;S   Append the sum of A.

```
> 3 votes

# Answer
## JavaScript (ES6), ~~127~~ 45 bytes

```
f=(n,m=0)=>n?++m*f(--n,m--)+--m*f(n,m):m-1?0:1

```

Port of @xnor's solutions.
> 2 votes

# Answer
# J, ~~15~~ 13 bytes

There is also the builtin `t:` which calculates the *n*th coefficient of the exponential generating function of *tan(x)*.

```
(1&o.%2&o.)t:

```

Thanks to @Leaky Nun for reminding me of Taylor series adverbs in J which saved 2 bytes.

Alternative for **15 bytes**.

```
3 :'(3&o.d.y)0'

```

Another approach is to calculate the *n*th derivative of *tan(x)* and evaluate it at *x = 0*.

Note: In **J**, the amount of memory used by the derivative function `d.` grows quickly as *n* passes 10.

## Usage

```
   f =: (1&o.%2&o.)t:
   f 7
272
   (,.f"0) i. 11  NB. Additional commands are just for formatting the output
 0    0
 1    1
 2    0
 3    2
 4    0
 5   16
 6    0
 7  272
 8    0
 9 7936
10    0

```

## Explanation

```
(1&o.%2&o.)t:  Input: n
(         )    Define a monad (one argument function), call the input y
 1&o.          Get the trig function sin(x) and call it on y
      2&o.     Get the trig function cos(x) and call it on y
     %         Divide sin(y) by cos(y) to get tan(y)
           t:  Get the nth coefficient of the exponential generating series
               for that function and return

3 :'(3&o.d.y)0'  Input: n
3 :'          '  Define a monad (one argument function) with input y
     3&o.        Get the trig function tan(x)
           y     The input n
         d.      Get the nth derivative of tan(x)
             0   Evaluate the nth derivative at x = 0 and return

```
> 2 votes

# Answer
# Julia, ~~39~~ 37 bytes

```
!n=(spdiagm((0:n,1:n+1),(1,-1))^n)[2]

```

Saved 2 bytes thanks to Dennis.

Not the shortest Julia solution (see Dennis's solution), but this one is done purely using derivative logic... in the form of matrices.

Basically, it uses the fact that the derivative of tan(x) is 1+tan(x)^2. So since the derivative of any power of tan(x), say tan(x)^k, is k tan(x)^(k-1) tan(x)' = k tan(x)^(k-1) + k tan(x)^(k+1), we can use a simple matrix power on a matrix with the appropriate values to generate the expansion, with the second row or column (depending on construction) holding the derivatives of tan(x) itself.

So we just need to find the constant in the resulting expression, and that's the first value in the corresponding row or column.
> 2 votes

# Answer
# Haskell, ~~95~~ 93 bytes

```
p=product
f n=sum[(-1)^(n`div`2+j+1)*j^n*p[k-j+1..n+1]`div`p[1..n+1-k+j]|k<-[1..n],j<-[0..k]]

```

It is basically an implementation of the general formula with some minor optimizations.
> 0 votes

# Answer
# MATLAB with Symbolic Toolbox, 84 bytes

```
n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)

```

Example runs:

```
>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
7
ans =
272

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
8
ans =
0

>> n=input('');syms x;c=coeffs(taylor(tan(x),'Order',n+1))*factorial(n);c(end)*mod(n,2)
9
ans =
7936

```
> 0 votes

# Answer
**Haskell** (too many bytes)

Using only operations on lists and Raymond Manzoni's result:

```
c n = last $ map numerator $ zipWith (*) (scanl (*) (1) [2,3..]) (intersperse 0 $ foldr (.) id (replicate n (\xs->(xs ++ [(1%(1+2*length xs)) * (sum (zipWith (*) xs (reverse xs)))]))) [1])

```

Unfortunately, this overflows for modest values of `n`, as it uses `Int` values. I will try to fix the problem using `Integer`values. Until then, suggestions are welcome.
> 0 votes

# Answer
# Axiom, 46 bytes

```
f(n:NNI):NNI==(n=0=>0;eval(D(tan(x),x,n),x=0))

```

code for test and results

```
(32) -> [[i, f(i)] for i in 0..26]
   (32)
   [[0,0], [1,1], [2,0], [3,2], [4,0], [5,16], [6,0], [7,272], [8,0], [9,7936],
    [10,0], [11,353792], [12,0], [13,22368256], [14,0], [15,1903757312],
    [16,0], [17,209865342976], [18,0], [19,29088885112832], [20,0],
    [21,4951498053124096], [22,0], [23,1015423886506852352], [24,0],
    [25,246921480190207983616], [26,0]]
                                       Type: List List NonNegativeInteger

```
> 0 votes

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


title: Tips for golfing in SOGL

text:
# Question
Title: Tips for golfing in SOGL
Do you have any tips for writing in SOGL, a golfing language created by dzaima?

Your tips should be at least somewhat specific to SOGL.

Please post one tip per answer.

# Answer
# Use the compression creator

Here is a new, buggy but mostly working online JavaScript compression creator. There, in each line enter a part of the string on each line which closest matches one of:

1. custom dictionary string - this will find the different characters used in the part, store them and store a number in the base of the amount of characters. This is effective for strings like `niooaaoasoioaiaaaoiineeaei` where there aren't a lot of different characters. It also works well for just a single character repeated. This has a limit of 98+(different characters used), and the compressor (currently) doesn't auto-split those.
2. boxstrings - strings with only the characters `/\|_-` and `\n`. Practically the same as custom dictionary strings, but more efficient. Note that this is chooses whether to use `/` and `\` with the same bit, so then custom strings will be used. This has a limit the same as custom dictionary strings.
3. english - this has two word dictionaries, one of length 256 and another of ±65500. This only contains lowercase words and automatically adds spaces between words. To get something like `spaceface` do two parts of `space` and `face`. Each english part has a max of 4 words. If a 4-word part is followed by more english, it adds a space between. Trough the compressor will automatically split the input for you.
**Note:** the dictionary contains only lowercase versions of strings (except `I`, `I've`, and a couple others), so you must correctly case if after usage (using the characters  \- uppercase 1st letter,  \- sentence-case, `ū` \- every words 1st letter).
4. ascii - Plain ascii - each part is 1-18 long (trough 1 and 2 are done differently) and auto-splits for you. Approx. 87% compression ratio.

### Other stuff:

* It's always useful to try different combinations and see which is smaller. At the end, it gives you the original and ending byte count and compression ratio. This might be automated sometime in the future. For example, `-_-_\_/_-`  is shorter than `-_-_\_/_-` and  as different parts

An example input would be

```
row
,
row
,
row your boat
,¶"

```

, which outputs `"π¾⌡īk#S)G⁶⁷λ7&[¶⁶āΡn‘`, after which I can put uppercase 1st letter and remove the starting quote and get `π¾⌡īk#S)G⁶⁷λ7&[¶⁶āΡn‘⁽` for `Row, row, row your boat,\n"`
> 3 votes

# Answer
# Remove unnecessary quotes and brackets

You can remove quotes if the string they're encasing is either at the beggining of the program, or right after another string. For example, `"hello”"world”` can be shortened to `hello”world”`. This works for all types of quotes, mixed or not.

Similarly this works with brackets. No need to write `}` after `{`, `?`, nor any of `[]F∫‽⌠`. You can also ommit a starting `{` if there exists and ending `}`
> 2 votes

---
Tags: code-golf, tips
---


title: Google Autocomplete Fun

text:
# Question
Title: Google Autocomplete Fun
Your task is to create a program which, given an input string, will output the first Google autocomplete result for that search. The format of input/output is up to you.

## Rules

1. Your program must take 1 input, a string, and output the top Google autocomplete/auto-fill suggestions result. The format of input/output is up to you. Just be sure to mention what your I/O format is.
2. Obviously, accessing the Internet is allowed.
3. URL shorteners (like bit.ly, TinyURL, etc.) are strictly *disallowed*. You should fetch your autocomplete results from this URL: http://suggestqueries.google.com/complete/search?client=your\_browser&q=your\_query or http://google.com/complete/search?client=your\_browser&q=your\_query. You are allowed to assume any browser name (or string, for that matter) for `client`. In the program I wrote, I assume Chrome. Any browser name or string should work. You are allowed to pass any options to the webpage as long as you are using some variant of http://suggestqueries.google.com/complete/search.
4. Please provide an explanation of how your program works. It is not mandatory, but I strongly advise it.
5. All standard loopholes are *strictly forbidden*.

## Test Cases

These are constantly changing, so edit this post if these become out-of-date.

```
'how to'
  => 'how to make slime'
'code golf'
  => 'code golf languages'
'you'
  => 'youtube'
'g'
  => 'google' (why would you google 'google'?)

```

This is , so may the shortest code win and the best programmer prosper...

# Answer
# Zsh \+ coreutils + w3m, ~~88~~ ~~71~~ 68 bytes

```
echo `w3m "google.com/complete/search?client=gma&q=$*"|cut -d\" -f4`

```

Switching from Bash to Zsh saved 3 bytes.

*Thanks to @FatalMerlin for the shorter URL, saving 17 bytes!*

### Sample run

```
$ zsh complete.sh how to
how to make slime
$ zsh complete.sh dont you
don't you forget about me
$ zsh complete.sh don\'t you
don't you worry child

```
> 8 votes

# Answer
# Vim 8 + unimpaired.vim, 93 89 85 70 73 71 bytes

* -4 bytes thanks to tsh
* -2 bytes thanks to Ian Emnace
* -2 bytes thanks to FatalMerlin
* -1 byte thanks to tsh/ckjbgames

```
:s/ /+/g
D:e http://google.us/complete/search?client=gma&q="
d3f";D]yy

```

As a bonus, the last bytes look like they're winking at you `;D` Since this contains non-printing characters, the explanation contains substitutions (and I've replaced the pre-querystring part of the url with `[url]`, for brevity):

```
:s/ /+/g<CR>D:e [url]?client=gma&q=<C-R>"<CR>d3f";D]yy
:s/ /+/g<CR>                                           " Replace spaces with +
            D                                          " Delete and yank result
             :e                                        " Type :e ('edit' command) and a space
                [url]?client=gma&q=                    " Type the url, except the query
                                   <C-R>"              " Paste from the default register
                                         <CR>          " Execute the command, which opens the response
                                                       "   in a new buffer
                                             d3f"      " Delete through the first three quotation marks
                                                       "   This deletes everything before the suggestion
                                                 ;     " Repeat motion; this jumps to the next \"
                                                  D    " Delete everything from there, leaving only the suggestion
                                                   ]yy " unimpaired.vim C string unescape to handle escaped '

```

As far as running goes, it works fine if you save it to a file named `script` and run with `vim -s script input.txt` on macOS, at least. It doesn't work if you add `-u NONE`, but it works fine if my `.vimrc` is empty. I assume it is using something from the system `.vimrc` to make the URL stuff work. This means, however, that it doesn't work in V, so no TIO link.

Some more test cases:

```
'what' => 'whataburger'
'what ' => 'what time is it' (Seriously? People Google that?)

```

---

What I really need is a way to open a URL with spaces in it. Replacing them with `+` first is just too many bytes!
> 12 votes

# Answer
# Python + requests ~~121~~ ~~117~~ 103 bytes

```
from requests import*
lambda s:get("http://google.com/complete/search?client=gma&q="+s).json()[1][0][0]

```
> 7 votes

# Answer
# JavaScript, 109 Bytes

```
q=>fetch("//suggestqueries.google.com/complete/search?client=chrome&q="+q).then(r=>r.json()).then(r=>r[1][0])

```

`Promise`, you gotta love it, but man is it verbose! This answer uses `fetch()`, a promise-based fetch API present in modern browsers. Promises work by establishing handlers for async actions at the beginning, like callbacks, but better. The `.then()` takes a function which will be called with the result of the async action. `.then(r=>r.json())` uses the `.json()` response method to convert the text array to a manipulable variable, the second `.then()` just pulls the first response.

Usage:

```
S = q=>fetch("//suggestqueries.google.com/complete/search?client=chrome&q="+q).then(r=>r.json()).then(r=>r[1][0])

S("node.js").then(console.log); // Prints the result to the debug console

```
> 5 votes

# Answer
# PowerShell, 133 115 bytes

```
([net.webclient]::new().downloadstring("http://google.com/complete/search?client=gma&q=$_")|convertfrom-json)[1][0]

```

**Sample run**

**Windows CMD command line:**

```
powershell.exe -c "'code golf l'|%{([net.webclient]::new().downloadstring(""""http://google.com/complete/search?client=gma&q=$_"""")|convertfrom-json)[1][0]}"

```

**PowerShell console:**

```
'code golf l'|%{([net.webclient]::new().downloadstring("http://google.com/complete/search?client=gma&q=$_")|convertfrom-json)[1][0]}

```
> 1 votes

# Answer
# C#, 192 112 111 Bytes

Saved 80 Bytes thanks to @TheLethalCoder. Thanks for reformatting my code, I didn't know it was allowed to just leave off the surrounding Class and Method Body :)

Saved another Byte by replacing `gma` by `hp`, as it doesn't matter for the parsing and there is just some gibberish before the response body.

I litterally brute-forced the API to find `gma` and `hp`.

```
s=>new System.Net.WebClient().DownloadString("http://google.com/complete/search?client=hp&q="+s).Split('"')[3];

```
> 1 votes

# Answer
# Groovy, 122 bytes

```
{Eval.me(new URL("http://suggestqueries.google.com/complete/search?client=chrome&q="+it).text.split(",\\{")[0]+"]")[1][0]}

```

Basically:

1. Get the text from the end-point.
2. Remove the part with the brackets at the end, this isn't valid syntax.
3. Parse the remaining bit as a groovy array.
4. Grab the second element of the result array.
> 1 votes

# Answer
## R, 111 bytes

Long time since I last came here but giving it a shot:

```
jsonlite::fromJSON(readLines(url(paste0("http://google.com/complete/search?client=gma&q=",scan(,"")))))[[2]][1]

```

Using the package `jsonlite` to convert the string fetched from `readLines()` into a list object.

Subsequently extract the second element, e.g (gives a warning that we don't have to care about):

```
> jsonlite::fromJSON(readLines(url(paste0("http://google.com/complete/search?client=gma&q=",scan(,"")))))[[2]][1]
1: "how to"
2:
    Read 1 item
[[1]]
[1] "how to make slime"

Warning message:
    In readLines(url(paste0("http://google.com/complete/search?client=gma&q=",  :
                                incomplete final line found on 'http://google.com/complete/search?client=gma&q=how to'

```
> 1 votes

# Answer
## C#, 127 bytes

```
s=>new System.Net.WebClient().DownloadString("http://suggestqueries.google.com/complete/search?client=gma&q="+s).Split('"')[3];

```

Complete and formatted version:

```
static void Main()
{
    System.Func<string, string> f = s =>
        new System.Net.WebClient()
                      .DownloadString("http://suggestqueries.google.com/complete/search?client=gma&q="+s)
                      .Split('"')[3];

    System.Console.WriteLine(f("you"));
    System.Console.ReadLine();
}

```
> 0 votes

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


title: Find a User's SE Reputation

text:
# Question
Title: Find a User's SE Reputation
## Challenge

Given a SE user's ID, output the sum of their reputation from across all of the Stack Exchange networks the user has signed up to.

## Rules

If a user has 101 or less reputation on a site, count it as zero in the sum.

***You should not count Area 51 rep or hidden communities!!***

URL shorteners are disallowed.

## Examples

***Subject to change***

### User 3244989 (Beta Decay)

```
14141

```

### User 918086 (Dennis)

```
204892

```

### User 11683 (Jon Skeet)

```
1029180

```

## Winning

The shortest code in bytes wins.

# Answer
> 1 votes
# curl, grep and awk, 106 bytes

```
curl http://api.stackexchange.com/users/$1/associated|grep -o n\"[^,]*|awk -F: '$2>101{s+=$2}END{print s}'

```

It's dirty but seems to work well. I don't use `awk` often so I wouldn't be surprised if there was a way to golf the `grep` away with it.

# Answer
> 3 votes
## Python 2 (with Requests), 149 Bytes

```
from requests import*
lambda i,r="reputation":sum(u[r]for u in get("http://api.stackexchange.com/users/"+i+"/associated").json()["items"]if u[r]>101)

```

I requested the API, converted the API to JSON, then summed the reputation via a generator expression. The generator does remove accounts with less than 101 reputation.

Credit for improving the code: Jonathan Allan.

# Answer
> 1 votes
# R with httr, 146 Bytes

```
library(httr)
a=sapply(content(GET(paste0("http://api.stackexchange.com/users/",readline(),"/associated")))$items,'[[','reputation')
sum(a[a>101])

```

# Answer
> 0 votes
# JavaScript (ES6), ~~148~~ ~~143~~ ~~142~~ 141 bytes

```
u=>fetch(`//api.stackexchange.com/users/${u}/associated`).then(j=>j.json(s=0)).then(i=>(i.items.map(r=>s+=(r=r.reputation)>101&&r),alert(s)))

```

---

## Try it

```
f=

u=>fetch(`//api.stackexchange.com/users/${u}/associated`).then(j=>j.json(s=0)).then(i=>(i.items.map(r=>s+=(r=r.reputation)>101&&r),alert(s)))

i.addEventListener("submit",e=>{e.preventDefault();(v=+i.firstChild.value)&&f(v)})
```

```
<form id=i><input type=number><button>Calc.</button></form>
```

# Answer
> 0 votes
# Ruby 2.4, 136 + 20 = 156 bytes

Requires the `-rjson -rnet/http -n` flags. Input is from STDIN (no trailing newline). Ruby 2.4 is needed for `sum`.

```
p JSON.parse(Net::HTTP.get URI"http://api.stackexchange.com/users/#$_/associated")["items"].map{|i|i["reputation"]}.select{|i|i>101}.sum

```

---
Tags: code-golf, internet, stack-exchange-api
---


title: Tips for writing quines

text:
# Question
Title: Tips for writing quines
A is a program that produces output that's identical to the program's source code. On this website, we generally only care about proper quines (at the time of writing, the current definition is "some part of the output is encoded by a different part of the program").

What advice do you have for writing proper quines, or programs with quine-like properties? As usual, each tip should be in a different answer.

# Answer
## Take advantage of string formatting

One of the easiest ways to create a quine is to define a string, then put the string inside itself with string formatting.

```
s='s=%r;print s%%s';print s%s

```

So in this example Python quine, we declare a string with the first part equal to whatever is before the string `s=`, then we allow for the string to be inserted with formatting with `%r`, and finally we put what comes after the string to print and format it. The trailing newline is because `print` prints a trailing newline.

So the template is really this, in Python:

```
<A>'<A>%r<B>'<B>

```

To expand the existing quine with more code:

```
<more A>s='<more A>s=%r;print s%%s<more B>';print s%s<more B>

```
> 16 votes

# Answer
# Use `eval` to reduce the need to copy code

The majority of quines require two copies of the code; one to be executed, one as data. This can end up doubling the length of the source code, making it harder to maintain, and worsening the score if you're writing the quine for a competition.

Merging the two copies means that one piece of information needs to be used for two purposes. Trying to treat your code as data is often not possible, and is typically considered cheating when it is. Treating data as code, however, can be done in many languages via use of a builtin, typically called `eval`. As such, your quine basically consists of storing the main body of your quine in a variable (so that you can refer to it more than once), then evaluating that variable.

Here's an example of how this works (the example is written in Python, but something similar works in many other languages):

```
d='print("d="+repr(d)+"\\neval(d)")'
eval(d)

```
> 15 votes

# Answer
# Stringified functions

In several languages, function objects (or equivalent constructs) implicitly store their source code, and will return it when converted into a string. This allows compact quines without using string eval. A notable example of such a language is JavaScript:

```
function f(){console.log(f+"f()")}f()
```

This code defines and calls a function `f` that, when called, prints its own source code followed by a call to itself. The only part of the program that needs to be duplicated is the function call `f()`. Of course, the function body can include an arbitrary "payload" of code that will also be executed when the function is called.

---

A more compact version of the same trick works in the golfing languages GolfScript:

```
{".~"}.~

```

and CJam:

```
{"_~"}_~

```

Each of these quines first defines an anonymous code block (enclosed in braces), which behaves much like a function object in JavaScript: it can be executed, and if stringified, it returns its source code. The rest of the code (`.~` in GolfScript, or `_~` in CJam) then executes the block, while leaving a copy of it on the stack. The code inside the block then pushes a string onto the stack that repeats the code outside the block. When the interpreter exits, it automatically stringifies and prints everything left on the stack. As with the JavaScript example, these code blocks could also be made to carry and execute an arbitrary payload of additional code without having to duplicate it.
> 11 votes

# Answer
# Use string delimiters that nest without escaping

Often, one of the hardest parts about writing a quine is the escaping step. This is needed in almost every quine; the issue is that you're storing data somehow, and you need to replicate the code that stores the data in the quine's output. That code will contain an escaped form of the data, so the program will see an unescaped form, and you'll need to re-escape it.

The easiest way to handle the unescaping step is if the escaped and unescaped forms of the data differ only in the presence or absence of string delimiters. Escaping is thus a simple matter of adding a new pair of string delimiters around the string. Unfortunately, this can clearly only work if the string delimiters themselves can be expressed in the data without escaping.

Perl is a good example of a language where this trick works. Although its usual string delimiters are `"…"` or `'…'`, the less commonly used `q(…)` nests, allowing this sort of quine to be written:

```
$_=q($_=q(0);s/\d/$_/;print);s/\d/$_/;print

```

This is a code+data quine. `s///` is a regex string-replace operation; we use `0` as the marker, and match it within the regex as `\d` ("any digit"), to avoid using the marker more than once (although as another optimization, we could actually just have used `0` again, because Perl's `s///` only replaces the first occurrence by default). Note that there's no explicit escaping step needed here, as the `q(…)` delimiters can just be included literally in the data string.
> 10 votes

# Answer
# Code + data quines

The most general structure for a quine looks something like this pseudocode:

```
data = "*an escaped version of the entire program,
        with this string replaced with a marker*"
program = data.replace(
  *an expression that evaluates to the marker but doesn't mention it*,
  escaped(data))
print program;

```

This structure can be used to write a (fairly naive) quine in most languages. However, it tends to score fairly badly on most scoring systems, because you have to write the entirety of the program twice. However, most quine structures can be considered optimizations of this one.

There are some subtleties to this. In some languages, the hardest part of performing this operation is to write the escaping code; in many languages, producing the marker without mentioning its name is difficult; and in some esoteric languages, you'll have to invent your own sort of string literal. All three operations tend not to cause too much trouble, though.

For example, we can write a Python quine escaping a string using `repr`, and using the 2-character-sequence `x"` string (which is representable as `"x\""`, i.e. not using the sequence `x"` in the string representation of the string itself) as the marker:

```
d='d=x"\nprint(str.replace(d,"x\\"",repr(d)))'
print(str.replace(d,"x\"",repr(d)))

```
> 9 votes

# Answer
## Remember the Structure of a Quine

I like to think of quines as *three* parts, rather than 2:

* Part 1: Generate a data representation of parts 2 and 3.
* Part 2: Use the data to algorithmically print back part 1.
* Part 3: Decode the representation to print parts 2 and 3.

This can make it easier to think about quines. Here is a Python quine, with each line corresponding to a part:

```
s = "print(\"s = \" + repr(s))\nprint(s)"
print("s = " + repr(s))
print(s)

```

Sometimes, you use an `eval` or similar to remove duplication, but generally I have found that this helps in writing simple quines.

Let's take a look at two different Underload quines. This is the first:

```
(:aSS):aSS

```

The first part is `(:aSS)`, which generates the data representation. The second is `:aS`, which prints `(:aSS)`. The third part is `S`, which prints `:aSS`.

Here is the second quine:

```
(:aS(:^)S):^

```

At first, this doesn't seem to fit. But if you expand the quine, you get:

```
(:aS(:^)S):aS(:^)S

```

Now `(:aS(:^)S)` is part 1, `:aS` is part 2, and `(:^)S` is part 3.
> 7 votes

# Answer
# Exploit wrapping source code

In quite a few languages (mostly 2D languages), the source code can wrap around; under certain circumstances (e.g. in Befunge-98, if your program is a one-liner) going past the end of the program will take you back to the start of the program. This kind of nonlinear behaviour means that you can write code that's inside and outside a string literal at the same time; an unmatched `"` (or whatever the string delimiter is) will effectively give you a string containing the whole of the rest of the program (except for the `"` itself).

One problem with using this trick is that you'll get the string as seen from the point of view of the `"`, rather than from the start of the program (like you'd want). As such, it's likely easiest to rearrange the program so that the `"` appears at the start or end. This often means chopping your program up into multiple pieces and making use of whatever interesting/unusual flow control commands your language has (most languages which let string literals wrap around the program have a good selection of these).

A good example is @Justin's Befunge-98 quine:

```
<@,+1!',k9"

```

The unmatched `"` at the end of the program wraps the whole program in a string literal, so (running right to left due to the `<` at the start) all we have to do is output the program (`9k`), then output the double quote (`'!1+,`) and exit (`@`). This saves needing two copies of the program (one as code, one as data); the two copies are the same piece of code, just interpreted in different ways.
> 4 votes

---
Tags: tips, quine
---


title: Perfect Palindromes

text:
# Question
Title: Perfect Palindromes
Your task is to determine how much of a perfect palindrome a string is. Your typical palindrome (eg 12321) is a perfect palindrome; its perfectness is 1.

To determine the perfectness of a string, you see how many sections you can split it into where each section is a palindrome. If there are ambiguities, such as with `aaaa`, as you can split it into `[aa, aa]` or `[aaaa]` or `[a, aaa]` or `[aaa, a]`, the shortest set will override, giving `aaaa` a score of 1, which is the length of the shortest set.

Therefore, you must write a program or function that will take one non-empty input and output how perfect it is (which is the length of the shortest set you can split it into where each element in the set is a palindrome).

### Examples:

```
1111 -> 1 [1111]
abcb -> 2 [a, bcb]
abcbd -> 3 [a, bcb, d]
abcde -> 5 [a, b, c, d, e]
66a -> 2 [66, a]
abcba-> 1 [abcba]
x -> 1 [x]
ababacab -> 2 [aba, bacab]
bacababa -> 2 [bacab, aba]
26600 -> 3 [2, 66, 00] [my user id] [who has a more perfect user id?]
ababacabBACABABA -> 4 [aba, bacab, BACAB, ABA]

```

Note that in the examples anything in square brackets shouldn't be part of the output.

# Answer
# Brachylog, 7 bytes

```
~cL↔ᵐLl

```

Try it online!

### Explanation

```
~cL          Deconcatenate the input into L
  L↔ᵐL       Reversing all elements of L results in L
     Ll      Output = length(L)

```
> 14 votes

# Answer
# Jelly, ~~13~~ ~~12~~ 11 bytes

```
~~ŒṖLÞŒḂ€P$ÐfḢL~~
~~ŒṖLÞṚ€⁼$ÐfḢL~~
ŒṖṚ€⁼$ÐfL€Ṃ
ŒṖ            obtain partitions
      Ðf      filter for partitions which
  Ṛ€              after reversing each subpartition
    ⁼             is equal to the partition
        L€    length of each successful partition
          Ṃ   minimum

```

Try it online!

### Specs

* Input: `"ababacab"` (as argument)
* Output: `2`
> 9 votes

# Answer
# Pyth, 9 bytes

```
lh_I#I#./

```

Test suite

This forms all partitions of the input, from shortest to longest. Then, it filters those partitions on invariance under filtering the elements on invariance under reversal. Finally, we take the first element of the filtered list of partitions, and return its length.

To explain that complicated step, let's start with invariance under reversal: `_I`. That checks whether its input is a palindrome, because it checks whether reversing changes the value.

Next, filtering for palindromicity: `_I#`. This will keep only the palindromic elements of the list.

Next, we check for invariance under filtering for palindromicity: `_I#I`. This is truthy if and only if all of the elements of the list are palindromes.

Finally, we filter for lists where all of the elements of the list are palindromes: `_I#I#`.
> 6 votes

# Answer
# Haskell, 83 bytes

```
f s=minimum[length x|x<-words.concat<$>mapM(\c->[[c],c:" "])s,all((==)=<<reverse)x]

```

Try it online!

This uses Zgarb's great tip for generating string partitions.

```
f s = minimum[                               -- take the minimum of the list
    length x |                               -- of the number of partitions in x
    x<-words.concat<$>mapM(\c->[[c],c:" "])s -- where x are all partitions of the input string s
    , all((==)=<<reverse)x                   -- where each partition is a palindrome.
]

```
> 6 votes

# Answer
## JavaScript (ES6), ~~143~~ ~~126~~ 124 bytes

*Saved 2 bytes thanks to Neil*

Inspired by NikoNyrh method.

```
s=>(r=1/0,F=(s,i=1,p=0)=>s[p++]?([...o=s.slice(0,p)].reverse().join``==o&&(s[p]?F(s.slice(p),i+1):r=r<i?r:i),F(s,i,p)):r)(s)

```

### Formatted and commented

```
s => (                          // given a string 's':
  r = 1 / 0,                    // 'r' = best score, initialized to +Infinity
  F = (                         // 'F' is a recursive function that takes:
    s,                          //   - the current string 's'
    i = 1,                      //   - a substring counter 'i'
    p = 0                       //   - a character pointer 'p'
  ) =>                          //
    s[p++] ? (                  // if we haven't reached the end of the string:
      [...o = s.slice(0, p)]    //   compute 'o' = substring of length 'p'
      .reverse().join`` == o    //   if 'o' is a palindrome,
      && (                      //   then:
        s[p] ?                  //     if there are still characters to process:
          F(s.slice(p), i + 1)  //       do a recursive call on the remaining part
        :                       //     else:
          r = r < i ? r : i     //       update the score with r = min(r, i)
      ),                        //   in all cases:
      F(s, i, p)                //     do a recursive call with a longer substring
    ) :                         // else:
      r                         //   return the final score
  )(s)                          // initial call to F()

```

### Test cases

```
let f =

s=>(r=1/0,F=(s,i=1,p=0)=>s[p++]?([...o=s.slice(0,p)].reverse().join``==o&&(s[p]?F(s.slice(p),i+1):r=r<i?r:i),F(s,i,p)):r)(s)

console.log(f('1111'))      // -> 1 [1111]
console.log(f('abcb'))      // -> 2 [a, bcb]
console.log(f('abcbd'))     // -> 3 [a, bcb, d]
console.log(f('abcde'))     // -> 5 [a, b, c, d, e]
console.log(f('66a'))       // -> 2 [66, a]
console.log(f('abcba'))     // -> 1 [abcba]
console.log(f('x'))         // -> 1 [x]
console.log(f('ababacab'))  // -> 2 [aba, bacab]
console.log(f('bacababa'))  // -> 2 [bacab, aba]
```

---

## Initial approach, ~~173~~ 168 bytes

A pretty long recursive function that computes all possible partitions of the input string.

```
f=(s,b=1/(k=0))=>++k>>(L=s.length)?b:f(s,(k|1<<30).toString(2).slice(-L).match(/(.)\1*/g).some(m=>[...o=s.slice(i,i+=m.length)].reverse(n++).join``!=o,n=i=0)?b:b<n?b:n)

```

### Formatted and commented

```
f = (                           // given:
  s,                            //   - a string 's'
  b = 1 / (k = 0)               //   - a best score 'b' (initialized to +Infinity)
) =>                            //   - a counter 'k' (initialized to 0)
  ++k >> (L = s.length) ?       // if 'k' is greater or equal to 2^(s.length):
    b                           //   stop recursion and return 'b'
  :                             // else:
    f(                          //   do a recursive call:
      s,                        //     using the same string 's'
      (k | 1 << 30)             //     compute an array containing the groups of identical
      .toString(2).slice(-L)    //     digits in the binary representation of 'k', padded
      .match(/(.)\1*/g)         //     with leading zeros and cut to the length of 's'
      .some(g =>                //     for each group 'g' in this array:
        [... o = s.slice(       //       compute 'o' = corresponding substring of 's',
          i, i += g.length      //       starting at position 'i' with the same length
        )]                      //       (e.g. s = 'abcd' / k = 0b1101 => 'ab','c','d')
        .reverse(n++)           //       increment the number of groups 'n'
        .join`` != o,           //       return true if this substring is NOT a palindrome
        n = i = 0               //       initialize 'n' and 'i'
      ) ?                       //     if some() returns true:
        b                       //       invalid partition -> keep the previous score 'b'
      :                         //     else:
        b < n ? b : n           //       valid partition -> use min(b, n)
    )                           //   end of recursive call

```

### Test cases

```
f=(s,b=1/(k=0))=>++k>>(L=s.length)?b:f(s,(k|1<<30).toString(2).slice(-L).match(/(.)\1*/g).some(m=>[...o=s.slice(i,i+=m.length)].reverse(n++).join``!=o,n=i=0)?b:b<n?b:n)

console.log(f('1111'))      // -> 1 [1111]
console.log(f('abcb'))      // -> 2 [a, bcb]
console.log(f('abcbd'))     // -> 3 [a, bcb, d]
console.log(f('abcde'))     // -> 5 [a, b, c, d, e]
console.log(f('66a'))       // -> 2 [66, a]
console.log(f('abcba'))     // -> 1 [abcba]
console.log(f('x'))         // -> 1 [x]
console.log(f('ababacab'))  // -> 2 [aba, bacab]
console.log(f('bacababa'))  // -> 2 [bacab, aba]
```
> 5 votes

# Answer
## Clojure, 111 bytes

```
(defn f[s](if(=()s)0(+(apply min(for[i(range(count s))[a b][(split-at(inc i)s)]:when(=(reverse a)a)](f b)))1)))

```

Splits at all possible positions, and when the first part is a palindrome proceeds to find a partitioning for the remaining of the string.

Try it online.

Ungolfed, uses thread-last macro `->>`.

```
(defn f [s]
  (if (empty? s)
    0
    (let [results (for[i (range(count s))]
                      (let [[a b] (split-at (inc i) s)]
                         (when (= a (reverse a))
                           (f b))))]
      (->> results        ; Take results (a list of integers and nils),
           (filter some?) ; remove null values (they occur when "a" is not a palindrome)
           (apply min)    ; find the minium value,
           inc))))        ; and increment by one.

```

An obscure version, please do not write code like this :D

```
(defn f [s]
   (->> (f b)
        (when (= a (reverse a)))
        (let [[a b] (split-at (inc i) s)])
        (for[i (range(count s))])
        (filter some?)
        (apply min)
        inc
        (if (empty? s) 0)))

```
> 5 votes

# Answer
# Jelly, 10 bytes

```
ŒṖŒḂ€¬$ÞḢL

```

**Try it online!**

### How?

Uses the fact that
`[0]<[0,0]<[0,0,0],...,<[0,...,0,1]<...`
\- thus if we sort the partitions by a key "is not palindromic for each part" the first entry will be all palindromic and of minimal length.

*Note: any non-empty string of length **n** will always result in such a key with **n** zeros, since all length **1** strings are palindromic.*

```
ŒṖŒḂ€¬$ÞḢL - Main link: s             e.g. 'abab'
ŒṖ         - partitions of s               [['a','b','a','b'],['a','b','ab'],['a','ba','b'],['a','bab'],['ab','a','b'],['ab','ab'],['aba','b'],['abab']]
       Þ   - sort by (create the following key and sort the partitions by it):
      $    -   last two links as a monad:  (key evaluations aligned with above:)
  ŒḂ€      -     is palindromic? for €ach   [ 1 , 1 , 1 , 1 ] [ 1 , 1 , 0  ] [ 1 , 0  , 1 ] [ 1 , 1   ] [ 0  , 1 , 1 ] [ 0  , 0  ] [ 1   , 1 ] [ 0    ]
     ¬     -     not                        [ 0 , 0 , 0 , 0 ] [ 0 , 0 , 1  ] [ 0 , 1  , 0 ] [ 0 , 0   ] [ 1  , 0 , 0 ] [ 1  , 1  ] [ 0   , 0 ] [ 1    ]
           - ...i.e.:
           -       making the sorted keys: [[ 0 , 0   ],[ 0   , 0 ],[ 0 , 0 , 0 , 0 ],[ 0 , 0 , 1  ],[ 0 , 1  , 0 ],[ 1    ],[ 1  , 0 , 0 ],[ 1  , 1  ]]
           -  hence the sorted partitions: [['a','bab'],['aba','b'],['a','b','a','b'],['a','b','ab'],['a','ba','b'],['abab'],['ab','a','b'],['ab','ab']]
        Ḣ  - head of the result             ['a','bab']
         L - length                         2

```
> 5 votes

# Answer
## Haskell, 69 bytes

```
x!(a:b)|p<-a:x=p!b++[1+f b|p==reverse p]
x!y=[0|x==y]
f=minimum.(""!)

```

Defines a function `f`. Try it online!

## Explanation

The infix helper function `x ! y` computes a list of integers, which are the lengths of some splittings of `reverse x ++ y` into palindromes where `reverse x` is left intact. It is guaranteed to contain the length of the minimal splitting if `y` is nonempty. How it works is this.

* If `y` is nonempty, a char is popped off it and pushed into `x`. If `x` becomes a palindrome, we call the main function `f` on the tail of `y` and add 1 to account for `x`. Also, we call `!` on the new `x` and `y` to not miss any potential splitting.
* If `y` is empty, we return `[0]` (one splitting of length 0) if `x` is also empty, and `[]` (no splittings) otherwise.

The main function `f` just calls `"" ! x` and takes the minimum of the results.

```
x!(a:b)|          -- Function ! on inputs x and list with head a and tail b,
  p<-a:x=         -- where p is the list a:x, is
  p!b++           -- the numbers in p!b, and
  [1+f b|         -- 1 + f b,
   p==reverse p]  -- but only if p is a palindrome.
x!y=              -- Function ! on inputs x and (empty) list y is
  [0|             -- 0,
   x==y]          -- but only if x is also empty.
f=                -- Function f is:
  minimum.(""!)   -- evaluate ! on empty string and input, then take minimum.

```
> 5 votes

# Answer
## JavaScript (Firefox 30-57), 97 bytes

```
f=(s,t=``,i=0)=>s?Math.min(...(for(c of s)if([...t+=c].reverse(++i).join``==t)1+f(s.slice(i)))):0

```

ES6 port:

```
f=(s,t=``)=>s?Math.min(...[...s].map((c,i)=>[...t+=c].reverse().join``==t?1+f(s.slice(i+1)):1/0)):0
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

It seems such a simple solution that I keep thinking I've forgotten something but it does at least pass all the test cases.
> 3 votes

# Answer
# PHP, 319 Bytes

```
for(;$i<$l=strlen($s=$argn);$i++)for($j=$l-$i;$j;$j--)strrev($r=substr($s,$i,$j))!=$r?:$e[+$i][]=$r;uasort($e,function($a,$b){return strlen($b[0])<=>strlen($a[0])?:count($a)<=>count($b);});foreach($e as$p=>$v)foreach($v as$w){$s=preg_replace("#^(.{{$p}})$w#","$1".str_pad("",strlen($w),"ö"),$s,1,$c);!$c?:++$d;}echo$d;

```

Online Version

Expanded

```
for(;$i<$l=strlen($s=$argn);$i++)
for($j=$l-$i;$j;$j--)strrev($r=substr($s,$i,$j))!=$r?:$e[+$i][]=$r; #Make all substrings that are palindromes for each position
uasort($e,function($a,$b){return strlen($b[0])<=>strlen($a[0])?:count($a)<=>count($b);}); # sort palindrome list high strlen lowest count for each position
foreach($e as$p=>$v)
foreach($v as$w){
    $s=preg_replace("#^(.{{$p}})$w#","$1".str_pad("",strlen($w),"ö"),$s,1,$c);
    !$c?:++$d; # raise count
}
echo$d; # Output

```

Longer Version without E\_NOTICE and Output the resulting array
> 1 votes

# Answer
# Haskell, ~~139~~ ~~116~~ 109 bytes

```
h[]=[[]]
h x=words.concat<$>mapM(\c->[[c],c:" "])x
r x=reverse x==x
g x=minimum[length y|y<-h x,and$r<$>y]

```

Still green at Haskell golfing but here is my best attempt I can come up with quickly.

* h is a function that creates a List of all possible contiguous subsequences of a List (like a string). It takes the input String and breaks it out for g.
* r is a simple function that returns a Boolean for if a List is a palindrome
* g is the main function that takes an input List, calls h to get the list of contiguous subsequence possibilities, filters on `(and.map r)` to remove sub lists that do not contain a palindrome, at which point length is applied to the list, and then the result is sorted so we can grab the head which is the answer.

I was thinking a better answer might be able to leverage the non-deterministic nature of Lists in Haskell through the use of Applicatives. It might be possible to shave many bytes off of function h by using applicatives, even if we have to import Control.Applicative. Comments for improvement are welcome.

**UPDATE1**

Huge savings based on Laikoni's reminder about the minimum function. Removing sort actually allowed me to drop the Data.List import because minimum is defined in Prelude!

**UPDATE2**

Thanks to nimi's suggestion about using list comprehensions as a useful replacement for filter.map. That saved me a few bytes. Also I borrowed the neat String partition trick from Laikonis answer and saved a couple bytes there as well.
> 1 votes

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


# Question
Title: Calculate the sine of a float (in radians)…
…without using any operator/function besides addition (`+`), subtraction (`-`), multiplication (`*`), division (`/`), modulo (`%`), exponent/power `pow()` or any of the standard C bitwise operators (`<<, >>, ~, &, |, ^`) or unary operators (`—, ++`) or assignment/comparison operators (`=, ==`).

If these symbols represent a different operation in your chosen language, go with the spirit of the question and don't use them.

Rules:

* You cannot use any mathematical functions your language might offer (Mathematica, looking at you.)
* You cannot use any operator besides the bitwise operators or the arithmetic operators listed above.
* Your output should be a float and be correct to at least 2 decimal places when truncated/rounded.
* You can use constants your language's **standard libraries** might provide.
* You can hardcode the values, but your program should work correctly for all floats (up to 2 decimal places) between `0` and ;

This is code-golf, so the shortest answer wins.

Example:

```
Input: 3.141592653 / 2
Output: 1.00xxxxxx…

```

Please also post an ungolfed version of your code.

# Answer
> 7 votes
## Python 83 69

*Based on Bhaskara I's sine approximation formula*

**Implementation**

```
def f(x):p=3.14;x,s=x%p,(4,-4,4)[int(x/p)];return s/(12.34/x/(p-x)-1)

```

**Ungolfed**

```
def apxsine(radian):
    pi = 3.14 # Approximate to 2 decimal places
    sign = (4,-4,4)[radian % pi]
    return sign / (12.34/radian/(pi - radian) - 1))

```

**Deduction**

**Demo**

```
>>> from math import pi, sin
>>> any(round(abs(f(e) - sin(e)), 2) for e in (e/180.*pi for e in range(0,360)))
False

```

JUst realized that if I would have opted for Euler's formula route, the code would be shorter (49 characters). But then it uses Complex numbers and am not sure if the call to the real method would be valid in the current question context.

```
f=lambda x:((2.72**(x*1j)-2.72**(-x*1j))/2j).real

```

# Answer
> 5 votes
# Javascript 114 77

Using Taylor Series expansion at 0:

```
function s(y){
    var p=2*Math.PI,
        // z = sign (y)
        z=(y>0?1:-1),
        // x = (abs(y) mod 2 PI - PI) * sign(y) => put x in [-PI, PI] range
        x=-z*((z*y)%p-p/2),
        // u = x^2
        u=x*x;
        // return Taylor Expansion
        return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6);
}

```

Golfed (114):

```
function s(y){var z=(y>0?1:-1),p=2*Math.PI,x=-z*((z*y)%p-p/2),u=x*x; return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6);}

```

**Edit**

"Improved" for y in \[0,2PI\], golfed (77) :

```
function s(y){var x=3.14-y,u=x*x;return x*(1-(1-(1-(1-u/72)*u/42)*u/20)*u/6)}

```

Another version for more precision (varying k) :

```
function s(y){
    var p=2*Math.PI,
        // z = sign (y)
        z=(y>0?1:-1),
        // x = (abs(y) mod 2 PI - PI) * sign(y) => put x in [-PI, PI] range
        x=-z*((z*y)%p-p/2),
        // u = x^2
        u=x*x,
        // k = 2* expansion level +1
        k=9,
        // r = 1 initial value
        r = 1;

        // Taylor Expansion
        // while k > 1
        for(;k>1;) {
            r= 1 - r*u /k--/k--;
        }
        return x*r;
 }

```

Golfed (114):

```
function s(y){var z=(y>0?1:-1),p=2*Math.PI,x=-z*((z*y)%p-p/2),u=x*x,k=9,r=1;for(;k>1;)r=1-r*u/k--/k--;return x*r;}

```

# Answer
> 5 votes
## MATLAB 35

Too bad `e` is not a constant in Matlab. That would have saved me 10 characters. I will see if I can come up with a solution for this.

```
@(x)(2.7183^(x*i)-2.7183^(-x*i))/2i

```

# Answer
> 4 votes
# APL - 21

```
{|{.5×⍵-+⍵}0J1*⍵÷○.5}

```

This uses the fact that `sin pi*x/2 = Im[(-1)^x]`.

Example test on ngn APL

Previous answer: 26

```
{-/((×\9⍴⍵)÷×\1+⍳9)[2×⍳5]}

```

This uses the Taylor/Maclaurin series up to 9th term.

Example test on ngn APL

Note about operators: only operators used were `/\⍴⍳` which don't have anything to do with arithmetic, and are mostly list manipulation tools,  which is *multiply by pi*, and `+-×÷*` which are permitted by the rules

# Answer
> 4 votes
# C++ 80 68(excluding white-spaces + edit)

### GOLFED

```
float S(float x){float z=x*x,y=x*(5040-(840+(42-z)*z)*z)/5040;return y;}

```

### UNGOLFED

both versions are different so that, it is easy to get output.

```
#include<iostream>
int main()
{
    float x,y,z;
    for(;;)
    {
        std::cin>>x;
        z=x*x;
        y=(x*(5040-840*z+42*z-z*z*z))/5040;
        std::cout<<y<<'\n';
    }
}

```

### Output

```
1.047197 ((pie)/3)
0.865096 (sin((pie)/3) = 1.73201/2 = 0.8660)

```

# Answer
> 2 votes
## Haskell

```
import Prelude hiding (sin)
import Data.Complex
sin x=(\(_:+y) -> y) $ exp (0 :+ x)

```

Uses Euler's formula. `(y :+ z)=y+zi` I think.

# Answer
> 2 votes
## Javascript (56)

```
j=x=+prompt(r=0);for(i=1;i<99;j*=x/++i)r+=i&1?i&2?-j:j:0

```

Taylor series used here.
`x` is the input value, `r` is the result, `j` contains `x^i/i!`
The result is output in console.

```
x=prompt();
r=0;
j=1;
for(i=1;i<99;i++) {
  j=j*x/i;
  if (i%2) {
    if (i%4 == 1) r+=j;
    else r-=j;
  }
}
alert(r);

```

If evaluation is needed for input (for example `3.141592653 / 2`) :

```
j=x=eval(prompt(r=0));for(i=1;i<99;j*=x/++i)r+=i&1?i&2?-j:j:0

```

# Answer
> 2 votes
# Python, 70 bytes

Using sin(x) = Im(exp(ix)) and the series for the exponential function:

```
def s(x):
    s,f=0,1
    for i in range(1,50):f*=1j*x/i;s+=f
    return s.imag

```

Note that `imag` is not a function here, strictly speaking.

Ungolfed:

```
def s(x):
    s = 0
    f = 1
    for i in range(1,50):
        f *= 1j*x/i
        s += f
    return s.imag

```

# Answer
> 1 votes
### R, 80 chars

```
f=function(x){a=seq(1,99,2);sum((-1)^(0:49)*(x^a)/sapply(mapply(`:`,1,a),prod))}

```

Uses Taylor approximation at an order of 99. `sapply` and `mapply` are just functions to vectorize the operation, while `sum` and `prod` are just vectorized `+` and `*`.

```
> b=seq(0,2*pi,1e5)
> all((f(b)-sin(b))<.01)
[1] TRUE

```

If the `*apply` functions are a problem, here is a solution at 91 characters:

```
f=function(x){a=0:100;b=c();for(i in 1:50)b[i]=(-1)^(i-1)*(x^a[2*i])/prod(1:a[2*i]);sum(b)}

```

# Answer
> 1 votes
# C 70

This one is not only golf but also useful in microcontrollers without floating point instructions or math libraries:

```
float S(float a){float x,y=1,h=1e-4;while(x+=h*(y-=h*x),(a-=h)>0);return x;}

```

Of course, the majority of the characters is taken by these annoyingly long type declarations and return. If the function declaration doesn't count, it's much shorter. If we take the value by pointer and overwrite it (removing the return statement), we get 71 characters.

```
S(float*x){float a=*x,y=1,h=1e-4;*x=0;while(*x+=h*(y-=h**x),(a-=h)>0);}

```

However, it complains about default return value.

EDIT: 70, for is shorter:

```
S(float*x){float a=*x,y=1,h=1e-4;*x=0;for(;(a-=h)>0;*x+=h*(y-=h**x));}

```

EDIT2: forgot ungolfed version

```
float fake_sin(float a){
   float x=0,y=1;
   float h=1e-4;//adjust for accuracy
   while(a>0){
      y-=h*x;
      x+=h*y;
      a-=h;
   }
   return x;//return y for cosine or y/x for tangent
}

```

It takes arbitrary positive angle, but doesn't work for negative.

# Answer
> 1 votes
## Java - 108 / 81

```
float s(float p){for(float q=p-=3.14,d=p=-p,i=1,m=1;i<11;)p+=(q*=d*d)/(m*=++i*++i)*(((int)i&2)-1);return p;}

```

Without the function declaration, it's just doing `p = sin(p)`:

```
for(float q=p-=3.14,d=p=-p,i=1,m=1;i<11;)p+=(q*=d*d)/(m*=++i*++i)*(((int)i&2)-1);

```

The error is max ±0.00201 in the range 0..2π, much worse in either direction.

Ungolfed:

```
float s(float p) {
    for (float q = p -= 3.14, d = p = -p, i = 1, m = 1; i < 11;)
        p += (q *= d * d) / (m *= ++i * ++i) * (((int)i & 2) - 1);
    return p;
}

```

Unobfuscated:

```
float sin(double ph) {
    float [] dividers = {-1, 6, -120, 5040, -362880, 39916800L};
    ph -= Math.PI;
    double d = 0;
    for (int i = 0; i < 6; i++)
        d += Math.pow(ph, i * 2 + 1) / dividers[i];
    return d;
}

```

# Answer
> 1 votes
# C# - 115 103

This code uses an approximation of Maclaurin series calculation of the sine of x, and is accurate to 7 decimal places.

`float x=0;for(int i=1;i<96;i+=2){float n=i,d=1,p=a;while(n>1){d*=n;n--;p*=a;}x+=((i+1)%4==0?-1:1)*p/d;}`

Where `a` is the input in radians.

Here's the code with whitespaces:

```
float x = 0; for (int i = 1; i < 96; i += 2)
{
    float n = i, d = 1, p = a;
    while (n > 1)
    {
        d *= n;
        n--;
        p *= a;
    }
    x += ((i+1)%4==0?-1:1)*p / d;
}

```

# Answer
> 0 votes
# TI-84 BASIC, 21 bytes

```
(e^(iAns)-e^(⁻iAns))/2i

```

# Answer
> 0 votes
# Perl 6, ~~17~~ 16 bytes

```
{(e**(i*$_)).im}

```

# Answer
> 0 votes
# Axiom, 139 bytes

```
s(x:Float):Complex Float==(digits()>20=>%i;x>2*%pi=>s(x-2*%pi);x< -2*%pi=>s(x+2*%pi);imag(reduce(+,[(%i*x)^k/factorial(k)for k in 0..40])))

```

I see this formula in the other solutions and I inplemented it in Axiom... The formula i follow is this:

```
                               +oo
                               ----
                               \      (i*x)^k
sin(x)=ImPart(e^(i*x))=imPart( /     --------  )
                               ----k     k!
                                 0

```

ungolf

```
sin1(x:Float):Complex Float==
              digits()>20=>%i
              x>  2*%pi  =>sin1(x-2*%pi)
              x< -2*%pi  =>sin1(x+2*%pi)
              imag(reduce(+,[(%i*x)^k/factorial(k)for k in 0..40]))

```

there is some problem for the last 2 digits each number; some test cases:

```
(79) -> [-23, numeric(sin(-23)), s(-23) ]
   (79)  [- 23.0,0.8462204041 7517063524,0.8462204041 7517063514]
                                                 Type: List Complex Float
(80) -> [ 23, numeric(sin( 23)), s( 23) ]
   (80)  [23.0,- 0.8462204041 7517063524,- 0.8462204041 7517063536]
                                                 Type: List Complex Float
(81) -> [[x/2,numeric(sin(x/2)),s(x/2)] for x in 0..(7*2)]
   (81)
                  1
   [[0,0.0,0.0], [-,0.4794255386 0420300027,0.4794255386 0420300027],
                  2
    [1,0.8414709848 0789650665,0.8414709848 0789650665],
     3
    [-,0.9974949866 0405443094,0.9974949866 0405443093],
     2
    [2,0.9092974268 256816954,0.9092974268 256816954],
     5
    [-,0.5984721441 0395649405,0.5984721441 0395649405],
     2
    [3,0.1411200080 598672221,0.1411200080 5986722208],
     7
    [-,- 0.3507832276 8961984812,- 0.3507832276 8961984817],
     2
    [4,- 0.7568024953 0792825138,- 0.7568024953 0792825139],
     9
    [-,- 0.9775301176 6509705539,- 0.9775301176 6509705545],
     2
    [5,- 0.9589242746 6313846889,- 0.9589242746 6313846888],
     11
    [--,- 0.7055403255 7039190623,- 0.7055403255 7039190626],
      2
    [6,- 0.2794154981 9892587281,- 0.2794154981 9892587545],
     13
    [--,0.2151199880 878155243,0.2151199880 878155243],
      2
    [7,0.6569865987 187890904,0.6569865987 1878909041]]
                                                      Type: List List Any

```

---
Tags: code-golf
---


title: Backwards and forwards polyglot quine!

text:
# Question
Title: Backwards and forwards polyglot quine!
You must make a polyglot that outputs its source code in one language and its source code *backward* in another. Unlike the normal rules, you are allowed to read the current file or use a builtin to get the source code of your submission and reverse that in one language. **Your source code cannot be a palindrome.**

For example, if your source code is `abcxyz`, it must output `abcxyz` in one language and `zyxcba` in another. If your code is `abcxyzyxbca`, it's invalid because it's a palindrome.

Good luck!

# Answer
## PHP & GolfScript, 2 bytes

```

1

```

i.e. a newline and the digit 1.

This is a reverse quine in GolfScript, contributed on this site by Justin. PHP hasn't triggered that it's a programming language so it prints its input.
> 4 votes

# Answer
## Batch / bash + tac, 39 bytes

```
:;tac -r -s '.\|'$'\n' $0;exit
@type %0

```

Outputs forwards in Batch. Explanation: Batch sees the first line as a label and ignores it, while the second line simply copies the source file to STDOUT. (Note that you need to invoke the file including extension, or change `%0` to `%~f0`.) `bash` sees four commands:

* `:` does nothing (same as `true`)
* `tac -r -s '.\|'$'\n' $0`
    + `-r` puts `tac` into regex mode
    + `-s` specifies a regex
    + `'.\|'$'\n'` is the regex, composed of
        - `.` any character except newline
        - `\|` or
        - `$'\n'` a newline
    + The upshot is that `tac` splits the file into characters rather than lines.
* `exit` stops the script, ignoring the fourth command
* `@type %0` (ignored)
> 5 votes

# Answer
# Python 2 / Python 3, 71 bytes

```
lambda _='lambda _=%r:(_%%_)[::int(1-(1/2)*4)]':(_%_)[::int(1-(1/2)*4)]

```

Does not use any quine builtins.

Thanks to ovs for generally awakening me.
> 5 votes

# Answer
# JS (ES5), JS (ES6), 94 bytes

```
function f(){try{eval("x=(f+'f()').split``.reverse().join``")}catch(e){x=f+"f()"};return x}f()

```

Does not use any quine built-ins. Just uses the fact that JS functions stringify to their code. Probably can be golfed more.
> 2 votes

# Answer
# PHP & Retina, 2 bytes

```

1

```

The same as Gille's PHP & GolfScript answer.

PHP just reads the code and outputs it directly, Retina will replace matches of an empty string in the input and replace it with 1, and output that with a newline.
> 2 votes

# Answer
If you allow reading the source code, it isn't really a quine.

## PHP & sh+util-linux, 6 bytes

```
rev $0

```

I'm sure that the usual golfing languages can do it in 2 bytes.
> 0 votes

---
Tags: code-golf, quine, polyglot
---


title: Disconnect 4 bits

text:
# Question
Title: Disconnect 4 bits
Your task: given an input string, determine whether the binary representation of that string does not have 4 `1`s or `0`s in a row, anywhere. Furthermore, your code itself should not contain any such runs of four in a row.

## Test Cases

```
String      Binary              Result

U3          01010101 00110011   Truthy

48          00110100 00111000   Falsy

Foobar      01000110 01101111   Falsy
            01101111 01100010
            01100001 01110010

Feeber      01000110 01100101   Truthy
            01100101 01100010
            01100101 01110010

$H          00100100 01001000   Truthy

<Empty>     -                   Truthy

```

## Rules

* Input will always be within the range of printable ASCII, including whitespace characters.
    + Your code may use any encoding, since it only matters at the bit level.
* Because this condition prevents the use of white space and many other chars, your code actually *can* contain such runs of four in a row, at a 10 byte penalty for each run.
    + A run of 5 `1`s or `0`s counts as two runs, 6 in a row counts as three runs, etc.
* Input will be a string or char array, not any other form.
* You may write a complete program or function.
* You must provide the binary representation of your code in your answer.

Good luck, lowest score wins!

This script might help you with your challenge, put your code in the input and it will give you your code's binary representation, it's length, your penalty, and the total score, if you're using UTF-8.

## Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

```
/* Configuration */

var QUESTION_ID = 111758; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 60042; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/<a/.test(lang)) lang = jQuery(lang).text();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# Jelly, 18 bytes \+ 0 penalties = 18

```
79Ọv2;$ḅ⁹b2+4\b4FẠ

```

Returns `1` if there are no equal bit strings of length **4** or more in the 8-bit word representation of the ASCII string input, and `0` otherwise.

**Try it online!** (test suite with some extra cases added)

Using Jelly's codepage there are no length 4 or longer substrings of equal bits:

```
7    0x37    00110111
9    0x39    00111001
Ọ    0xB5    10110101
v    0x76    01110110
2    0x32    00110010
;    0x3B    00111011
$    0x24    00100100
ḅ    0xD4    11010100
⁹    0x89    10001001
b    0x62    01100010
2    0x32    00110010
+    0x2B    00101011
4    0x34    00110100
\    0x5C    01011100
b    0x62    01100010
4    0x34    00110100
F    0x46    01000110
Ạ    0xAB    10101011

```

With equal-bit run lengths of:

```
221323221211111312322133122121221111213121123132213111122211311332313211313211111112

```

### How?

Tricks to avoid demerits are:

* to avoid the "convert from character to ordinal" monad `O` by converting the number `79` to a character using  followed by an "evaluation of Jelly code with input", `v`.
* to avoid direct conversion to binary using `B` (`0x42`, `1000010`) by the simple two-byte alternative `b2` using the generic dyadic base conversion.
* to avoid a few normal choices for counting the runs of equal bits - first choice would be "all overlapping slices of given length",  (`0xF5` or `11110101`). A second choice might be to utilise "all sublists",  (`0xCF` or `11001111`).
A workaround I used before the current one was to take the increments (between consecutive elements) with `I` (putting zeros and ones on an equal footing), and to look for any occurrence of three zeros in a row. To do that I converted all the zeros to ones by use of the binomial function with `2c` i.e. **2Cx** \- making the `-1`s become `0`s the `1`s become `2`s, and the `0`s become `1`s; that way the code can look for the first occurrence of the sublist `[1,1,1]` with `w111`.
However a shorter way became apparent - to mimic the action of "all overlapping slices of given length", , one can use a **4**-wise overlapping reduce with some dyad, `<dyad>4\`. If this is performed with addition, `+4\`, it counts the `1`s, so then any `0` or `4` being present is the indicator to return a truthy value. The issue here is that the next obvious step would be to take the modulo **4** of that to put the `0` and `4` entries on an equal footing while leaving the other possible values (`1`, `2`, and `3`) unchanged, but `+\%4` has `\%` inside, which has bit-value 010111**0000**100100. In order to avoid that penalty the numbers are all converted to base **4** with `b4` (mapping `0` to `[0]`, `1` to `[1]`, `2` to `[2]`, `3` to `[3]`, and `4` to `[1,0]`) and the whole list is flattened with `F`. Now the last test is simply to check if there are any `0`s in the list, achievable directly with the monad .

```
79Ọv2;$ḅ⁹b2+4\b4FẠ - Main link: printable ASCII character list
79                 - 79
  Ọ                - character from ordinal : 'O'
   v               - evaluate as Jelly code : input -> 'O' converts the input to ordinals
      $            - last two links as a monad
    2              -     2
     ;             -     concatenate (why? see the note beneath the code block)
       ḅ⁹          - convert from base 256 : gets an integer representing the byte string
         b2        - convert to base 2 AKA binary
            4\     - 4-wise reduce with
           +       -     addition (sums all overlapping slices of length 4)
              b4   - convert to base 4 (vectorises)
                F  - flatten into a single list
                 Ạ - any falsy?

```

Note: The reason a **2** is concatenated with the ordinal list is to deal with the edge cases where the only run of **4** in the input string is in the leading zeros of the very first character - these characters are: tab; line-feed; and carriage-return. Without this the base 256 conversion effectively strips leading zeros from the (fully concatenated) binary string; with the leading **2** the leading zeros will be there and an extra one and zero before them. Since no printable ASCII has exactly three leading zeros there is no need to discard these extra bits before the rest of the check.
> 19 votes

# Answer
# Java 7, ~~812~~ ~~726~~ ~~673~~ ~~644~~ ~~634~~ ~~616~~ ~~599~~ ~~588~~ 145 bytes + 10\*44 = 585

```
boolean
b(char[]b){String
g="";for(char
c:b)g+=g.format("%"+(1-1)+"8d",new
Integer(Integer.toString(c,2)));return!g.matches(".*(.)\\1\\1\\1.*");}

```

I am using newlines instead of spaces to try to minimize penalty...

Try it online!

### Binary

```
01100010011011110110111101101100011001010110000101101110000010100110001000101000011000110110100001100001011100100101101101011101011000100010100101111011010100110111010001110010011010010110111001100111000010100110011100111101001000100010001000111011011001100110111101110010001010000110001101101000011000010111001000001010011000110011101001100010001010010110011100101011001111010110011100101110011001100110111101110010011011010110000101110100001010000010001000100101001000100010101100101000001100010010110100110001001010010010101100100010001110000110010000100010001011000110111001100101011101110000101001001001011011100111010001100101011001110110010101110010001010000100100101101110011101000110010101100111011001010111001000101110011101000110111101010011011101000111001001101001011011100110011100101000011000110010110000110010001010010010100100101001001110110111001001100101011101000111010101110010011011100010000101100111001011100110110101100001011101000110001101101000011001010111001100101000001000100010111000101010001010000010111000101001010111000101110000110001010111000101110000110001010111000101110000110001001011100010101000100010001010010011101101111101

```

## Old bitshifting solution 141 bytes + 10\*101 = 1,151

```
boolean
b(char[]b){
int
o=0,p=0,i;
for(char
c:b){for(i=0;i<8;){if((c&(1<<i++))<1){o=0;p++;}else{p=0;o++;}if(3<o|3<p)return
6<5;}}return
5<6;}

```

Try it online!

### Binary

```
011000100110111101101111011011000110010101100001011011100000101001100010001010000110001101101000011000010111001001011011010111010110001000101001011110110000101001101001011011100111010000001010011011110011110100110000001011000111000000111101001100000010110001101001001110110000101001100110011011110111001000101000011000110110100001100001011100100000101001100011001110100110001000101001011110110110011001101111011100100010100001101001001111010011000000111011011010010011110000111000001110110010100101111011011010010110011000101000001010000110001100100110001010000011000100111100001111000110100100101011001010110010100100101001001111000011000100101001011110110110111100111101001100000011101101110000001010110010101100111011011111010110010101101100011100110110010101111011011100000011110100110000001110110110111100101011001010110011101101111101011010010110011000101000001100110011110001101111011111000011001100111100011100000010100101110010011001010111010001110101011100100110111000001010001101100011110000110101001110110111110101111101011100100110010101110100011101010111001001101110000010100011010100111100001101100011101101111101

```
> 11 votes

# Answer
# APL (Dyalog Classic), 26 + 1 × 10 = 36 bytes

### Notes

Contains one 4-run of 1s. Requires `⎕IO←0` which is default on many systems. Note that this *must* be run on a Classic interpreter so that strings are one byte per character.

### Submission

`1≠⊃⌽⌈\∊(×4\¨⍳≢⍬⍬)⍷¨⊂11⎕DR⍞`

Try it online!

### Binary source

0011000110101100100111001011001010010111010111001011100100101000110101110011010001011100101010001011110010111011101010111010101100101001101110101010100010011011001100010011000110001100010001000101001010001101

### Explanation

Prompt for string input

`11 ⎕DR` convert to **1**-bit Boolean (**1**) **D**ata **R**epresentation

enclose so we can apply multiple things to it

`(``) ⍷¨` binary indicators where each of the following sequences begin…

`×` sign (no-op on binary data, but included as spacer to split runs)

`4 \¨` expand (copy) each to length four

the integers up to

the tally of

`⍬⍬` the list consisting of two empty numeric lists

enlist (flatten)

`⌈\` cumulative maximum

reverse

pick the first

`1 ≠` is one different from? (i.e. NOT)

### Walk-through

We will input "48" to the ungolfed un-de-runned version `~ ∨/ ∊ (0 0 0 0)(1 1 1 1) ⍷¨ ⊂ 11 ⎕DR ⍞`:

`11 ⎕DR ⍞` converts "48" to 0 0 1 1 0 1 0 0 0 0 1 1 1 0 0 0 (i.e. Dec 52 56, Hex 34 38)

`(0 0 0 0)(1 1 1 1) ⍷¨ ⊂` finds beginnings of 0-runs and 1-runs; (0 0 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 0 0 0 0 0)

`∨/ ∊` looks if there is any Truth (i.e. any runs); 1

`~` negates that; 0
> 9 votes

# Answer
# Jelly 28 + 140 demerits = 168

```
L8_0xṭ
OBUÇ€UFŒr<4FẠ

```

# Explanation

```
OB

```

Converts the argument to a list of their binary encodings, e.g.

```
“U3”OB -> [[1, 0, 1, 0, 1, 0, 1], [1, 1, 0, 0, 1, 1]]

```

The next piece

```
UÇ€U

```

fixes the fact that the above list can be missing characters as `B` does not include leading zeros. `Ç€` calls the previously defined link over each element which restores that

```
L8_0xṭ

```

This link is equivalent to

```
lambda x: x + repeat(0, 8 - len(x))

```

For example

```
[1, 1, 0, 0, 1, 1] L8_0xṭ -> [1, 1, 0, 0, 1, 1, [0, 0]]

```

We upend the list before and after this operation (the two `U` calls in that list) to get that to be a prepend rather than an append. The next piece

```
FŒr

```

Flattens the list (`F`), giving the total binary string of the ASCII encoding, and run-length encodes the output (`Œr`). So for example

```
L8_0xṭ
“U3”OBUÇ€UF -> [1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0]

```

and

```
L8_0xṭ
“U3”OBUÇ€UFŒr -> [[1, 1], [0, 1], [1, 1], [0, 1], [1, 1], [0, 1], [1, 1], [0, 1], [1, 2], [0, 2], [1, 2], [0, 2]]

```

Finally we check whether each element is \< 4 (thankfully this is always true for 0,1) with

```
<4F

```

For example

```
L8_0xṭ
“U3”OBUÇ€UFŒr<4F -> [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

```

Finally

Returns 0 if any of those are falsy (in this case, 0).

# Code Pages

In Jelly's code page this code is 20 bytes but has 27 runs worth of rule violations. In UTF-8 it is 28 bytes but with only 14 runs worth of violations.
> 4 votes

# Answer
# 05AB1E, 22 + 3 * 10 = 52

Saved 2 penalty runs borrowing the *delta* trick from *Jonathan Allan's* Jelly answer

```
$Ç256+bvy¦}J¥J6Ìb¦å2ÍQ

```

Try it online!

**Explanation**

```
$                       # push 1 and input (1 to handle the empty string)
 Ç                      # convert to list of ascii values
  256+                  # add 256 to each
      b                 # convert each to binary
       vy¦}             # chop off the leading digit of each
           J            # join to string
            ¥           # take delta's
             J          # join to string
              6Ìb¦      # push bin(6+2)[1:] = 000
                  å     # check if this exists in the delta's string
                   2ÍQ  # compare to 2-2 = 0

```

**Binary representation of the code**

```
00100100 11000111 00110010 00110101 00110110 00101011 01100010 01110110
01111001 10100110 01111101 01001010 10100101 01001010 00110110 11001100
01100010 10100110 11100101 00110010 11001101 01010001

```

The 3 penalty runs come from `vy¦}` which is used to chop off the first byte in each binary string, but it's still cheaper than the 4 runs we'd get from the shorter `€¦`.
> 3 votes

# Answer
# Perl, 33 + 160 = 193

32 bytes of code + 1 byte for `-n` flag.

```
$_=unpack"B*";print!m+(.)\1\1\1+

```

(the input needs to be supplied without final newline. The *Try it online* link has `-l` flag on to remove newlines, but for a single input, it's not needed).

Try it online!

xxd dump :

```
00000000: 00100100 01011111 00111101 01110101 01101110 01110000  $_=unp
00000006: 01100001 01100011 01101011 00100010 01000010 00101010  ack"B*
0000000c: 00100010 00111011 01110000 01110010 01101001 01101110  ";prin
00000012: 01110100 00100001 01101101 00101011 00101000 00101110  t!m+(.
00000018: 00101001 01011100 00110001 01011100 00110001 01011100  )\1\1\
0000001e: 00110001 00101011                                      1+

```

A few notes:

* `(.)\1\1\1` saves a few penalties over `(.)\1{3}`, `1111|0{4}` or any other regex I could think of (using `0` or `{}` comes at a heavy cost).
* `print` saves ~8 points over using `-p` and `$_=` because `p` contains a run of 4 `0` while `n` doesn't.
* `+` as a delimiter for the regex saves a run of `1` that is in `/`.
* doing two steps instead of one with `!~` saves two runs (`~` is `01111110` in binary).
* `unpack"B*"` is quite expensive (4 runs), but I couldn't find cheaper (solutions bases on `ord` will be even more expensive).
> 3 votes

# Answer
# PHP, 98 + 270 = 368 bytes

I wanted to take a different approach from what Titus proposed, and ended with a slightly longer, yet less penalized program.

```
$v=unpack('H*',$argv[1]);$e=base_convert($v[1],16,2);echo!stristr($e,'0000')&&!stristr($e,'1111');

```

Outputs `1` for truthy, nothing for falsey.

Try it here !

**Binary-encoded :**

```
0010010001110110001111010111010101101110011100000110000101100011011010110010100
0001001110100100000101010001001110010110000100100011000010111001001100111011101
1001011011001100010101110100101001001110110010010001100101001111010110001001100
0010111001101100101010111110110001101101111011011100111011001100101011100100111
0100001010000010010001110110010110110011000101011101001011000011000100110110001
0110000110010001010010011101101100101011000110110100001101111001000010111001101
1101000111001001101001011100110111010001110010001010000010010001100101001011000
0100111001100000011000000110000001100000010011100101001001001100010011000100001
0111001101110100011100100110100101110011011101000111001000101000001001000110010
1001011000010011100110001001100010011000100110001001001110010100100111011

```

(22 occurences of `0000` and 5 occurrences of `1111`, hence 270 bytes of penalty)
> 3 votes

# Answer
# PHP, 86 bytes+370=456

```
for(;$c=ord($argn[$i++]);)$s.=sprintf("%08b",$c);echo!preg_match("#(.)\\1\\1\\1#",$s);

```

creates the binary string and uses a regex to detect streaks. Output is `1` for truthy; empty for falsy.

Run with `echo '<string>' | php -nR '<code>'`.

**tweaks**

* backreferences save 100 penalty for 3 bytes. (-97 score)

**abandoned ideas**

* `join(array_map(str_split()))` would cost 31 bytes and 90 penalty
* and `<?=`/`$argv[1]` instead of `echo`/`$argn` cost another 2+40.
* `str_pad(decbin())` is costlier than `sprintf`: 7 bytes and 110 penalty.
* `strtr` saves 80 penalty for 13 extra bytes, but backreferences are better.
* Grouping the backreferences `#(.)\\1{3}` saves 3 bytes, but adds 10 penalty.
* `foreach` costs 3+50.
* No saving possible on the variable names.
* output buffering costs 42+120.
> 2 votes

# Answer
# MATL, 16 bytes + 60 = 76 bytes

```
8&B!1e&Y'tgw4<Z&

```

Try it at **MATL Online**
> 2 votes

# Answer
# JavaScript (ES8), 91 bytes + 430 penalty = 521 total

This will output `1` for `true` and `0` for `false`.

```
s=>1-/(.)\1\1\1/.test([...s].map(c=>c.charCodeAt().toString(2).padStart(3+5,1-1)).join(""))

```

```
01110011001111010011111000110001001011010010111100101000001011100010100101011100001100010101110000110001010111000011000100101111001011100111010001100101011100110111010000101000010110110010111000101110001011100111001101011101001011100110110101100001011100000010100001100011001111010011111001100011001011100110001101101000011000010111001001000011011011110110010001100101010000010111010000101000001010010010111001110100011011110101001101110100011100100110100101101110011001110010100000110010001010010010111001110000011000010110010001010011011101000110000101110010011101000010100000110011001010110011010100101100001100010010110100110001001010010010100100101110011010100110111101101001011011100010100000100010001000100010100100101001

```

---

## Try it

```
f=

s=>1-/(.)\1\1\1/.test([...s].map(c=>c.charCodeAt().toString(2).padStart(3+5,1-1)).join(""))

console.log(f("U3"))
console.log(f("48"))
console.log(f("Foobar"))
console.log(f("Feeber"))
console.log(f("$H"))
console.log(f(""))
```
> 2 votes

# Answer
## CJam, 23 bytes

*Uses Jonathan Allan's idea to work with deltas.*

```
1q256b2b2ew::-[TTT]#)g-

```

Try it online!

Binary representation:

```
00110001011100010011001000110101
00110110011000100011001001100010
00110010011001010111011100111010
00111010001011010101101101010100
01010100010101000101110100100011
001010010110011100101101

```

Explanation:

```
1     e# Push a 1 for (much) later, because we can't use ! for logical NOT.
q     e# Read input.
256b  e# Treat characters as base 256 digits.
2b    e# Convert to binary. The last two steps together give us a flat binary
      e# representation of the input, avoiding both :~ and e_ for flattening.
2ew   e# Get all pairs of consecutive bits.
::-   e# Compute their differences.
[TTT] e# Push [0 0 0].
#     e# Find its index in the list of differences, or -1 if not found.
)g    e# Increment and take signum. We've now got the result we want but
      e# with the wrong truth value.
-     e# Subtract it from the 1 we pushed earlier to negate the truth value.

```
> 1 votes

# Answer
## JavaScript (ES6), ~~87~~ 88 + ~~390~~ 380 = ~~477~~ 468 bytes

```
s=>1-/(.)\1\1\1/.test(s.replace(/[\S\s]/g,c=>(256+c.charCodeAt()).toString(2).slice(1)))

```

In binary:

```
01110011001111010011111000110001001011010010111100101000001011100010100101011100001100010101110000110001010111000011000100101111001011100111010001100101011100110111010000101000011100110010111001110010011001010111000001101100011000010110001101100101001010000010111101011011010111000101001101011100011100110101110100101111011001110010110001100011001111010011111000101000001100100011010100110110001010110110001100101110011000110110100001100001011100100100001101101111011001000110010101000001011101000010100000101001001010010010111001110100011011110101001101110100011100100110100101101110011001110010100000110010001010010010111001110011011011000110100101100011011001010010100000110001001010010010100100101001

```

Over half of the penalty is down to zeros in the overlap between bytes, rather than the runs in the following characters: `=>//pa//=>aCoAo`.

Since the `/`s (`00101111`) pay a penalty I tried a) switching from `test` to `match` b) switching from `replace` to `map` but the score always ended up higher. However I did find that `[\S\s]` was an improvement over `[^]`. Edit: Saved 9 bytes overall thanks to @Shaggy.
> 1 votes

# Answer
# JavaScript, 173 + 89 * 10 = 1063

JavaScript is not good at converting strings to binary, but I figured I'd give this challenge a shot just for fun.

### Code:

```
function(n){b="";for(var t=0;t<n.length;t++)c=[n.charCodeAt(t).toString(2)],c.unshift(Array(8-c[0].length+1).join(0)),b+=c.join("");return b.match(/[1]{4,}|[0]{4,}/g)?!1:!0}

```

### Binary:

```
0110011001110101011011100110001101110100011010010110111101101110001010000110111000101001011110110110001000111101001000100010001000111011011001100110111101110010001010000111011001100001011100100010000001110100001111010011000000111011011101000011110001101110001011100110110001100101011011100110011101110100011010000011101101110100001010110010101100101001011000110011110101011011011011100010111001100011011010000110000101110010010000110110111101100100011001010100000101110100001010000111010000101001001011100111010001101111010100110111010001110010011010010110111001100111001010000011001000101001010111010010110001100011001011100111010101101110011100110110100001101001011001100111010000101000010000010111001001110010011000010111100100101000001110000010110101100011010110110011000001011101001011100110110001100101011011100110011101110100011010000010101100110001001010010010111001101010011011110110100101101110001010000011000000101001001010010010110001100010001010110011110101100011001011100110101001101111011010010110111000101000001000100010001000101001001110110111001001100101011101000111010101110010011011100010000001100010001011100110110101100001011101000110001101101000001010000010111101011011001100010101110101111011001101000010110001111101011111000101101100110000010111010111101100110100001011000111110100101111011001110010100100111111001000010011000100111010001000010011000001111101

```

### Explanation:

Create a string to work with:

```
b="";

```

Loop over each character in the string:

```
for(var t=0;t<n.length;t++)

```

Create an array and convert the string to binary using character code:

```
c=[n.charCodeAt(t).toString(2)]

```

Add the leading zeros to the array:

```
c.unshift(Array(8-c[0].length+1).join(0))

```

Join the array back into a string:

```
b+=c.join("")

```

Return whether or not a string of four or more 1's or 0's was found in the binary result using a regular expression:

```
return b.match(/[1]{4,}|[0]{4,}/g)?!1:!0

```

### Fiddle:

https://jsfiddle.net/vrtLh97c/

### Stats:

Length: 173 bytes Penalty: 890 Total: 1063

Code Golf is hard :)
> 1 votes

# Answer
# Pyth, 19 + 12 * 10 = 139

```
!|}*"0"4.BQ}*"1"4.B

```

### Binary

```
00100001 01111100 01111101 00101010
00100010 00110000 00100010 00110100
00101110 01000010 01010001 01111101
00101010 00100010 00110001 00100010
00110100 00101110 01000010

```

### Explanation

```
!|}*"0"4.BQ}*"1"4.B
            *"1"4     # Repeat  ; '1111'
                 .B   # Convert ; input as a binary string
           }          # In      ; '1111' in the binary repr
   *"0"4              # Repeat  ; '0000'
        .BQ           # Convert ; input as a binary string
  }                   # In      ; '0000' in the binary repr
 |                    # Or      ; 4 consequent idenical digits found
!                     # Negate  ; True if not found, False if found

```
> 1 votes

# Answer
# Retina, 101 + 1390 = 1491

The code contains unprintable characters, but they show up in Chrome if you edit the post. `-` is `\x01-\x7f`.

```
¶
±
S_`
%(S`±
{2`
$`
}T01`-`_o
)Ms`.
.+
$*
+`(1+)\1
${1}0
01
1
m+`^(?!.{8})
0
0{8}|¶

M&`(.)\1{3}
0

```

**Try it online**

This code uses this `ord`, followed by conversion to binary and a simple check for overlapping sequences of four.

In binary:

```
11000010101101100000101011000010101100010000101001010011010111110110000000001010001001010010100001010011011000001100001010110001000010100111101100110010011000000000101000100100011000000000101001111101010101000011000000110001011000000000000100101101011111110110000001011111011011110000101000101001010011010111001101100000001011100000101000101110001010110000101000100100001010100000101000101011011000000010100000110001001010110010100100000001000010100010010001111011001100010111110100110000000010100011000000110001000010100011000100001010011011010010101101100000010111100010100000111111001000010010111001111011001110000111110100101001000010100011000000001010001100000111101100111000011111010111110011000010101101100000101000001010010011010010011001100000001010000010111000101001000000010111101100110011011111010000101000110000

```

Penalties counted with this Python program.
> 1 votes

# Answer
# Pyth, 21 + 2 * 10 = 41

```
J-T2-4eS%2.nr.[dJ.BwJ

```

Try it online!

Binary representation:

```
01001010 00101101 010101[00 00]110010 00101101 00110100 01100101 01010011
00100101 00110010 00101110 01101110 01110010 00101110 01011011 01100100
01001010 00101110 01[0000]10 01110111 01001010

```
> 1 votes

# Answer
# Python 2, 74 (length) + 130 (penalty) = 204

```
k,n=2*[1]
for[c]in(input(n)*2*2*2)[:1:-1]:n,k=k*ord(c[:n%16%15])+n/2,k*128

```

Output is via exit code; **0** is truthy, **1** is falsy. Produces garbage output to STDOUT and STDERR.

Try it online!

### Binary dump

```
00000000: 01101011 00101100 01101110 00111101 00110010 00101010  k,n=2*
00000006: 01011011 00110001 01011101 00001010 01100110 01101111  [1].fo
0000000c: 01110010 01011011 01100011 01011101 01101001 01101110  r[c]in
00000012: 00101000 01101001 01101110 01110000 01110101 01110100  (input
00000018: 00101000 01101110 00101001 00101010 00110010 00101010  (n)*2*
0000001e: 00110010 00101010 00110010 00101001 01011011 00111010  2*2)[:
00000024: 00110001 00111010 00101101 00110001 01011101 00111010  1:-1]:
0000002a: 01101110 00101100 01101011 00111101 01101011 00101010  n,k=k*
00000030: 01101111 01110010 01100100 00101000 01100011 01011011  ord(c[
00000036: 00111010 01101110 00100101 00110001 00110110 00100101  :n%16%
0000003c: 00110001 00110101 01011101 00101001 00101011 01101110  15])+n
00000042: 00101111 00110010 00101100 01101011 00101010 00110001  /2,k*1
00000048: 00110010 00111000                                      28

```
> 1 votes

# Answer
# Pyth, 16 + 1 x 10 = 26 bytes

```
qZsm:.BQjk*4]dZ2
   m           2  for d being the natural numbers below 2
            ]d        [d]
          *4          [d,d,d,d]
        jk            "dddd"
    :         Z       search for the above in
     .BQ              the binary representation of the input
                      (true/false)
  s               sum the 2-element array generated above, 1 for True, 0 for False
qZ                is equal to 0

```

Try it online!

## Binary

```
01110001 01011010 01110011 01101101
00111010 00101110 01[0000]10 01010001
01101010 01101011 00101010 00110100
01011101 01100100 01011010 00110010

```

## Tricks

The following alternations are done to avoid the demerits:

* Using `qZ` (is equal to zero) instead of `!` (negate)
* Using `:xy0` (search for) instead of `}xy` (is sublist)
* Using `Z` (variable, default to zero) instead of `0` (zero itself)

## Improvements

I do not find any way to circumvent the penalty. We have these commands related to binary:

* `.B` binary (`00101110 01[0000]10`)
* `C` charcode (`01[0000]11`)
* `.O` octary (`00101110 0100[1111]`)
* `.H` hexadecimal (`00101110 01001[000`)

Note that `.H` will also give us a penalty, because every printable character has its binary representation starting with `0`. Therefore, I used the most direct one, which is `.B`, directly converting it to binary.

I can end with `.H` to avoid the penalty, but it costs me 27 bytes...

## Generation

I found all allowed characters, which are those that do not contain `0000` or `1111`, and that do not end with `000` (because the next character must start with `0`):

* `"#$%&')*+,-.12345679:;DEFGIJKLMNQRSTUVWYZ[\]bcdefgijklmnqrstuvw`

Here are the characters that end with `1000`. They can only be used at the end:

* `(8HXhx`
> 1 votes

---
Tags: code-challenge, restricted-source, decision-problem, binary
---