title: Tuple addition in pointfree

text:
# Question
Title: Tuple addition in pointfree
What is the shortest way we can express the function

```
f(a,b)(c,d)=(a+c,b+d)

```

in point-free notation?

pointfree.io gives us

```
uncurry (flip flip snd . (ap .) . flip flip fst . ((.) .) . (. (+)) . flip . (((.) . (,)) .) . (+))

```

which with a little bit of work can be shortened to

```
uncurry$(`flip`snd).((<*>).).(`flip`fst).((.).).(.(+)).flip.(((.).(,)).).(+)

```

for 76 bytes. But this still seems *really* long and complex for such a simple task. Is there any way we can express pairwise addition as a shorter point-free function?

To be clear by what I mean by point-free, a point-free declaration of a function involves taking existing functions and operators and applying them to each other in such a way that the desired function is created. Backticks, parentheses and literal values (`[]`,`0`,`[1..3]`, etc.) are allowed but keywords like `where` and `let` are not. This means:

* You may not assign any variables/functions
* You may not use lambdas
* You may not import

Here is the same question when it was a CMC

# Answer
> 11 votes
# 44 bytes

Got this from `\x y -> (fst x + fst y, snd x + snd y)`

```
(<*>).((,).).(.fst).(+).fst<*>(.snd).(+).snd

```

Try it online!

Or, 42 bytes using `do`:

```
do a<-fst;((,).(a+).fst<*>).(.snd).(+).snd

```

Try it online!

# Answer
> 9 votes
# 44 bytes

*-8 bytes thanks to Ørjan Johansen. -3 bytes thanks to Bruce Forte.*

```
(.).flip(.)<*>(zipWith(+).)$mapM id[fst,snd]

```

Try it online!

Translates to:

```
f t1 t2 = zipWith (+) (mapM id [fst, snd] $ t1) (mapM id [fst, snd] $ t2)

```

## 67 bytes

*-8 bytes thanks to Ørjan Johansen. -1 byte thanks to Bruce Forte.*

If tuple output is required:

```
(((,).head<*>last).).((.).flip(.)<*>(zipWith(+).)$mapM id[fst,snd])

```

Try it online!

Yup, me manually doing it doesn't produce ripe fruit. But I am happy with the `[a] → (a, a)` conversion.

```
listToPair ∷ [a] → (a, a)
listToPair = (,) . head <*> last
-- listToPair [a, b] = (a, b)

```

Now if there was a *short* function with `m (a → b) → a → m b`.

# Answer
> 4 votes
# 60 bytes

I'm not seeing any `uncurry` love here, so I figured I'd pop in and fix that.

```
uncurry$(uncurry.).flip(.)(flip(.).(+)).(flip(.).((,).).(+))

```

I thought, with all of the `fst` and `snd`, that unpacking the arguments with `uncurry` might yield some results. Clearly, it was not as fruitful as I had hoped.

# Answer
> 4 votes
# 54 bytes

I honestly doubt that we'll beat @H.PWiz's 44 bytes solution, but nobody was using the fact that `(,)` implements the type class `Functor`, so here's another interesting one which isn't too bad:

```
((<*>snd).((,).).(.fst).(+).fst<*>).flip(fmap.(+).snd)

```

Try it online!

### Explanation

The implementation of the type class `Functor` for *2*-Tuples are very similar to that of `Either` (from *base-4.10.1.0*):

```
instance Functor ((,) a) where
    fmap f (x,y) = (x, f y)

instance Functor (Either a) where
    fmap _ (Left x) = Left x
    fmap f (Right y) = Right (f y)

```

What this means for this challenge, is that the following function adds the second elements while keeping the first element of the second argument:

```
λ f = fmap.(+).snd :: Num a => (a, a) -> (a, a) -> (a, a)
λ f (1,-2) (3,-4)
(3,-6)

```

So if only we got some little helper `helpPlz = \a b -> (fst a+fst b,snd b)` we could do `(helpPlz<*>).flip(fmap.(+).snd)` and would be done. Luckily we have the tool `pointfree` which gives us:

```
helpPlz = (`ap` snd) . ((,) .) . (. fst) . (+) . fst

```

So by simply plugging that function back in we arrive at the above solution (note that `(<*>) = ap` which is in *base*).

---
Tags: code-golf, tips, functional-programming, haskell
---


title: High Precision Metallic Means

text:
# Question
Title: High Precision Metallic Means
## Background

The metallic means, starting with the famous golden mean, are defined for every natural number (positive integer), and each one is an irrational constant (it has an infinite non-recurring decimal expansion).

For a natural number , the metallic mean is the root of a quadratic equation

The roots are always

but the metallic mean is usually given as the positive root. So for this question it will be defined by:

For the result is the famous golden ratio:

---

## Challenge

Your code should take 2 inputs: n and p *(the order is not important as long as it is consistent)*

* n is a natural number indicating which metallic mean
* p is a natural number indicating how many decimal places of precision

Your code should output the nth metallic mean to p decimal places precision.

### Validity

Your code is valid if it works for values of n and p from 1 to 65,535.

You must output a decimal in the form

digit(s).digit(s) (without spaces)

For example, the golden mean to 9 decimal places is

1.618033988

Display the last digit without rounding, as it would appear in a longer decimal expansion. The next digit in the golden mean is a 7, but the final 8 in the example should not be rounded up to a 9.

The number of decimal digits must be p, which means any trailing zeroes must also be included.

Answers of the form

are not valid - you must use a decimal expansion.

You may output up to 1 leading newline and up to 1 trailing newline. You may not output any spaces, or any other characters besides digits and the single point/full stop/period.

## Score

This is standard code golf: your score is the number of bytes in your code.

---

# Leaderboard

*(Using Martin's leaderboard snippet)*

```
var QUESTION_ID=52493;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}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
> 17 votes
# dc, 12

```
?kdd*4+v+2/p

```
* `?` Push n and p onto the stack
* `k` set precision to p
* `dd` duplicate n twice (total three copies)
* `*` multiply n\*n
* `4+` add 4
* `v` take square root
* `+` add n (last copy on stack)
* `2/` divide by 2
* `p` print

### Testcase:

```
$ dc -f metalmean.dc <<< "1 9"
1.618033988
$

```

# Answer
> 2 votes
# R, 116 bytes

```
library(Rmpfr);s=scan();n=mpfr(s[1],1e6);r=(n+(4+n^2)^.5)/2;t=toString(format(r,s[2]+2));cat(substr(t,1,nchar(t)-1))

```

This reads two integers from STDIN and prints the result to STDOUT. You can try it online.

Ungolfed + explanation:

```
# Import the Rmpfr library for arbitrary precision floating point arithmetic
library(Rmpfr)

# Read two integers from STDIN
s <- scan()

# Set n equal to the first input as an mpfr object with 1e6 bits of precision
n <- mpfr(s[1], 1e6)

# Compute the result using the basic formula
r <- (n + sqrt(4 + n^2)) / 2

# Get the rounded string representation of r with 1 more digit than necessary
t <- toString(format(r, s[2] + 2))

# Print the result with p unrounded digits
cat(substr(t, 1, nchar(t) - 1))

```

If you don't have the `Rmpfr` library installed, you can `install.packages("Rmpfr")` and all of your dreams will come true.

# Answer
> 1 votes
# Mathematica, 50 bytes

```
SetAccuracy[Floor[(#+Sqrt[4+#^2])/2,10^-#2],#2+1]&

```

Defines an anonymous function that takes `n` and `p` in order. I use `Floor` to prevent rounding with `SetAccuracy`, which I need in order to get decimal output.

# Answer
> 1 votes
# CJam, 35 bytes

```
1'el+~1$*_2#2$2#4*+mQ+2/1$md@+s0'.t

```

Reads **p** first, then **n**.

Try it online in the CJam interpreter.

### How it works

We simply compute the formula from the question for **n × 10p**, get the integer and fractional part of the result divided by **10p**, pad the fractional part with leading zeroes to obtain **p** digits and print the parts separated by a dot.

```
1'e  e# Push 1 and 'e'.
l+   e# Read a line from STDIN and prepend the 'e'.
~    e# Evaluate. This pushes 10**p (e.g., 1e3 -> 1000) and n.
1$*  e# Copy 10**p and multiply it with n.
_2#  e# Copy n * 10**p and square it.
2$   e# Copy 10**p.
2#4* e# Square and multiply by 4.
+    e# Add (n * 10**p)**2 and 4 * 10**2p.
mQ   e# Push the integer part of the square root.
+2/  e# Add to n * 10**p and divide by 2.
1$md e# Perform modular division by 10**p.
@+s  e# Add 10**p to the fractional part and convert to string.
0'.t e# Replace the first character ('1') by a dot.

```

# Answer
> 1 votes
# Python 2, 92 Bytes

As I am now looking at the answers, it looks like the CJam answer uses the same basic method as this. It calculates the answer for `n*10**p` and then adds in the decimal point. It is incredibly inefficient due to the way it calculates the integer part of the square root (just adding 1 until it gets there).

```
n,p=input()
e=10**p;r=0
while(n*n+4)*e*e>r*r:r+=1
s=str((n*e+r-1)/2);print s[:-p]+'.'+s[-p:]

```

# Answer
> 1 votes
# PHP, 85 78 bytes

```
echo bcdiv(bcadd($n=$argv[bcscale($argv[2])],bcsqrt(bcadd(4,bcpow($n,2)))),2);

```

It uses the BC Math mathematical extension which, on some systems, could not be available. It needs to be included on the compilation time by specifying the `--enable-bcmath` command line option. It is always available on Windows and it seems it is included in the PHP version bundled with OSX too.

**Update**:

I applied all the hacks suggested by @blackhole in their comments (thank you!) then I squeezed the initialization of `$n` into its first use (3 more bytes saved) and now the code fits in a single line in the code box above.

# Answer
> 1 votes
# J, 27 Bytes

```
4 :'}:":!.(2+x)-:y+%:4+*:y'

```

### Explanation:

```
4 :'                      '   | Define an explicit dyad
                       *:y    | Square y
                     4+       | Add 4
                   %:         | Square root
                 y+           | Add y
               -:             | Half
      ":!.(2+x)               | Set print precision to 2+x
    }:                        | Remove last digit, to fix rounding

```

Call it like this:

```
    9 (4 :'}:":!.(2+x)-:y+%:4+*:y') 1
1.618033988

```

Another, slightly cooler solution:

```
4 :'}:":!.(2+x){.>{:p._1,1,~-y'

```

Which calculates the roots of the polynomial x^2 - nx - 1. Unfortunately, the way J formats the result makes retreving the desired root slightly longer.

---
Tags: code-golf
---


title: Tips for golfing in Pyth

text:
# Question
Title: Tips for golfing in Pyth
Pyth is a Python-inspired procedural programming language, created by PPCG user isaacg.

What general tips do you have for golfing in Pyth? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pyth.

One tip per answer, please.

# Answer
> 26 votes
# Write the code in Python first

Pyth is so similar to Python that it is pretty easy to translate Python programs to Pyth. However, because Pyth is a single-letter-per-command language, it is sometimes hard to write straight Pyth. By writing in Python first, there is less to think about at a time (since Python is a pretty easy language to code in).

# Answer
> 25 votes
# Know Your Variables

Pyth has 3 categories of variables: generic pre-initialized variables, variables pre-initialized based on user input, and variables that implicitly generate an assignment on first use.

### Generic variables:

```
b = "\n"
d = " "
k = ""
G = "abcdefghijklmnopqrstuvwxyz"
H = {}                            # (empty dict)
N = '"'
T = 10
Y = []
Z = 0

```

### Input-initialized variables:

```
Q = eval(input())
z = input()

```

Note that these initializations will only be run in a given program if the associated variable is used outside of a string in the code. In addition, the order is `Q`, then `z`, if both are used.

### Assignment on first use variables:

`J` and `K`. If you want to initialize them both to the same value, you can do so with an expression such as `KJ0`, which is equivalent to the lengthier `J0K0`.

# Answer
> 19 votes
# Use the even newer online interpreter to test your answers.

Note that this is new software, so it may be buggy. Please report any problems to me.

# Answer
> 14 votes
Strings at the end of the line don't need end quotes. For example:

```
"Hello, world!

```

is a completely valid Hello World program.

# Answer
> 10 votes
# Use `C` for base compression

This is actually undocumented, C on a string is actually *not* direct chr -\> int but instead base 256 -\> base 10 (which is the same on one char strings). This is hugely helpful in compressing an int, we can use this script to compress:

```
sCMjQ256

```

Take `12345678910`, it results in `ßÜ>` (some unprintables in there).

Also with an array of ints, you can concatenate them, and with large strings by converting to code points and treating as base 128 number.

Another usage of `C`, thanks @xnor for showing me this, is making an arbitrary large number. The naive way is:

```
^TT

```

But we can do one byte better with:

```
CG

```

this base 256 deconverts the entire alphabet. Results `156490583352162063278528710879425690470022892627113539022649722` = ~`1.56e62`.

# Answer
> 9 votes
# Use the short functional...err...functions

When the lambda argument to `map` or `reduce` just applies one operation to the arguments,, you can use the short forms, `M` and `F`. `fMx` is equivalent to `mfdx`, and `fFx` is the same thing as `.UfbZx`. For instance, say we take a list of numbers as input and output each one incremented. A first approach might be:

```
mhdQ

```

However, that can be rewritten as:

```
hMQ

```

A similar thing applies to `reduce` with `F`. As an example, say there's a challenge to calculate the product of a list of integers. Again, a first try may be:

```
.U*bZQ

```

However, with `F`, that can be shortened to:

```
*FQ

```

Shaves off three bytes...not bad!

# Answer
> 8 votes
# There is now an online tutorial for Pyth.

Full documentation will be added later.

# Answer
> 7 votes
## Keep your Pyth implementation up to date.

I'm fairly regularly improving Pyth, removing less useful features and adding more useful ones, so keep an eye out for what's new and update your copy of the implementation regularly.

Some recently added features: (as of 10/19/14)

`y`: Acts as `*2` on numbers, and as list of all subsets on strings and lists. For instance:

```
pyth -c 'y"abc'
['', 'a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']

```

`f`: `f` is normally the filter command. Now, when called with a number as its second argument, it will filter over the infinite sequence starting with that number and counting up by ones, then return the first element of the resulting sequence.

For instance, here's the code to find the smallest prime over a billion:

```
pyth -c 'f!tPT^T9'
1000000007

```

# Answer
> 5 votes
# Look at all of the control flow options

### Loops:

`F`: For loop. Just like Python's.

`V`: For loop over a range. Neither variable nor range must be given, so 2 characters shorter.

`W`: While loop. Just like Python's.

`#`: Infinite while loop. Escape with error or explicit break. ~~Only `try ... except` feature now in Pyth.~~

### Functions:

`D`: General define. Just like Python.

`L`: 1 argument, no assignment function, like Python's lambda, but named. Function name, variable name and return (`R`) need not be given, so 3 characters shorter.

### Functional programming:

`f`: Filter - select elements of input sequence that return truthy on input lambda.

`f`: First integer greater than or equal to input which gives truthy filter result.

`m`: Map - transform elements of input sequence using input lambda.

`u`: Reduce - fold input sequence on input lambda, initializing accumulator to third argument.

`o`: Order - older elements of input sequence using input lambda as the key.

Usually, there will be multiple possibilities for any given problem, and only by writing test solutions with each of them can you figure out which is shortest.

# Answer
> 5 votes
## Named arguments in functions (No longer supported)

Sometimes, default values in functions can be useful for golfing. Pyth actually supports this (much to my surprise). For example:

```
DC=Z1RZ;C;C5

```

Will print:

```
1
5

```

You can also use J and K to save characters when doing this:

```
DgJ1K1R+JKg;g2;g2 3

```

prints:

```
2
3
5

```

This is usually useful for recursive algorithms.

This no longer works, but I have left it here in case someone wants to golf using an old version of Pyth.

# Answer
> 5 votes
# Unpacking 2 element tuples with `F`

Say you have a 2 element tuple, `J = (a, b)`, and you want `r(a,b)`, for some 2 arity function r.

The naive way to do this is `rhJeJ`.

The fancy way to do this is `r.*J`, using the unpack operator.

The really fancy way to do this is `rFJ`, using the fold operator.

# Answer
> 4 votes
# Use `map` to generate lists

It's basically an equivalent of the fancy list comprehensions of python. Use an existing list or an range to iterate over and map each value, even if the value doesn't matter.

Two examples:

* Generate a list of 8 zeros.

`mZ8` instead of `*8]Z`
* Generate a list of 5 random numbers between 0 and 9:

`mOT5` instead of `V5~Y]OT)`

The second one automatically assigns the list to `Y` (well actually it appends to Y), but even `=YmOTU5` is shorter.

# Answer
> 4 votes
# Use the short arithmetic functions

`h`: Other than returning the first element of a list, it increments a number, e.g. `hT` evaluates to `11`. Shorter than `+1T`.

`t`: This decrements a number (other than return the tail of a list), e.g. `tT` evaluates to `9`. Shorter than `-T1`.

`y`: This doubles a number, e.g. `yT` evaluates to `20`, shorter than `*T2` or `+TT`.

# Answer
> 4 votes
# Implicit Q at EOF

This is a new change, as of today.

`Q` is the variable which is auto-initialized to the evaluated input. It is implicitly appended to the end of the Pyth program, as many times as is necessary to make the arity work out. To see an example of how to use this for golfing, let's say we want to compute the Collatz function of the input.

A shortest way to write it is like this:

```
@,/Q2h*3QQ

```

However, since the `Q`s are implicit at the end of the file, we can simply write:

```
@,/Q2h*3

```

Saving 2 bytes.

Note that functions with non-required arguments will not have those arguments filled in. For instance, `c"12 12"` will not have an implicit `Q`, since `c` only requires 1 argument.

# Answer
> 3 votes
# Use reduce to apply a function repeatedly.

Suppose you need to set a variable to some function of itself, and repeat a certain number of times. Take, for instance, the problem of finding the number 100 later in the Collatz Sequence from the input. The shortest way to find the next number in the sequence, if the initial number is `Q`, is

```
@,/Q2h*Q3Q

```

The most obvious way to apply this 100 times and print the result would be

```
V100=Q@,/Q2h*Q3Q;Q

```

Loop 100 times, updating the value of Q each time, then end the loop and print Q.

Instead, we can use a reduce function which ignores the sequence variable (`H`).

```
u@,/G2h*G3GU100Q

```

This is 2 characters shorter. It is 3 characters shorter if you are trying to loop as many times as there are elements in a sequence.

# Answer
> 3 votes
# Switching two elements in a list

Switching two elements can be quite an expensive task. So here are two approaches you wanna use.

### Tmp-variable approach

In preparation we define a list `Y` and fill it with some numbers. The goal is to switch the second and third element.

```
=Y[1 3 5 3 6 7)AGH,1 2

```

We simply assign the tmp variable `J = Q[G]`, do the first list assignment `Y[G] = Y[H]` and then the second last assignment `Y[H] = J`. The trick here is to nest the two list assignments, so you don't have to suppress printing and don't have to use refer twice to `Y`.

```
J@YGXXYG@YHHJ

```

instead of

```
J@YG XYG@YHXYHJ

```

### Translating approach

If the elements, which you want to switch, are unique in the list, use this approach. It's really short. So this time we switch the first and third element (the values `1` and `5` are unique).

```
=Y[1 3 5 3 6 7)K,Z2

```

This uses the translation functionality of the list:

```
XYm@YdK)

```

This translating replaces every element `Y[0]` with `Y[1]` and every `Y[1]` with `Y[0]`. So if the values are not unique, bad things happend. For instance `K,1 2` results in `[1, 5, 3, 5, 6, 7]`.

Notice that the closing parentheses is optional, if the statement is the last one in your code.

# Answer
> 3 votes
# There are usually shorter alternatives to Any

When you want to find if any of a sequence satisfy a condition, you would usually use `.Em`. For example, if you want to find out if any in a list are greater-than-or-equal to 5:

```
.Emgd5Q

```

But, if it only needs to be a truthy/falsey, not true/false, `sm` would work since sum works on bools.

```
smgd5Q

```

We can even do one shorter, with `f`ilter:

```
fgT5Q

```

The last one looks really ugly though.

For `.A`ll, the only thing I can think of is to use the opposite condition and negate it for a one char save over `.Am`:

```
!f<T5Q

```

# Answer
> 3 votes
# Finding the maximum of two integers

```
g#

```

For instance, suppose you have `J=5` and `K=12`. Then `g#JK` = 12, and `g#KJ` = 12 as well.

This was discovered by @Pietu1998, who put it this way:

Not sure if someone has already found it, but there's a cool way to do max(A, B) in 2 bytes, no need to use 3 for `eS,AB`. `g#AB` does the same thing. (It's very inefficient, though, since it loops max(1, A-B+1) times. An optimization is to put the number likely to be larger as B.)

# Answer
> 2 votes
# Pyth's `join` method

The `join` method in Python can be often a little bit annoying, since it only joins strings. Pyth's `join` is more generous. It transforms all objects in strings by default.

E.g. `jkUT` gives `0123456789` or `jb["abc"4,5\f]7` gives

```
abc
4
(5, 'f')
[7]

```

# Answer
> 2 votes
# Divisibility testing using `I` and GCD

**Disclaimer:** This *only* works for non-negative integers.

To check if two non-negative integers are divisible, you can do the following:

```
iI<divisor><dividend>

```

If **a** is divisible by **b** and **a ≥ b ≥ 0**, then **gcd(a, b) = b**.

It doesn't necessarily save bytes over `!%<dividend><divisor>`, but it might bring you a saving, because:

* You might be able to tweak the implicit stuff at the end of a Pyth program (like dropping `Q`), when working with the dividend.
* You can use it as a `<pfn>`, since it is a function on its own.
* It handles modulo by `0`.

**Try it!**

# Answer
> 1 votes
# Debugging with `<newline>`

If your code is written in an imperative programming style, it is quite easy to debug, since you can easily print intermediate results. (permalink)

```
FN.:Q2                loop
      =Y+-Y-FNhN      some random command
                Y     print intermediate result
                 ;Y   end for loop and print result

```

But a large amount of Pyth programs use elements of functional programming, like map, filter and reduce, which don't allow such a simple printing. But it is still possible, using the `\n` command.

The same code using `u` (reduce) would be: (permalink)

```
u        .:Q2Y   reduce .:Q2, start with G = Y
 +-G-FHhH        random command

```

If you want to print the intermediate values, simply to insert `\n`: (permalink)

```
u         .:Q2Y   reduce
   \nG             print(G)
 +-\nG-FHhH        random command

```

`\na` prints `a` on a newline and returns `a`. So you can insert it anywhere without worrying changing the functionality of the program.

# Answer
> 1 votes
# Telling if a Number is a Whole Number

A neat trick is using `I`nvariant to tell if a number is a whole number as such:

```
sI

```

This checks if the number doesn't change when you truncate it, which it won't if it's a whole number.

For example, you can use this as a perfect square check:

```
sI@Q2

```

# Answer
> 1 votes
# Use Packed Pyth

Packed Pyth is a new "programming language" which is exactly the same as Pyth, except that it uses 7 bits per character instead of 8 bits per character.

To use it, clone the pyth repository. The file `packed-pyth.py` is the interpreter.

Say your code is `"Hello, world!`.

First, put it in a file: `echo -n '"Hello, world!' > code.pyth`

Next, pack the Pyth code into Packed Pyth file: `python3 packed-pyth.py -p code.pyth code.ppyth`

Finally, run the Packed Pyth code: `python3 packed-pyth.py code.ppyth`

When running code, you can provide the `-d` flag to see what the Pyth code that's actually being run is, and you can provide input as a second command line argument after the file containing the code.

Upside:

* Code is shorter by 1/8th.

Downside:

* ASCII only.
* No interactive input.
* Full debug options are not availible.
* Worse error reporting.

# Answer
> 1 votes
# Assigning a variable to a function applied to itself

If you have a function of arity 1, and want to apply that to a variable and apply to itself, you can use the following syntax:

```
=<function><variable>

```

Instead of:

```
=<variable><function><variable>

```

For example, if you want to increment the variable `Z`, you can do:

```
=hZ

```

Which saves one byte over `=ZhZ`.

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


title: Could They Be The Same Day Of The Week?

text:
# Question
Title: Could They Be The Same Day Of The Week?
### Challenge

Given a non-negative integer, output whether it is possible for two dates (of the Gregorian calendar) differing by exactly that many years to share a day of the week. A year is assumed to be a leap year either if it is divisible by 4 but not by 100, or if it is divisible by 400.

Output may be:

* falsey/truthy (in either orientation)
* any two distinct values
* one distinct value and one being anything else
* by program return code
* by success/error
* by any other reasonable means - just ask if you suspect it may be controversial

But **not** by two non-distinct sets of values, except for falsey/truthy (as this would allow a no-op!)

### Detail

This is whether the input is a member of OEIS sequence A230995.

Members:

```
0, 5, 6, 7, 11, 12, 17, 18, 22, 23, 28, 29, 33, 34, 35, 39, 40, 45, 46, 50, 51, 56, 57, 61, 62, 63, 67, 68, 73, 74, 78, 79, 84, 85, 89, 90, 91, 95, 96, 101, 102, 106, 107, 108, 112, 113, 114, 117, 118, 119, 123, 124, 125, 129, 130, 131, 134, 135, 136, 140, 141, 142, 145, 146, 147, 151, 152, 153, 157, 158, 159, 162, 163, 164, 168, 169, 170, 173, 174, 175, 179, 180, 181, 185, 186, 187, 190, 191, 192, 196, 197, 198, 202, 203, 204, 208, 209, 210, 213, 214, 215, 219, 220, 221, 225, 226, 227, 230, 231, 232, 236, 237, 238, 241, 242, 243, 247, 248, 249, 253, 254, 255, 258, 259, 260, 264, 265, 266, 269, 270, 271, 275, 276, 277, 281, 282, 283, 286, 287, 288, 292, 293, 294, 298, 299, 304, 305, 309, 310, 311, 315, 316, 321, 322, 326, 327, 332, 333, 337, 338, 339, 343, 344, 349, 350, 354, 355, 360, 361, 365, 366, 367, 371, 372, 377, 378, 382, 383, 388, 389, 393, 394, 395
plus
400, 405, 406, 407, 411, ...

```

Non-members:

```
1, 2, 3, 4, 8, 9, 10, 13, 14, 15, 16, 19, 20, 21, 24, 25, 26, 27, 30, 31, 32, 36, 37, 38, 41, 42, 43, 44, 47, 48, 49, 52, 53, 54, 55, 58, 59, 60, 64, 65, 66, 69, 70, 71, 72, 75, 76, 77, 80, 81, 82, 83, 86, 87, 88, 92, 93, 94, 97, 98, 99, 100, 103, 104, 105, 109, 110, 111, 115, 116, 120, 121, 122, 126, 127, 128, 132, 133, 137, 138, 139, 143, 144, 148, 149, 150, 154, 155, 156, 160, 161, 165, 166, 167, 171, 172, 176, 177, 178, 182, 183, 184, 188, 189, 193, 194, 195, 199, 200, 201, 205, 206, 207, 211, 212, 216, 217, 218, 222, 223, 224, 228, 229, 233, 234, 235, 239, 240, 244, 245, 246, 250, 251, 252, 256, 257, 261, 262, 263, 267, 268, 272, 273, 274, 278, 279, 280, 284, 285, 289, 290, 291, 295, 296, 297, 300, 301, 302, 303, 306, 307, 308, 312, 313, 314, 317, 318, 319, 320, 323, 324, 325, 328, 329, 330, 331, 334, 335, 336, 340, 341, 342, 345, 346, 347, 348, 351, 352, 353, 356, 357, 358, 359, 362, 363, 364, 368, 369, 370, 373, 374, 375, 376, 379, 380, 381, 384, 385, 386, 387, 390, 391, 392, 396, 397, 398, 399
plus
401, 402, 403, 404, 408, ...

```

This is so the shortest answer in each language wins!

# Answer
# MATL, 17 bytes

```
`0Gv@+5:YcYO8XOda

```

The program halts if the input belongs to the sequence, or runs indefinitely (infinite loop) otherwise.

Let `n` be the input. The code executes a loop that tests years `1` and `1+n`; then `2` and `2+n`; ... until a matching day of the week is found. If no matching exists the loop runs indefinitely.

The membership function for `n` is periodic with period `400`. Therefore, at most `400` iterations are needed if `n` belongs to the sequence. This requires less than 20 seconds in Try It Online. As a proof of this upper bound, here's a modified program that limits the number of iterations to 400 (by adding `@401<*` at the end). Note also that this bound is loose, and a few seconds usually suffice.

Try it online!

### Explanation

```
`           % Do...while
  0Gv       %   Push column vector [0; n], where n is the input number
  @+        %   Add k, element-wise. Gives [k; k+n]
  5:        %   Push row vector [1, 2, 3, 4, 5]
  Yc        %   Horizontal "string" concatenation: gives the 2×6 matrix
            %   [k, 1, 2, 3, 4, 5; k+n, 1, 2, 3, 4, 5]. The 6 columns
            %   represent year, month, day, hour, minute, second
  YO        %   Convert each row to serial date number. Gives a column
            %   vector of length 2
  8XO       %   Convert each date number to date string with format 8,
            %   which is weekday in three letters ('Mon', 'Tue', etc).
            %   This gives a 2×3 char matrix such as ['Wed';'Fri']
  d         %   Difference (of codepoints) along each column. Gives a
            %   row vector of length 3
  a         %   True if some element is nonzero, or false otherwise
            % End (implicit). The loop proceeds with the next iteration
            % if the top of the stack is true

```

---

## Old version, 24 bytes

```
400:"0G&v@+5:YcYO8XOdavA

```

Output is `0` if the input belongs to the sequence, or `1` otherwise.

Try it online!

### Explanation

```
400         % Push row vector [1, 2, ..., 400]
"           % For each k in that array
  0G&v      %   Push column vector [0; n], where n is the input number
  @+        %   Add k, element-wise. Gives [k; k+n]
  5:        %   Push row vector [1, 2, 3, 4, 5]
  Yc        %   Horizontal "string" concatenation: gives the 2×6 matrix
            %   [k, 1, 2, 3, 4, 5; k+n, 1, 2, 3, 4, 5]. The 6 columns
            %   represent year, month, day, hour, minute, second
  YO        %   Convert each row to serial date number. Gives a column
            %   vector of length 2
  8XO       %   Convert each date number to date string with format 8,
            %   which is weekday in three letters ('Mon', 'Tue', etc).
            %   This gives a 2×3 char matrix such as ['Wed';'Fri']
  d         %   Difference (of codepoints) along each column. Gives a
            %   row vector of length 3
  a         %   True if some element is nonzero, or false otherwise
  v         %   Concatenate vertically with previous results
  A         %   True if all results so far are true
            % End (implicit). Display (implicit)

```
> 4 votes

# Answer
# Python 2, 58 bytes

```
u=-abs(200-input()%400)-4
print u/100+5>(u-8)*5/4%7>u%4/-3

```

Try it online!

A direct formula.
> 5 votes

# Answer
# Jelly, ~~20~~ 18 bytes

```
99R4ḍj`‘ṡ%4ȷ$S€P7ḍ

```

Outputs **1** for members, **0** for non-members.

Try it online!

### How it works

```
99R4ḍj`‘ṡ%4ȷ$S€P7ḍ  Main link. Argument: n

99                  Set the return value to 99.
  R                 Range; yield [01, .., 99].
   4ḍ               Test each element in the range for divisibility by 4.
     j`             Join the resulting array, using itself as separator.
                    The result is an array of 9801 Booleans indicating whether the
                    years they represent have leap days.
       ‘            Increment the results, yielding 1 = 365 (mod 7) for non-leap
                    years, 2 = 366 (mod 7) for leap years.
         %4ȷ$       Compute n % 4000.
        ṡ           Take all slices of length n % 4000 of the result to the left.
             S€     Take the sum of each slice.
               P    Take the product of the sums.
                7ḍ  Test for divisibility by 7.

```
> 5 votes

# Answer
# Python 2, 83 bytes

```
lambda i:all(c(y)-c(y-i)for y in range(401))
c=lambda n:(5*(n/4)+n%4-n/100+n/400)%7

```

Try it online!

Direct port of my Haskell answer.
> 2 votes

# Answer
# Haskell, 76 bytes

*-35 bytes thanks to Jonathan Allan. -2 bytes thanks to Lynn.*

```
f i=or[c y==c$y+i|y<-[0..400]]
c n=(5*n#4+n%4-n#100+n#400)%7
(%)=mod
(#)=div

```

Try it online!

Using the OEIS PARI program's algorithm.
> 1 votes

# Answer
# Pyth, 32 bytes

```
iI7*FsM.:hMs.iKiIL4S99*98]K%Q400

```

**Try it here!** (Click "Switch to Test Suite" to verify more test cases at once)

### How?

Uses a cool trick I just added to the "Tips for golfing in Pyth" thread.

```
iI7*FsM.:hMs.iKiIL4S99*98]K%Q400 | Full program. Reads from STDIN, outputs to STDOUT.

                   S99           | Generate the integers in 1 ... 99.
                 L               | For each integer N in that list...
               iI 4              | Check if 4 is invariant over applying GCD with N.
                                 | This is equivalent to checking if 4 | N.
              K                  | Store the result in a variable K.
            .i         *98]K     | And interleave K with the elements of K wrapped
                                 | into a list and repeated 98 times.
           s                     | Flatten.
         hM                      | Increment.
       .:                        | And generate all the substrings...
                           %Q400 | Of length  % 400.
     sM                          | Sum each.
   *F                            | And apply folded product.
iI7                              | Check if 7 is invariant when applied GCD with the
                                 | product (basically check whether 7 | product).
                                 | Implicitly output the appropriate boolean value.

```
> 1 votes

# Answer
# Python 3, ~~110~~ 107 bytes

```
from datetime import*
lambda n,d=date:0in[d(i,1,1).weekday()-d(i+n%400,1,1).weekday()for i in range(1,999)]

```

Try it online!

*-3 bytes thanks to Mr. Xcoder.*
> 0 votes

---
Tags: code-golf, number, sequence, decision-problem, date
---


title: Ternary Triangles

text:
# Question
Title: Ternary Triangles
The idea of this is mainly from BIO 2017 q1. I got the idea for posting this challenge from my Binary Sequences challenge, since lots of people seemed to like it.

Also, this is the first challenge I've posted without posting on the sandbox. I'll delete it if no one likes it.

### Rules

Take in a sequence of digits in ternary (base 3); this could be as a string, an array or the numerical value along with the number of preceding zeros.

For each row in the triangle, a row below is generated until there is only one digit in the last row. To find a digit below two other digits, the digit will be the same as two above it if these two other digits above are equal. Otherwise, it will be the digit that is not equal to either of them. Here is an example:

```
0 0 1 2 0 1 2 2
 0 2 0 1 2 0 2
  1 1 2 0 1 1
   1 0 1 2 1
    2 2 0 0
     2 1 0
      0 2
       1

```

*You are only expected to return the last row.*

Make your code short.

### Test Cases

```
0 -> 0
11 -> 1
10 -> 2
000 -> 0
012 -> 1
21102 -> 2
201021 -> 1
111111 -> 1
1020202020 -> 2
0212121210 -> 0

```

# Answer
> 9 votes
## Husk, 9 bytes

```
%3←ΩεẊo_+

```

Try it online!

### Explanation

The main idea is to compute the mapping of two digits to one as **f(a,b) = (-a-b) % 3**. For golfing purposes we can delay the modulo until the very end.

```
   Ωε       Apply the following function until the list is only one
            element in length.
     Ẋo       Apply the following function to pairs of adjacent values.
       _+       Add the two values and negate the result.
  ←         Take the first (and only) element of this list.
%3          Take it modulo 3.

```

In principle, it's also possible to compute the result directly by multiplying each element by the corresponding binomial coefficient and multiplying the sum by **-1** for even-length lists, but I don't know of a way to do that in fewer bytes.

# Answer
> 6 votes
# MATL, 10 bytes

```
td"HYCEsI\

```

Try it online! Or verify all test cases.

### Explanation

For each pair of digits, the code computes twice the sum modulo 3. The process is repeated as many times as the length of the input minus 1.

```
t        % Implicit input: array of length n. Duplicate
d        % Consecutive differences. Gives an array of length n-1
"        % For each (that is, do n-1 times)
  HYC    %   2-column matrix where each column is a sliding block of length 2
  E      %   Times 2, element-wise
  s      %   Sum of each column
  I\     %   Modulo 3
         % Implicit end. Implicit display

```

# Answer
> 3 votes
# Python 2, 48 bytes

```
f=lambda a,*l:-(f(*l)+f(a,*l[:-1]))%3if l else a

```

Try it online!

Recurses on the sublists deleting the first and last elements respectively.

This would be cleaner in Python 3 if it could actually unpack `f=lambda a,*b,c:...`.

# Answer
> 3 votes
# Emojicode, 242 bytes

```
➡i⏩➖1 0j⏩0i❎j➕1jj➖➖3j➕1j0

```

Uses the same algorithm as my C answer. Try it online!

# Answer
> 3 votes
# Jelly, 9 bytes

```
+2\N$Ḋ¿%3

```

Try it online!

Using Martin Ender's Husk algorithm.

# Answer
> 2 votes
# C (gcc), ~~91~~ ~~88~~ 84 bytes

*-1 byte thanks to @Mr.Xcoder!*

```
j;f(a,l)int*a;{for(;l-->1;)for(j=0;j<l;)a[j++]=a[j]^a[j+1]?3-a[j]-a[j+1]:a[j];a=*a;}

```

Gets the array and the length. Try it online!

# Answer
> 2 votes
# Haskell, 36 bytes

```
f[a]=a
f(h:t)=mod(-f t-f(h:init t))3

```

Try it online!

Saves 1 byte over the more symmetrical:

```
f[a]=a
f l=mod(-f(tail l)-f(init l))3

```

Try it online!

The idea is simple: recursively compute the function on the sublists deleting the first and last element respectively, and combine them with `\a b -> mod(-a-b)3`. This seems shorter than `zipWith`'ing this fuction .

**Haskell, 44 bytes**

```
f[a]=mod a 3
f l=f$zipWith((-).(0-))l$tail l

```

Try it online!

# Answer
> 2 votes
# J, ~~23~~ 15 Bytes

```
3&(|2+/\-)~<:@#

```

Thanks to @miles

### Old Solution:

```
3|2&(-@+/\)^:(#>1:)^:_]

```

Inspired by Martin Ender's solution:

### Explanation

```
3|2&(-@+/\)^:(#>1:)^:_]    | Whole program
                      ]    | Seperates the argument from the _ (infinity)
           ^:(#>1:)^:_     | Do while the length is greater than one
  2&(-@+/\)                | Inverse of the sum of adjacent elements
3|                         | Modulo 3

```

# Answer
> 1 votes
# APL (Dyalog), 17 bytes

```
{3|3-2+/⍵}⍣{1=≢⍺}

```

Try it online!

**How?**

`2+/⍵` \- sum each two adjacent items

`3-` \- vectorized subtract from three

`3|` \- vectorized modulo by three

\- repeat until...

`1=≢⍺` \- only one item is left

# Answer
> 1 votes
# Javascript (ES6), 58 bytes

```
f=s=>s[1]?f(s.replace(/.(?=(.?))/g,(a,b)=>b&&(6-a-b)%3)):s

```

# Answer
> 0 votes
## Batch, 122 bytes

```
@set/an=2,s=i=l=0
@for %%e in (%*)do @set/al+=1,n^^=3
@for %%e in (%*)do @set/as+=%%e*n,s%%=3,n*=l-=1,n/=i+=1
@echo %s%

```

Uses binomial expansion. As @MartinEnder points out, the sum has to be negated (modulo 3) if the number of values (which are counted in the first loop) is even, so `n` is set to either `1` or `2` accordingly. The second loop then computes the sum via the binomial coefficients.

# Answer
> 0 votes
# APL+WIN, ~~30~~ 28 bytes

2 bytes saved courtesy of Uriel.

```
n←⎕⋄¯1↑∊⍎¨(⍴n)⍴⊂'n←3|3-2+/n'

```

Explanation:

```
n←⎕ Prompt for screen input of the form: 0 0 1 2 0 1 2 2

'n←3|3-2+/n' Successive rows are 3 mod 3 minus successive digit pairs.

(⍴n)⍴⊂ Create a nested vector of the row code, one element per row.

¯1↑∊⍎¨ Execute each element of row code, flatten result and take final value.

```

This is one way of writing looping code in APL on a single line.

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


title: Make me an upside-down Christmas tree!

text:
# Question
Title: Make me an upside-down Christmas tree!
## Challenge

We all know about normal Christmas trees - but how about an upside-down Christmas tree! This is a fairly easy, Christmas themed challenge. The objective of this challenge is to make me an ASCII upside-down Christmas tree. Here are the rules for this challenge:

1. Accept an odd, positive integer. You can assume it will always be between `7` and `51`.
2. The base of the tree will be made of the characters:

```
___
\ /
 |

```
3. The top of the tree (the star), will be made up of a single `*`.
4. Each line of the tree will be constructed using the format `<?>` where `?` is any number of `-`s. For example, if making a line of length `5`, the line should be `<--->`. Or if making a line of length `8`, the line should be `<------>`.
5. Here is how the body of the tree should be constructed:

1. Take the odd number `n` given as input, and create a line of the tree that length.
    2. Subtract `4` from `n` and create a line of the tree that length.
    3. Subtract `2` from `n` and create a line of the tree that length.
    4. Decrement `n` by `2`. After that, unless **`n` equals `5`**, go back to step 2.
6. The base (see step 2.) the star (see step 3.) and each line of the tree (see steps 4. and 5.) should all be centered using the *original* odd number input (see step 1.) as the maximum width.

## Examples/Test Cases

```
odd number inputed: 7
  ___
  \ /
   |
<----->      line length -> 7
  <->        line length -> 7 - 4 = 3
 <--->       line length -> 7 - 2 = 5
   *

odd number inputed: 13
     ___
     \ /
      |
<----------->      line length -> 13
  <------->        line length -> 13 - 4 = 9
 <--------->       line length -> 13 - 2 = 11
   <----->         line length -> 11 - 4 = 7
  <------->        line length -> 11 - 2 = 9
    <--->          line length -> 9 - 4 = 5
   <----->         line length -> 9 - 2 = 7
     <->           line length -> 7 - 4 = 3
    <--->          line length -> 7 - 2 = 5
      *

odd number inputed: 9
   ___
   \ /
    |
<------->      line length -> 9
  <--->        line length -> 9 - 4 = 5
 <----->       line length -> 9 - 2 = 7
   <->         line length -> 7 - 4 = 3
  <--->        line length -> 7 - 2 = 5
    *

odd number inputed: 17
       ___
       \ /
        |
<--------------->      line length -> 17
  <----------->        line length -> 17 - 4 = 13
 <------------->       line length -> 17 - 2 = 15
   <--------->         line length -> 15 - 4 = 11
  <----------->        line length -> 15 - 2 = 13
    <------->          line length -> 13 - 4 = 9
   <--------->         line length -> 13 - 2 = 11
     <----->           line length -> 11 - 4 = 7
    <------->          line length -> 11 - 2 = 9
      <--->            line length -> 9 - 4 = 5
     <----->           line length -> 9 - 2 = 7
       <->             line length -> 7 - 4 = 3
      <--->            line length -> 7 - 2 = 5
        *

```

## Rules

# Answer
> 10 votes
# Python 3, ~~127~~ ~~121~~ ~~105~~ ~~103~~ ~~100~~ 98 bytes

This is an unnamed lambda function which returns a list of lines:

```
lambda o:[s.center(o)for s in['___','\ /','|',*[f'<{"-"*(o-i+2-i%2*3)}>'for i in range(4,o)],'*']]

```

**Try it online!**

The main part of this answer is `(o-i+2-i%2*3)`, which works out the number of dashes to have on a line. The rest of the answer is simply converting this into the desired ASCII-art.

*Many thanks to Mr. Xcoder, for shaving 6 bytes, and discussing golfs with me in chat.*

*Thanks also to Lynn for noticing that `3*(i%2)` can be `i%2*3`, 2 bytes shorter!*

# Answer
> 7 votes
# C, 163 bytes

```
#define P;printf(
i;g(l){P"%*c",1+i-l--/2,60);for(;--l P"-"))P">\n");}f(n){i=n/2 P"%*c__\n%*c /\n%*c|\n",i,95,i,92,i,32);for(g(n);n>5;g(n-=2))g(n-4)P" %*c",i,42);}

```

Try it online!

**Unrolled:**

```
#define P;printf(

i;
g(l)
{
    P"%*c", 1+i-l--/2, 60);
    for (; --l P"-"))
    P">\n");
}

f(n)
{
    i=n/2
    P"%*c__\n%*c /\n%*c|\n", i, 95, i, 92, i, 32);

    for(g(n); n>5; g(n-=2))
        g(n-4)

    P" %*c", i, 42);
}

```

# Answer
> 6 votes
# Proton, 83 bytes

Thanks to FlipTack for saving 4 bytes, and for collaborating in chat (we actually form a great team). Indirectly saved 2 bytes thanks to Lynn.

```
o=>[s.center(o)for s:['___','\ /','|']+['<'+"-"*(o-i+2-i%2*3)+'>'for i:4..o]+['*']]

```

Try it online!

# Answer
> 5 votes
# SOGL V0.12, ~~35~~ 30 bytes

```
┌* <++L
%⁽⁄6‘√.⁾δ№{⁽LFL}j *+§Γ

```

Try it Here!

Uses Neil's Charcoal algorithm, takes input as the index in the odd numbers - so 13 would correspond to the input 7

# Answer
> 5 votes
# Charcoal, 28 bytes

```
__⸿ /⸿|Ｆ⮌…¹⊘Ｎ«⸿⊕ι>⸿⊖ι>»‖Ｂ← *

```

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

```
__⸿ /⸿|

```

Print the base.

```
Ｆ⮌…¹⊘Ｎ«

```

Loop from half of the input number down to 1.

```
⸿⊕ι>⸿⊖ι>»

```

Print two lines, the first with one more `-` than the loop index, the second with one fewer.

```
‖Ｂ←

```

Mirror to complete the tree.

```
 *

```

Place the star.

# Answer
> 3 votes
# Retina, 89 bytes

```
.+
$*->
^--
<
+`( *<)----(-+>)$
$&¶  $1$2¶ $1--$2
s`.*¶( +)<->.*
$1___¶$1\ /¶$1 |¶$&¶$1 *

```

Try it online! Explanation: The first stage converts the input to unary and appends a `>`. The second stage replaces two `-`s with a `<` to correct the line length. The third stage then replicates the branch but slightly shorter each time until the branch cannot be shortened any further. The final stage adds the base and the star.

# Answer
> 2 votes
**Javascript** 506 bytes

Golf-version:

```
function tree(i){const mid=(i+1)/2;const leg1=' '.repeat((mid-2))+`___
`;const leg2=' '.repeat((mid-2))+`\\ \/
`;const leg3=' '.repeat((mid-1))+`|
`;let xmasTree=leg1+leg2+leg3;for(let j=0;j<(i-4);j++){if(j%2===0){let v=j/2;let t=i-2*v-2;let body1=" ".repeat(j/2)+"<"+"-".repeat(t)+">"+`
`;xmasTree=xmasTree+body1}else{let k=1+Math.ceil(j/2);let h=i-2*k-2;let body2=' '.repeat(k)+'<'+'-'.repeat(h)+">"+`
`;xmasTree=xmasTree+body2}}
const head=' '.repeat((mid-1))+'*'
xmasTree=xmasTree+head;return xmasTree}

```

Ungolf-version:

```
function tree(i){
  const mid = (i+1)/2;
  const leg1 = ' '.repeat((mid-2)) + `___
`;
  const leg2 = ' '.repeat((mid-2)) + `\\ \/
`;
  const leg3 = ' '.repeat((mid-1)) + `|
`;
  let xmasTree = leg1 + leg2 + leg3;
  for (let j = 0; j<(i-4); j++) {
    if (j%2===0) {
      let v = j/2;
      let t = i-2*v-2;
      let body1 = " ".repeat(j/2)+"<"+"-".repeat(t) +">"+`
`;
      xmasTree = xmasTree + body1;
    } else {
      let k = 1 + Math.ceil(j/2);
      let h = i-2*k-2;
      let body2 = ' '.repeat(k)+ '<'+ '-'.repeat(h) + ">"+`
`;
      xmasTree = xmasTree + body2;
    }
  }
  const head = ' '.repeat((mid-1)) + '*'
  xmasTree = xmasTree + head;
  return xmasTree;
}

```

Usage: `console.log(tree(13)), console.log(tree(17)),`

**ES6** 165 bytes (from my friend)

Golf-version:

```
p=n=>{l=_=>console.log(`${' '.repeat((n-_.length)/2)}${_}`);t=_=>_==1?'*':'<'+'-'.repeat(_-2)+'>';x=n;l('___');l('\\ /');l('|');for(;x!==3;){l(t(x));l(t(x-4));x-=2}}

```

Ungolf-version:

```
p = n => {
  l = _ => console.log(`${' '.repeat((n-_.length)/2)}${_}`);
  t = _ => _ == 1 ? '*' : '<' + '-'.repeat(_-2)+'>';
  x = n;
  l('___');l('\\ /');l('|');
  for(;x!==3;) {
    l(t(x)); l(t(x-4));x-=2;
  }
}

```

Usage: `p(31); p(17);`

# Answer
> 1 votes
# PowerShell, 131 bytes

```
$i=2;$x="$args"..5|%{' '*($j=if($_%2){$i-2}else{($i++)})+'<'+'-'*($_-(5,2)[$_%2])+'>'};($y=' '*++$j)+"___";"$y\ /";"$y |";$x;"$y *"

```

Try it online!

Well, this is a right mess to anyone not conversant in PowerShell... so, let's see how well I can explain how it works.

For the explanation, I'll be using `input = 17`.

We start off simple enough, with setting helper variable `$i=2` and setting `$x` to `<something>`, with the `<something>` starting as a range from the input `$args` down to `5`, so `17,16,15,...,6,5`. That range is pumped into a for loop.

Each iteration, we start with setting helper variable `$j` to be the result of an `if` statement, `if($_%2){$i-2}else{($i++)}`. If it's odd, `$j=$i-2`, otherwise `$j=($i++)`. This, coupled with `$i=2` at the beginning, gives us the sequence `0, 2, 1, 3, 2, 4, 3, 5...` which just so happens to correspond exactly to how many spaces we need to prepend to our tree line. ;-) We take `' '` and string-multiply it out by that number.

Next we need our branches. This is done with `'<'` plus the middle part `'-'` multiplied out, plus the end `'>'`. The multiplication is done by recognizing that the `-` alternate in a `2, 5, 2, 5, 2...` pattern based on the input number `$_`, so we're selecting from a pseudo-ternary based on that pattern.

For further clarification, here are the first couple terms in each section:

```
$_ = 17 16 15 14 13 12 11 10
$j =  0  2  1  3  2  4  3  5
mid=  2  5  2  5  2  5  2  5
'-'= 15 11 13  9 11  7  9  5

```

So now we've set `$x` to be an array of branches (i.e., strings). Outside the loop, we now build our tree "top" with the appropriate number of spaces saved into `$y`, then display our branches `$x`, and then the tree "bottom" with the `*`. Each of those are left on the pipeline and output is implicit with a newline between items.

# Answer
> 1 votes
# JavaScript (ES6), ~~150~~ 147 bytes

```
N=>{for(s=' '[r='repeat'](N/2-1),s+=`___
${s}\\ /
${s} |
`,n=N,l=n=>' '[r](N/2-n/2)+(n-1?`<${'-'[r](n-2)}>
`:'*');n-3;n-=2)s+=l(n)+l(n-4)
return s}

```

```
f=

N=>{for(s=' '[r='repeat'](N/2-1),s+=`___
${s}\\ /
${s} |
`,n=N,l=n=>' '[r](N/2-n/2)+(n-1?`<${'-'[r](n-2)}>
`:'*');n-3;n-=2)s+=l(n)+l(n-4)
return s}

console.log(f(7))
console.log(f(9))
console.log(f(13))
console.log(f(17))
```

# Answer
> 1 votes
# Canvas, 28 bytes

```
-×>＋∔
__¶ /¶|╶┤ｒ⇵｛├⁸¹⁸｝ｋ*∔↔│

```

Try it here!

A port of my SOGL answer which is a port of Neil's Charcoal answer.

# Answer
> 0 votes
```
N=>{for(s=' '[r='repeat'](N/2-1),s+=`___
${s}\\ /
${s} |
`,l=n=>' '[r](N/2-n/2)+n-1?`<${'-'[r](n-2)}>
`:'*');N-=2;s+=l(N)+l(N-4);return s}

```

My attempt at JS ESGoogoltriplex.

```
f=

N=>{for(s=' '[r='repeat'](N/2-1),s+=`___
${s}\\ /
${s} |
`,l=n=>' '[r](N/2-n/2)+n-1?`<${'-'[r](n-2)}>
`:'*');N-=2;s+=l(N)+l(N-4);return s}

console.log(f(7))
console.log(f(9))
console.log(f(13))
console.log(f(17))
```

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


title: Count like Chuck Norris

text:
# Question
Title: Count like Chuck Norris
As is well known,

> Chuck Norris counted to infinity. Twice

Besides,

> Chuck Norris can count to infinity backwards.

Also, although perhaps less known, Chuck Norris can speak a little Spanish in addition to English.

# The challenge

Write a program (or function) that can be run in two different languages. In one language the program should output the sequence

```
1, 1, 2, 2, 3, 3, 4, 4, ...

```

and in the other language it should produce the sequence (including leading zeros)

```
1, 2, ..., 9, 01, 11, 21, 31, ..., 89, 99, 001, 101, 201, ...

```

# Rules

* Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
* Different versions of the same language (such as Python 2/3) don't count as different languages. Related languages (such as C/C++ or Matlab/Octave) do count as different.
* No input will be taken.
* The program should continue to output terms of the sequence until stopped by the user. Since the program will not stop by itself, output cannot be produced at the end. It must be produced while the program runs, either continuously or in batches.
* Output can use STDOUT or equivalent, or can be displayed in a graphic window. Any non-numeric separator between sequence terms is allowed, as long as each term can be clearly distinguished from its neighbouring terms. It is also acceptable if the screen is cleared between terms.
* Either sequence can start at `0` instead of `1`. In that case, in the "twice" sequence the `0` should be repeated, just like the other numbers.
* Leading zeros are significant in the "backwards" sequence. For example, the tenth term is `01`; neither `1` nor `001` are acceptable.
* If the two languages use different character encodings, the program is defined by its *bytes*, not its characters. That is, the bytes should be the same in the two languages.
* Shortest code in bytes wins.

# Answer
> 19 votes
# 05AB1E / Jelly,  ~~14~~  13 bytes

-1 byte thanks to Adnan (avoid triplicate with non-popping print)

Raw bytes (hexadecimal):

```
31 5b 3d 3d 3e 5d fc 06 b6 3b 87 08 15

```

In 05AB1E's code-page:

```
1[==>]üε¶;‡ηΩ

```

**Try it online!**

In Jelly's code-page:

```
1[==>]‘©Ṛ;⁷®ß

```

**Try it online!**

### How?

The 05AB1E program prints the double count with each entry separated by newlines:

```
1[==>]üε¶;‡ηΩ
1             - push 1 onto the stack
 [            - start infinite loop:
  =           - print top of stack
   =          - print top of stack
    >         -   increment the top of the stack (pop(1), x+=1, push)
     ]        - end the infinite loop
      üε¶;‡ηΩ - this code is never executed nor is it parsed

```

The Jelly program prints the reversed count with each entry separated by newlines.

The parser will treat a valid literal between `[` and `]` as the enclosed literal, otherwise these bytes are undefined tokens and as such become equivalent to tokens separating the code into lines. `==>` does not parse as a literal, so the code is effectively:

```
1 - link 1 (not executed but parsed)
1 - literal 1

==> - link 2 (not executed but parsed)
=   - left equals right? (vectorises)
 =  - left equals right? (vectorises)
  > - is greater than the right argument? (vectorises)

‘©Ṛ;⁷®ß - Main link: no arguments
‘       - increment (implicit 0 on left increments to 1 on the first pass)
 ©      - copy the result to the register and yield it
  Ṛ     - reverse, this has an implicit decimal list build, e.g. 142 -> [2,4,1]
    ⁷   - a newline character
   ;    - concatenate, e.g. [2,4,1] -> [2,4,1,'\n']
     ®  - recall the number from the register, e.g. 142
        - The chain has reduced to one item of arity 0, causing a pre-evaluation print:
        -     ...and since the list contains a character it gets smashed together
        -     e.g. [2,4,1,'\n'] prints 241 followed by a newline character
      ß - call this link with the same arity, e.g. as a monad with left = 142

```

# Answer
> 26 votes
# Python 2/C (clang), ~~109~~ ~~107~~ ~~100~~ ~~84~~ ~~95~~ ~~88~~ ~~89~~ ~~88~~ ~~87~~ 84 bytes

```
i=0;
#/*
while 1:i+=1L;print`i`[::-1]
'''*/
a(){for(;;)printf("%i %1$i ",++i);}//'''

```

Python: Try it online!

C: Try it online!

The L in the Python code is part of the delimiter.

**Explanation:**

In the C code, It first sets i to 0. Then, it starts a comment (`#` is valid code in C for `#include` statements) where the Python code goes. At the end of the comment, it defines a function that forever increments a variable and prints it twice, space-delimited. It then begins a comment.

In the Python code, `i=0;` sets i to zero. Python ignores the next line because `#` starts a single-line comment. It then forever increments it and turns it into a long a number and prints its reversed string representation. The 'L' from the long is part of the delimiter. After that, it starts a multi-line string to comment the C code, that ends later.

-2 bytes thanks to @LuisMendo. -7 bytes thanks to @ZacharyT. -6 more bytes thanks to @ZacharyT. +11 bytes to fix a bug thanks to @mbomb007. -7 bytes thanks to @Doorknob. +1 byte to fix a bug thanks to @Doorknob. -1 byte thanks to @yoann. -1 more byte thanks to @yoann. -3 bytes thanks to @Cyoce.

# Answer
> 12 votes
## Jelly/Pyth, 15 bytes

```
.V1_`b;"1üÉÉ$

```

Unprintables are mangled by the SE software, so here's a hexdump:

```
00000000: 2e56 315f 6062 3b22 7f31 fcc9 c924 0b    .V1_`b;".1...$.

```

Run with `jelly f file` and `pyth file` respectively.

### Explanation

First comes the Pyth part. `.V` runs an infinite loop over the incrementing sequence starting from its input, which is here `1`. Then we reverse (`_`) the stringified (```) loop index (`b`) and implicitly output it. The `;` is there to end the loop, and the `"` is necessary to treat the rest of the program as a string literal so that the parser doesn't choke on it.

The Jelly part will be explained by first translating the remainder of the program from the Jelly codepage:

```
¶1‘ṄṄ$¿

```

The  acts as a line feed, effectively ignoring the first part of the program by making it a link that is never called. Then we start at `1` and run a while loop (`¿`) that uses `ṄṄ$` (print twice) as its condition, and increments () the value as the loop body.

---

Incidentally, replacing the Pyth part with `1[DR,>]` *would* create a valid Jelly/05AB1E submission in 14 bytes, but the current interpeter contains a bug that prevents this.

# Answer
> 11 votes
## Perl/JavaScript, 87 bytes

```
s=0;print=console.log;m=s;$_=s=s=s=m;while(++$_){print((m/s,$_+`
`+$_||/&&reverse.$/))}

```

### Perl

```
s/0;print/console.log;m/s;$_=s/s/s/m;while(++$_){print((/s,$_+`
`+$_||/&&reverse.$/))}

```

A mechanism I've used a lot in JS/Perl polyglots is to abuse the fact that substitution can accept pretty much any delimiter, using `=` means I can use the initial pointless substitutions (first replacing `0;print` with `console.log;m` with a flag of `/s` in `$_`, which is currently `undef`), then setting `$_` to the result of replacing `s` with `s` in multiline mode (`/m`), which is `0`. Now `$_` is `0` and I start the `while` loop, this then increments `$_`. Next I call `print`, passing in a regular expression that matches (due to `||` at the end which matches an empty string) and use the `&&` operator to then send the reverse of `$_` concatenated with a newline (`$/` is pre-initialised to `"\n"`). This counts to infinity backwards.

### JavaScript

```
s=0;print=console.log;m=s;$_=s=s=s=m;while(++$_){print((m/s,$_+`
`+$_||/&&reverse.$/))}

```

Lots of variable assignments here, masked in the Perl `s///` calls. I set up variables `s` and `m` as `0`, alias `console.log` to `print`, run some pointless division, set `$_` to `0` and begin the `while` loop incrementing `$_`, call `print` passing in `0` (`m/s`, this starts the call to `m` in Perl, but is treated as standard division in JS) and our target string (`$_+"\n"+$_`) via the comma operator, which returns the last item in the list. I avoid the last piece of Perl code (`&&reverse.$/`) because `$_+"\n"+$_` will be truthy and so I can use `||` to produce a `RegExp` object containing the end of the Perl code which is never evaluated.

Tested using Perl 5 and Node 6.

# Answer
> 8 votes
# NodeJS / PHP, ~~131~~ 106 bytes

*-25 bytes thanks to @Titus*

```
<!--
printf=(_,i)=>process.stdout.write(i+i),strrev=i=>i+" "//--><?
for($i=0;;)printf("%s ",strrev($i++));

```

Using NodeJS instead of browser JS for better output formatting and better infinite loop handling.

Try the JavaScript online
Try the PHP online

Note that the TIO output is cut off after 128KB.

# Answer
> 7 votes
# /Brain-flak Classic, ~~27~~, 26 bytes

```
(()){[[({}())[]]]}é1òÙæ_æ

```

Hexdump:

```
00000000: 2828 2929 7b5b 5b28 7b7d 2829 295b 5d5d  (()){[[({}())[]]
00000010: 5d7d e931 f2d9 e65f 01e6                 ]}.1..._..

```

Try it online! in V (modified slightly so that it will terminate so you can see the output. On TIO, V only outputs if the program terminates)

Try it online! in Brain-flak Classic

This isn't the most interesting of polyglots, since the V code has no effect on brain-flak classic, and vice-versa, however it's really fun to use both of my own languages on a challenge, and the two solutions are pretty interesting on their own.

V Explanation:

```
é1              " Insert a '1'
  ò             "   Recursively:
   Ù            "   Duplicate this number
    æ_          "   Flip this line
      <C-a>     "   Increment the number on this line
           æ    "   Flip it back (the '_' is implicit because it's at the end of the program)

```

BFC explanation:

```
#Push a one onto the main stack
(())

#Forever:
{

  #Print twice:
  [[

    #Increment the top of the stack.
    #Evaluates to *i + 1*
    ({}())

    #Minus one
    []
  ]]

#Endwhile
}

```

# Answer
> 4 votes
# Retina / Python 2, 61 bytes

```
#{*M`
#*M`
"""

}`$
1
""";i=1
while 1:print str(i)[::-1];i+=1

```

**Retina** | **Python 2**

# Answer
> 3 votes
# /Octave, ~~83~~ ~~80~~ ~~78~~ 71 bytes

*-3 bytes thanks to Luis Mendo*

```
i=0;
while(1)
#{
print(c(i<-i+1,i))
#}
disp(flip(num2str(i)))
i+=1;
end

```

`#{ }#` is an Octave block comment and `#` just so happens to be the comment for R. The R interpreter only sees the next line as the body of the `while` loop, and the Octave interpreter skips right ahead to the Octave code

The R part prints out pairs of numbers starting at 1, and the Octave portion prints out the backwards numbers starting at 0.

I fully expect to be outgolfed (even by the same combination of languages); I've just been writing so much Matlab and R code recently that I figured I'd give it a shot.

Try it online! \- Octave link

# Answer
> 3 votes
# CJam / \>\<\>, ~~27~~ 23 bytes

```
"la,:naonao
"1{_sW%n)}h

```

## To CJam:

Try it online! \- note that you have to wait until the 60 second limit to see the output, but it works offline.

```
"la,:naonao
"

```

This defines a multi-line string literal that is never used.

```
 1{_sW%n)}h

```

The second line goes like this:

```
1     e# Push 1:               | 1
{     e# Forever:              | 1
  _   e#   Duplicate:          | 1 1
  s   e#   Convert to string:  | 1 "1"
  W%  e#   Reverse:            | 1 "1"
  n   e#   Print with newline: | 1
  )   e#   Increment:          | 2
}h    e# End loop

```

## To \>\<\>:

```
"

```

Begins a string literal.

```
 la,:naonao

```

Content of the string literal. Each of the character codes is individually pushed to the stack.

```
"

```

The IP wraps around to reach `"` again, which ends string mode.

```
 la,

```

`l` takes the length of the stack, `a` pushes 10, and `,` divides. This gives us the length of the stack / 10.

```
    :nao

```

`:` duplicates, `n` prints as a number, `a` pushes 10, and `o` prints as a character code (a newline).

```
        nao

```

Same thing. Print the number followed by a newline. The stack now has length 10 again (the original string literal's content is on the stack).

The IP then wraps around to the `"` again, leading to 10 more elements to be pushed. Next time, `l` returns 20, so 2 is printed, etc.

The second line is never touched by the IP.

# Answer
> 3 votes
## Bash / Check, ~~50~~ 28 bytes

<sup>Thanks to @Doorknob for saving a bunch of bytes by switching from Python to Bash</sup>

```
#>
#v
 #p<p<)#
seq 1 inf|rev

```

### To Bash:

```
#>
#v
 #p<p<)#

```

These are just some comments, which are ignored.

```
seq 1 inf|rev

```

Start a sequence going from 1 to infinity, then pipe the result to `rev`.

### To Check:

```
#>

```

This immediately switches into 2D mode, going right. `>` directs the IP right, which has no effect. It wraps around to the beginning of the line and hits `#` again, which switches out of 2D mode. It then hits `>` in 1D mode, which pushes 0 to the stack. Because it is in 1D mode, the IP wraps to the next line.

```
#v

```

`#` switches the IP into 2D mode again and `v` directs it downwards.

```
 #p<p<)#

```

The first `#` switches back to 1D mode again. `p` outputs the TOS as a number (but does not pop it), and then `<` prints a newline. This is done twice, and then the number is incremented with `)`. `#` switches to 2D mode again, so the IP wraps to the beginning of the line, hits `#` to switch to 1D mode, etc.

# Answer
> 3 votes
# Ruby / Python2: ~~68~~ 64 bytes

```
i=0
"#{loop{p i+=1,i}}"
exec('while 1:print str(i)[::-1];i+=1')

```

### Ruby perspective

simple init of variable:

```
i = 0

```

`"#{}"` is syntax for string interpolation. I use it to exec expression instead.

```
"#{loop{p i+=1,i}}"

```

`p` is a shorthand for `puts`. `loop` creates an infinite loop.

Next there is the `exec` thing, but it never gets evaluated, as the infinite loop is by definition infinite. Needed `exec` not to yield syntax error with Python code.

### Python perspective

From perspective of Python, there is a common `i=0`. Next, Python has different syntax for string interpolation, so this line is simply discarded. Next there is an infinite loop similar to what others posted.

# Answer
> 2 votes
# QBIC / QBasic 4.5, 58 bytes

```
do
p=p+1
if q then
'?`_f!p$|
else
?p,p,
end if
loop

```

This heavily abuses the fact that all lowercase letters are seen as literal QBasic code by the QBIC interpreter and are therefor just passed along to the QBasic layer of QBIC. How both languages see this code, side by side:

```
LOC         QBasic                    QBIC
-------------------------------------------------------
do                   Start an infinite loop
p=p+1                Increment p, starts off as 0
if q then    q = 0, goto ELSE         q = 1, execute IF
'?`_f!p$|    ' = comment, invalid     '?` is a 'code literal', passing PRINT to QBASIC
             syntax is ignored        followed by QBIC code to flip p cast as string.
else         q=0, execute             q=1, so ignored
?p,p,        PRINT p twice,
             separated by tab
end if               End of the branching logic
loop                 Wrap around for the next pass

```

# Answer
> 2 votes
# Röda/C (gcc), 90 bytes

```
main(){f(0);}f(a){a=1//1{[` $a`[::-1]];a++}while[]/*
;for(;;a++)printf("%d %d ",a,a);/**/}

```

Röda: Try it online!

C: Try it online!

### Explanation

This abuses the fact that `//` is int divison in Röda but a line comment in C.

In both languages, `main(){}` denotes the main program, and they both call function `f` with a dummy argument of `0`.

In Röda, `a=1//1` does int division and assigns the result `1` to `a`. C sees `a=1` and does the same thing, but everything after that assignment is a comment for C. From there, the two languages branch off.

**Röda**

We have an infinite loop with `while[]` (an empty condition is truthy). Inside that, `` $a`` converts the integer `a` into a string (with a leading space) after which `[::-1]` reverses it (and it outputs with a trailing space). Then the value of `a` is incremented by one.

Outside of the while loop, a multiline comment starts `/*` and ends just before the end of the function.

**C**

After having ignored the rest of the line, the program goes to the second line. We start with a semicolon because the `a=1` statement needs to be terminated. After that, we encounter a simple for loop that prints the iterating variable, `a`, twice on each iteration.

Outside of the for loop, the `/*` is just there to ignore Röda's ending `*/` comment.

# Answer
> 2 votes
# laserLANG / \>\<\>, 163 bytes

```
!\0 \
/:+1/!   ]oo\
\:a( ?\:a%$a ,!
/r[-1l//" ,"/
/!n-%1:\?(1l
 \ --\/ <<---\
/----/'
\----  v
/>>--\#>---->/
\     /
/----<
\  \
/ -<< \
 /<< \
 "
">=>= /
\>=>=/

```

First time golfing, so it's a bit larger than it probably could be. I wanted to use \>\<\>, but since a few people already used it to create the second sequence, I decided I wanted to give creating the first sequence a go.

Try \>\<\> online!
For laserLANG, an offline interpreter is needed to try it. It can be found here.

**laserLANG**

```
!\
 \ --\/ <<---\
/----/'
\----  v
/>>--\#>---->/
\     /
/----<
\  \
/ -<< \
 /<< \
 "
">=>= /
\>=>=/

```

execution starts at `!` which is ignored completely. it then reaches the `\` and starts traveling down past several characters that it completely ignores. Finally it reaches another `\` and the fun begins. I basically took the idea behind the "Hello, World!" loop and condensed it as well as I could. It was a bit of a challenge dealing with the fact that laserLANG is only about to decrement/increment the memory counter when the program counter is going left/right respectively. I feel like the most bytes could be saved here by doing some tricks I haven't thought of.

**\>\<\>**

```
!\0 \
/:+1/!   ]oo\
\:a( ?\:a%$a ,!
/r[-1l//" ,"/
/!n-%1:\?(1l

```

Execution starts at `!` which causes it to skip the `\`. It then continues on as if the laserLANG code wasn't there. I didn't realize \>\<\> *only* had support for float division, so a short and simple truncation was a bit confusing at first.

# Answer
> 2 votes
# Befunge-98/\>\<\>, 32 bytes

```
\r.#%a/# :_::p#+a#1,#
>l::naonao

```

Wrote this before I saw how many `><>` answers there were. Some background: `\` is a direction changing operator in \>\<\>, in this case pushing it down, while in Befunge it swaps the top two items on the stack. The Befunge code looks like:

```
\r.#%a/# :_::p#+a#1,#

```

Try it online!

Prints out the backwards numbers separated by newlines. Befunge prints a space automatically after each number, so each digit is separated by spaces. Repeatedly gets the last digit, prints it and divides the number by 10 until it is 0. Then increment and repeat.

The \>\<\> code immediately goes down to the second line.

```
>l::naonao

```

Try it online!

And is pretty simple. Get length of stack, print twice with newlines and leave a copy of the length on the stack for the next loop.

# Answer
> 1 votes
# \>\<\> / Jelly, 37 bytes (25 in Jelly's codepage)

```
01+:nao:nao!
DU;⁷Ṙ€
®‘©Çß

```

Try \>\<\> online!

Try Jelly online!

**\>\<\>** prints the sequence to infinity twice, **Jelly** counts backwards.

**\>\<\>** is only concerned with the top line:

*And thanks to @Challenger5 for saving some bytes here on the linefeed*

```
01+:nao:nao!                           Stack at: 1st run   2nd run ...
0                 Push a 0             0         -
 1                Push a 1             0,1       1,1
  +               Pop 2, add them      1         2
   :              Duplicate top item   1, 1      2, 2
    n             Pop top, show as num 1         2
     a            Push the number 10   1, 10     2, 10
      o           Pop and show 10 as an ACII char (ie '\lf')
                                       1         2
         :nao     And again, for repetition
             !    ><> wraps around; this skips pushing a 0 again.

```

**Jelly** executes its code bottom-to-top. Only the last 2 lines are relevant.

```
®‘©Çß       main link, keeps track of the current number

®           Get a number from the register (0 on first run)
 ‘          Increment that by 1
  ©         Store in register
   Ç        Call helper (printer) link
    ß       Call this link again

DU;⁷Ṙ€      Printer

            (Say we are at number 21)
D           Break into digits         [2, 1]
 U          Reverse array             [1, 2]
  ;⁷        Append a line break       [1, 2, \n]
    Ṙ€      Print each char in array

```

# Answer
> 1 votes
# Ruby/Stacked, 37 bytes

```
0#/0[1+:tostr rev out]
loop{p p$.+=1}

```

Try it online!

This prints `1 1 2 2`... in Ruby and `1 2 3 ... 01 11 21...` in Stacked.

## Explanation

### In Ruby:

```
0#/0[1+:tostr rev out]
loop{p p$.+=1}

```

After removing the comment, this becomes:

```
0
loop{p p$.+=1}

```

The only relevant line here is the last. `p` returns its argument, so `p p` prints its argument twice. `$.` starts at `0`, so `$.+=1` increments `$.`, returning the incremented value. Therefore, this prints each number from `1` twice.

### In Stacked:

```
0#/0[1+:tostr rev out]
loop{p p$.+=1}

```

This is equivalent to the following tokens:

```
0 #/ 0 [ 1 + : tostr rev out ] loop { p p $ . + = 1 }

```

The first two are not relevant (basically, transforming `0` into a reduce f Unction). Then, `0` is pushed to the stack. After, the function `[1+:tostr rev out]` is pushed to the stack. `loop` pops this function and executes it infinitely.

The inside of the function increments the top of the stack (`1+`), duplicates it (`:`), converts it to a string (`tostr`), reverses it (`rev`) and outputs it (`out`). This process is repeated infinitely. Since the loop is infinite, anything that comes after that token is essentially ignored by the interpreter.

# Answer
> 1 votes
# C (gcc)/PHP, ~~102~~ ~~86~~ 80 bytes

```
#//\
for(;;)echo strrev(++$i).'
int main(i){for(;;i++)printf("%d %d ",i,i);}//';

```

Outputs the double sequence in C and the reverse sequence in PHP.

Try it in C!

Try it in PHP!

## Explanations

### C

In C, the `#` forms preprocessor stuff. I don't really know much about C but it doesn't complain when there's any empty line for this stuff. The `//` forms a line comment. A `\` at the end of a line is essentially "escaping" the newline and making the two lines be treated as one. This also works for line comments, so the second line is seen as a comment in C. The third line does the work of outputting the numbers with a simple for loop. Afterwards, there is simply a comment.

### PHP

In PHP, `#` forms a line comment, so the first line is ignored entirely. The second line prints the numbers reversed with a for loop, and separates them with `\nint main(i){for(;;i++)printf("%d %d ",i,i);}//` (the C code wrapped in a string).

---
Tags: code-golf, number, sequence, integer, polyglot
---


title: R[oman|everse] Polish Notation

text:
# Question
Title: R[oman|everse] Polish Notation
It is the year MDLXVII in a world in which the Roman Empire never fell, and the collapse into the dark ages never occurred. Due to the extended period of Pax Romana, the empire's economic stability enabled technology to progress at a rapid rate.

The Romans have begun to dabble with circuitry, and have invented an ingenious calculator that doesn't require the use of an "equals" button. They call it "Roman Polish Notation"

To make a calculation, they enter their operands first, then the operation.

For example, 100 + 11 * 20 would be `C XI XX * +`.

**Additionally**

The Romans have found that they often need to make multiple calculations at the same time, and would prefer for the method to return every value "on the stack" in some sort of array/list/tuple-like structure. (e.g. `X I + X I - CC II +` would return \[11, 9, 202\])

---

The challenge is to develop a calculator program capable of making these computations.

**Clarification**: Subtractive Notation is required. I hadn't realized it wasn't recognized feature in the Ancient Roman empire. The task was therefore ambiguous, and I apologize.

**Minimum Guidelines**

* Your output will be in Arabic Numerals.
* You only need to convert from Roman Numerals up to 5000.
* You will need to support +, -, /, * operations (addition, subtraction, division, and multiplication).
* Whether division is floating point based or integer based is implementation specific. Either works for this challenge.
* Your output will need to support numbers up to 4 Billion.
* Shortest answer overall, AND in each language wins. This is a Code Golf Challenge but I love the variety.

In the event of a tie, ~~factors like support for roman numerals above 5000 or additional operations will be considered~~ the earliest submission will win.

# Answer
> 6 votes
# Python 2 \+ roman, 118 bytes

```
from roman import*
s=[]
for i in input().split():s+=[eval(s.pop(-2)+i+s.pop())if i in"+-/*"else`fromRoman(i)`]
print s

```

### Demo

It cannot be tested online because of the module it makes use of, but you can see how to run this here (a full program accepting input from STDIN – an expression with quotes – and printing the output to STDOUT – in the form of a list, the stack). Uses a slightly older version, because I won't bother to create a new GIF for only a few bytes:

To install the package, you can run the following in the Terminal / Command Line:

```
pip install roman

```

# Answer
> 6 votes
# Haskell, 217 bytes

*-13 bytes thanks to Bruce Forte. -73 bytes thanks to Ørjan Johansen.*

```
foldl(!)[].words
s@ ~(x:y:z)!n=last$(a n:s):[y`f`x:z|(f,c)<-zip[(+),(-),(*),(/)]"+-*/",n==[c]]
a s=last$0:[n+a(drop(length x)s)|(n,x)<-zip l$words"I IV V IX X XL L XC C CD D CM M",x<=s,x++"Y">s]
l=[1,4,5,9]++map(10*)l

```

Try it online!

Manual implementation, yay!

# Answer
> 3 votes
# SOGL V0.12, 57 bytes

```
θ{:u=?F!!}F:u=‽0AøF{1"IVXLCDM”GWH∫2%3*⁽*}aa⁵<⌡±;A}a¹∑ι}}⁰

```

Try it Here!

# Answer
> 2 votes
# JavaScript (Node) + romans \+ stk-lang, 74 bytes

```
s=>(R=require)("stk-lang")(s.replace(/\w+/g,R("romans").deromanize)).stack

```

Returns a list of bigintegers.

## Execution

Run the following:

```
npm install romans
npm install stk-lang
node

```

Then paste the function. Example:

```
C:\Users\conorob\Programming\golf-new\roman
λ npm install romans
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json'
npm WARN Programming No description
npm WARN Programming No repository field.
npm WARN Programming No README data
npm WARN Programming No license field.

+ romans@1.0.0
added 1 package in 0.801s

C:\Users\conorob\Programming\golf-new\roman
λ npm install stk-lang
npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json'
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\conorob\Programming\package.json'
npm WARN Programming No description
npm WARN Programming No repository field.
npm WARN Programming No README data
npm WARN Programming No license field.

+ stk-lang@1.0.0
added 1 package in 0.847s

C:\Users\conorob\Programming\golf-new\roman
λ node
> s=>(R=require)("stk-lang")(s.replace(/\w+/g,R("romans").deromanize)).stack
[Function]
> f=_
[Function]
> f("X I + X I - CC II +").map(e => e.toString())
[ '11', '9', '202' ]
> f("C XI XX * +").map(e => e.toString())
[ '320' ]
> f("MMMM M I - +").map(e => e.toString())
[ '4999' ]

```

# Answer
> 2 votes
# Dyalog APL, 93 bytes

```
⎕CY'dfns'
a←⍬⋄{0::{a,←⍵}roman⍵⋄f←⍎'+-÷×'⌷⍨'+-/*'⍳⍵⋄r←f/¯2↑a⋄a↓⍨←¯2⋄a,←r}¨{1↓¨⍵⊂⍨⍵∊' '}' ',⍞⋄a

```

Try it online!

116 bytes without the roman built-in

# Answer
> 1 votes
# Python 3, ~~280~~ 206 bytes

```
N=dict(I=1,V=5,X=10,L=50,C=100,D=500,M=1000)
def d(s):
	n=0
	for v in map(N.get,s):n+=v-n%v*2
	return n
def c(w):
	s=[]
	for t in w.split():s+=[str(d(t)if t[0]in N else eval(s.pop(-2)+t+s.pop()))]
	return s

```

Try it online!

This time with subtractive notation support. Method `c` is the main entry point; the other is support.

Edit log:

# Answer
> 0 votes
# JavaScipt (ES6), ~~152~~ 151 bytes

*Saved 1 byte thanks to user202729*

```
p=>p.split` `.map(c=>s.push(eval("+-/*".indexOf(c)+1?(T=s.pop(),s.pop())+c+T:c.replace(/./g,c=>"+"+{I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[c]))),s=[])&&s

```

## Test cases

```
f=p=>p.split` `.map(c=>s.push(eval("+-/*".indexOf(c)+1?(T=s.pop(),s.pop())+c+T:c.replace(/./g,c=>"+"+{I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[c]))),s=[])&&s
console.log(f("C XI XX * +"))
console.log(f("X I + X I - CC II +"))
```

## Explanation (less golfed)

```
V={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}     // Values of the roman numerals
p=>(
 s=[],                                      // Initialize the stack
 p.split` `.map(c=>                         // For every part in the input:
  "+-/*".indexOf(c)+1?                      //   If the input is an operator:
   s.push(eval((T=s.pop(),s.pop())+c+T))    //     Evaluate the operator on the top of the stack
  :                                         //   Else (if it is a roman numeral):
   s.push(eval(c.replace(/./g,c=>"+"+V[c])))//     Push the sum of the characters' values
 ),s)                                       // return the stack

```

# Answer
> 0 votes
# Jelly, 82 bytes

```
ị“+-×÷”;”/v®ṫ-¤®ṖṖ¤;©
4Ḷ⁵*p1,5P€
“IVXLCDM”iÐ€ị¢µIN‘Ṡæ.µ®;©
Ḳµ“+-*/”W€i⁸Ñ⁸Ç¤¹?µ€ṛ®Ḋ

```

Try it online!

Originally posted in chat.

---

Explanation:

Because Jelly doesn't have a stack, I put the stack in the register.

When the program starts, the register value `®` is `0`, which is treated as `[0]` for the purposes of this program.

```

ị“+-×÷”;”/v®ṫ-¤®ṖṖ¤;©       Link 1: Given an operator index (an
                            integer in range 1..4), apply it.

ị“+-×÷”                     Index to the string "+-×÷"
       ;”/                  Concatenate with the character "/",
                            which is Jelly splat operator.
          v   ¤             Evaluate with parameter...
           ®                  the register's
            ṫ                 tail
             -                from -1. (2 last items)
               ®  ¤;        Concatenate with the register value,
                ṖṖ            pop twice.
                    ©       Store the result to register.

4Ḷ⁵*p1,5P€          Link 2: Niladic, generate [1,5,10,50,...]
4Ḷ                  Lowered range of 4, gives [0,1,2,3].
  ⁵*                Raise to power of 10. Value = 1,10,100,1000.
    p1,5            Calculate Cartesian product with [1,5].
                      Value = [1,1],[1,5],[10,1],[10,5],...
        P€          Calculate product of each item.

Alternatively, ×þ1,5F would also work instead of p1,5P€.

“IVXLCDM”iÐ€ị¢µIN‘Ṡæ.µ®;©   Link 3: Given roman number, push it
                            to the stack (register).
         i                  Find index of ...
          Ð€                  each character ...
“IVXLCDM”                     in "IVXLCDM".
            ị¢              Index to last link. (link 2)
              µ             With that value, (consider LIX ->
                            [50,1,10] for example)
               I
Ḳµ“+-*/”W€i⁸Ñ⁸Ç¤¹?µ€ṛ®Ḋ

[TODO complete explanation]

```

# Answer
> -1 votes
# Python 3, ~~216~~ 187 bytes

```
from operator import*
N=dict(I=1,V=5,X=10,L=50,C=100,D=500,M=1000)
def f(w):
	s=[]
	for t in w.split():s+=[str(sum(map(N.get,t)))if t[0]in N else str(eval(s.pop(-2)+t+s.pop()))]
	return s

```

Try it online!

Because it came up in the comments of both the question and this answer and likely led to down-votes: **this submission doesn't support subtractive notation.** Rationale: Subtractive notation was rarely used in the Roman Empire and only popularised later (see Subtractive Notation, paragraph 3, last sentence). The task presumes a Roman Empire that developed programmable integrated circuits, not one that underwent the same cultural changes as 13th century Europe. The description doesn't mention subtractive notation and none of the examples uses it.

---
Tags: code-golf, parsing
---


title: Prefixless Palindromes

text:
# Question
Title: Prefixless Palindromes
Write a program or function that takes **N**, and **S** and outputs the number of palindromes of length **S** you can build using an alphabet of size **N** such that any prefix of size between **2** and **S-1** is not a palindrome.

For example if **N** were **2** and **S** were **5**

The valid palindromes would be

```
01110
10001

```

And thus the answer would be 2

This is so answers will be scored in bytes based on their length with fewer bytes being better.

# Answer
> 4 votes
# Jelly, 10 bytes

```
ṗŒḂƤ€Ḋ€Ḅċ1

```

This is a brute-force search over all **ns** possible strings.

My results differ from the other answers', but the solutions my answer counts seem to be valid.

Try it online!

# Answer
> 1 votes
# Pyth, 16 bytes

```
lf!tit_IM._T2^SE

```

**Try it here!**

My answer agrees with Dennis' results, rather than the Haskell and the Python answers.

### How it works

```
lf!tit_IM._T2^SE | Full program.

              SE | Grab the second input (E), make an integer range from 1 ... E.
             ^   | And take the Qth Cartesian Power, where Q is the first input.
 f               | Filter by a condition that uses T as a variable.
         ._T     | Take all the prefixes of T...
      _IM        | And for each prefix, check if they're invariant over reversal.
     t           | Take the tail (remove the first element).
    i       2    | Convert from base 2 to integer.
  !t             | Decrement, negate. Note that among the integers, only 0 is falsy.
l                | Take the length of the filtered list.

```

# Answer
> 1 votes
# Husk, 19 bytes

```
Lf(=1ḋ↔mS=↔‼hU¡h)πŀ

```

Try it online or view the solutions!

### Explanation

```
Lf(=1ḋ↔mS=↔‼hU¡h)πŀ  -- takes two arguments N S, example: 2 4
                  ŀ  -- range [0..N-1]: [0,1]
                 π   -- all strings of length S: [[[0,0,0,0],[0,0,0,1],…,[1,1,1,1]]
 f(             )    -- filter with the following predicate (example with [0,1,1,0]):
              ¡h     --   infinitely times take the head & accumulate in list: [[0,1,1,0],[0,1,1],[0,1],[0],[],[],…
             U       --   only keep longest prefix with unique elements: [[0,1,1,0],[0,1,1],[0,1],[0],[]]
           ‼h        --   get rid of last two (apply twice head): [[0,1,1,0],[0,1,1],[0,1]]
       m             --   map the following
        S=           --     is itself equal to..
          ↔          --     .. itself reversed?
                     --   ↳ [1,0,0]
      ↔              --   reverse: [0,0,1]
     ḋ               --   convert from binary: 1
   =1                --   is it equal to 1: 1
                     -- ↳ [[1,0,0,1],[0,1,1,0]]
L                    -- length: 2

```

# Answer
> 0 votes
# Clean, 129 bytes

```
import StdEnv,StdLib
?l=l==reverse l
@n s=sum[1\\p<-iter s(\a=[[e:b]\\e<-[1..n],b<-a])[[]]|and[?p:[not(?q)\\q<-inits p%(2,s-1)]]]

```

Try it online!

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