title: Heart Point Generator

text:
# Question
Title: Heart Point Generator
It's mentioned last time that, in Hearts,

> Each round every player gets a non-negative amount of *points*. The sum of the points is 26, and at least one player gets 13 or more points.

Actually, it's the game part:

1. Average the 52 cards (♠♡♢♣ * 23456789 10 JQKA) to the 4 players
2. The player with a ♣2(the smallest value) starts the first hand
3. The player who play a largest value with same suit to the hand starter on `i`-th hand (`1<=i<=13`):

* Add 1 to his point for each ♡ in this hand
* Add 13 to his point if ♠Q is in this hand
* starts `(i+1)`th hand (`1<=i<=12`)

There's some playing rules:

1. On the first hand, ♣2 should be played.
2. If possible, no ♡ or ♠Q on the first hand.
3. If possible, non-starter should play starter's suit
4. If possible, the hand starter can't play ♡ if it isn't played.

Now given the point of 4 players, generate a valid game that lead to the point result. You can assume that it's possible. Output is flexible, you can choose any 52 values to mean the 52 cards (This is the explained output below, so there's no fear that you have to encode the output in a specific way)

Sample:

```
Input 13   0   0  13
Hand1 ♣5 [♣2] ♣3  ♣4
    2[♣9] ♣8  ♣7  ♣6
    3[♣A] ♣10 ♣J  ♣Q
    4[♣K] ♡10 ♡J  ♡Q
    5[♢7] ♢5  ♢4  ♢6
    6[♢A] ♢3  ♡A  ♢2
    7[♢K] ♡8  ♡7  ♡6
    8[♢Q] ♡5  ♡4  ♡3
    9[♢J] ♡2  ♠4  ♡9
   10[♢10]♡K  ♠6  ♠7
   11[♢9] ♠8  ♠10 ♠9
   12[♢8] ♠J  ♠A  ♠K
   13[♠3] ♠5  ♠2  ♠Q
                 [  ]

```

Sample:

```
Input 26   0   0   0
Hand1 ♣5 [♣2] ♣3  ♣4
    2[♣9] ♣8  ♣7  ♣6
    3[♣A] ♣10 ♣J  ♣Q
    4[♣K] ♡10 ♡J  ♡Q
    5[♢7] ♢5  ♢4  ♢6
    6[♢A] ♡K  ♢3  ♢2
    7[♢K] ♡8  ♡7  ♡6
    8[♢Q] ♡5  ♡4  ♡3
    9[♢J] ♡2  ♡A  ♡9
   10[♢10]♠5  ♠6  ♠7
   11[♢9] ♠8  ♠10 ♠9
   12[♢8] ♠J  ♠A  ♠K
   13[♠Q] ♠4  ♠3  ♠2
     [  ]

```

Sample:

```
Input 23   1   1   1
Hand1 ♣4 [♣2] ♣3  ♣5
    2 ♡2  ♣8  ♣7 [♣6]
    3 ♡3  ♣10 ♣J [♣9]
    4 ♡4  ♣A [♣Q] ♣K
    5 ♡6 [♡5] ♢4  ♢6
    6[♡A] ♢2  ♢3  ♢5
    7[♡7] ♢7  ♢8  ♢9
    8[♡8] ♢10 ♢J  ♢Q
    9[♡9] ♢K  ♢A  ♠Q
   10[♡10]♠5  ♠6  ♠7
   11[♡J] ♠8  ♠10 ♠9
   12[♡Q] ♠J  ♠A  ♠K
   13[♡K] ♠4  ♠3  ♠2
     [  ]

```

Here a `[]` means starter, which you needn't output. Also it's absolutely not a game that would happen in real play, but it's just valid.

This is code-golf, shortest code in each language wins.

# Answer
# Python, 676 bytes

```
R=range
def f(s):
    c,y=[0,13]+([2,1,2,2][(i:=s[0]==14):i+3],[2,2,1])[s[0]%2]+[1]*8,[]
    r=p=0
    for j,i in enumerate(c):
        r+=i
        if r==s[p]:y.append(j+1);r=0;p+=1
    p,t=y[:-1],c[2:5]
    h=[[(1,12)]+[(0,12),(0,11)]+[(0,9-x)for x in R(10)],[(1,0)]+[(2,x+1)for x in R(12)],[(1,11),(0,10)]+[(3,0),(3,1)]+[(1,x+1)for x in R(9)],[(1,10),(2,0)]+[(3,12-x)for x in R(11)]]
    for i in R(len(p)):
        k=p[i]
        if i==0:h[0][k],h[1][1]=h[1][1],h[0][k]
        if i==1:q=p[0];h[1],h[2]=h[1][:q]+h[1][q+1:k+1]+[h[2][k-1]]+h[1][k+1:],h[2][:q]+[h[1][q]]+h[2][q:k-1]+h[2][k:]
        if i==2:h[2],h[3]=h[2][:-1]+[h[3][-1]],h[3][:k]+[h[2][-1]]+h[3][k:-1]
    h[2][2:5]=[sorted(h[2][2:5]).pop(1-i)for i in t]
    return h
```

Attempt This Online!

Takes the input as a reverse sorted list of scores. Returns a list of the cards in each hand, ordered by round. Cards are encoded as `(suit, value)`, where `suit` and `value` are indexes of `"♠♣♢♡"` and `['2','3','4','5','6','7','8','9','10','J','Q','K','A']`  respectively. Works by rearranging the master arrangement

```
Hand 1  ♣A  [♣2]  ♣K   ♣Q
     2 [♠A]  ♢3   ♠Q   ♢2
     3 [♠K]  ♢4   ♡2   ♡A
     4 [♠J]  ♢5   ♡3   ♡K
     5 [♠10] ♢6   ♣3   ♡Q
     6 [♠9]  ♢7   ♣4   ♡J
     7 [♠8]  ♢8   ♣5   ♡10
     8 [♠7]  ♢9   ♣6   ♡9
     9 [♠6]  ♢10  ♣7   ♡8
    10 [♠5]  ♢J   ♣8   ♡7
    11 [♠4]  ♢Q   ♣9   ♡6
    12 [♠3]  ♢K   ♣10  ♡5
    13 [♠2]  ♢A   ♣J   ♡4
       [  ]

```

as needed to give the correct score.

Interestingly, I believe there are only 87 unique test cases. This is based on the assumption that `[n,n,n,1]` is an impossible score, as it is impossible for the lowest scoring hand to win a trick without gaining a score of two or having an illegal move prior. However, I'm not confident in this assumption, so may need to alter my solution if proven wrong.

I'm very confident that there is a better master arrangment and rearrangment method, and will update if I find it.

# Explanation

```
R=range
def f(s):
    c,y=[0,13]+([2,1,2,2][(i:=s[0]==14):i+3],[2,2,1])[s[0]%2]+[1]*8,[]  # Find the scoring arrangment per round
    r=p=0
    for j,i in enumerate(c):                                            # Find which rounds the next player takes over winning tricks
        r+=i
        if r==s[p]:y.append(j+1);r=0;p+=1
    p,t=y[:-1],c[2:5]                                                   # Rounds the next player takes over, adjustment needed at end to account for scoring arrangment
    h=[                                                                 # Master hand arrangment
    [(1,12)]+[(0,12),(0,11)]+[(0,9-x)for x in R(10)],
    [(1,0)]+[(2,x+1)for x in R(12)],
    [(1,11),(0,10)]+[(3,0),(3,1)]+[(1,x+1)for x in R(9)],
    [(1,10),(2,0)]+[(3,12-x)for x in R(11)]
    ]
    for i in R(len(p)):
        k=p[i]
        if i==0:h[0][k],h[1][1]=h[1][1],h[0][k]                                                                         # Rotation from first player to second player
        if i==1:q=p[0];h[1],h[2]=h[1][:q]+h[1][q+1:k+1]+[h[2][k-1]]+h[1][k+1:],h[2][:q]+[h[1][q]]+h[2][q:k-1]+h[2][k:]  # Rotation from second player to third player
        if i==2:                                                                                # Rotation from third player to fourth player
            h[0],h[3]=h[0][:p[0]+1]+h[3][p[0]+1:],h[3][:p[0]+1]+h[0][p[0]+1:]
            h[2],h[3]=h[2][:-1]+[h[3][-1]],h[3][:k]+[h[2][-1]]+h[3][k:-1]
    h[2][2:5]=[sorted(h[2][2:5]).pop(1-i)for i in t]                        # Adjusting arrangment of third player to match scoring arrangment per round
    return h

```
> 1 votes

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


title: Words Everywhere

text:
# Question
Title: Words Everywhere
Given a list of words, output a square grid of characters, so that all the words can be read from the grid, by moving horizontally, vertically, or diagonally between characters, without reusing characters in the same word. The grid must be the smallest possible which allows all words to be read.

## Example

```
B A D
R E T
E Y E

```

The above grid contains the words BAD, BAR, BARE, TAB, TEAR, EYE, EAR, TEE, TEED, BEAR, BEAD, BEET, DARE and YEAR (plus more, and duplicates of these in some cases). It could therefore be a valid output for the input list YEAR, BEET, DARE - the grid must be at least 3x3, since at least 8 characters are required (7 distinct characters, and 2 Es), which wouldn't fit in a 2x2 grid.

```
Y D R
B E A
T E E

```

The above grid would be another valid output for the input YEAR, BEET, DARE, but would not be valid if EYE was added to the input list, despite containing the same letters as the previous grid, since there is no way to reach the Y from two distinct Es.

There is no assumption that "words" in this challenge are English words, or even formed of letters - they are simply any string of at least 3 characters.

For input ☃, ☃❄,

```
☃
❄  ☃
  ❄

```

would be a valid output. In this case, all the "words" can be read in straight lines, which wasn't possible with the previous example (no way to fit a 4 letter word into a 3x3 grid without a turn)

## Rules

* Standard loopholes are forbidden.
* You can take input in any acceptable format (see Input/Output methods meta post)
* You can output in any acceptable format, as long as it is trivial to check that it is a square manually. For example, outputting `BADRETEYE` is not trivial to check - you need to count the characters, and take the square root of this, which is far too much effort for larger grids. Outputting `BAD RET EYE` is trivial to check - you count how many groups, and the length of any group, and if they are the same, the grid is square.
* You can fill in any gaps in the grid with any characters from the input
* Letters can only be used once in each word
* The grid should be as small as possible - the lower bound will be the square number above number of distinct characters required (e.g. 8 distinct characters would require 9 characters of output at minimum, but may require more characters if positioning means that they can't be read simultaneously)
* Languages without Unicode support (e.g. C64 BASIC, things that only run on calculators) may ignore the Unicode test case
* It's code-golf, so shortest answer in bytes wins!

## Test Data

* ANT - should give a 2x2 grid, with one letter repeated
* ANT, TAN, NAT - may well give same grid as previous
* ANT, MAN - 2x2 grid, with each of A, N, T, and M included once
* YEAR, BEET, DARE - 3x3 grid
* YEAR, BEET, DARE, EYE - 3x3 grid
* BAD, BAR, BARE, TAB, TEAR, EYE, EAR, TEE, TEED, BEAR, BEAD, BEET, DARE, YEAR - 3x3 grid
* ANTMAN, BATMAN, BANANA - 3x3 grid
* CHAOS, ORDER - 3x3 grid, no spare spaces
* SUPERMAN, SHAZAM - 4x4 grid
* 123, 1337, 911, 999, 112 - non-letters, 3x3
* SUPERGIRL, FLASH, ARROW, GOTHAM, BLACKLIGHTNING, KRYPTON, TITANS, DOOMPATROL - no idea, but at least 6x6
* ABSENTMINDEDNESS, MINT, DINED, TABS, STAND, SEATED - no idea, but might be a 4x4, since only 16 required letters
* ☃, ☃❄,  - Unicode characters, 3x3
* AUCTIONED, CAUTIONED, EDUCATION - 3x3
* COUNTRIES, CRETINOUS, NEUROTICS - at least 4x4 - both R and E need to be next to 6 distinct letters, which isn't possible on 3x3 grid

## Notes

* Inspired by the game "Words Everywhere" in the Word Games Pro app from LittleBigPlay, available on Google Play
* Solving Is This a Boggle Pad? in the unrestricted NxN case might be useful to determine the minimum required size, but is unlikely to help with actually generating the output
* There is a kind of inverse of this challenge at Is This Word on the Boggle Pad

# Answer
# Python 3, 444 bytes

```
def p(g,v=[]):
	l=len(g);r=[*range(l)];k=[[(x,y)]for x in r for y in r if(x,y)not in v]
	if len(k)<2:return[k[0]]
	return[n+N for n in k for N in p(g,v+n)if max(abs(N[0][0]-n[0][0]),abs(N[0][1]-n[0][1]))<2]
from itertools import*
def f(a):
	i=2;w=set("".join(a))
	while 1:
		for f in product(*[w]*i*i):
			g=[f[k*i:][:i]for k in range(i)];P=["".join(g[x][y]for x,y in l)for l in p(g)]
			if all(any(c in n for n in P)for c in a):return g
		i+=1

```

Try it online!

Horribly inefficient. The function `f` takes a list of words and returns a grid of characters as a list of tuples. The footer is just for formatting to take input and pretty-print output.

(Also when I golf this I get to make a crossed-out-44 meme :D)
> 3 votes

# Answer
# Python3, 853 bytes:

```
R=range
def O(n,b,w,c,x,y,p):
 if''==w:yield b,c;return
 F=0;q=[]
 for X,Y in[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]:
  if n>(j:=x+X)>=0 and n>(k:=y+Y)>=0:
   if 0==b[j][k]:q+=[(j,k)]
   if b[j][k]==w[0]and(j,k)not in p:yield from O(n,b,w[1:],c,j,k,p+[(j,k)]);F=1
 if F==0:
  for x,y in q:B=eval(str(b));B[x][y]=w[0];C=eval(str(c));C[w[0]]={*c.get(w[0],[]),(x,y)};yield from O(n,B,w[1:],C,x,y,p+[(x,y)])
def f(w):
 l=len(set(''.join(w)))
 n=min(i for i in R(l)if i**2>l)
 q,s=[([[0for _ in R(n)]for _ in R(n)],{},w)],[]
 while q:
  b,c,W=q.pop(0)
  if[]==W:return[[j or w[0][0]for j in i]for i in b]
  for x,y in(c.get(W[0][0],[])or[(x,y)for x in R(n)for y in R(n)if 0==b[x][y]]):
   P=eval(str(b));P[x][y]=W[0][0];K=eval(str(c));K[W[0][0]]={*c.get(W[0][0],[]),(x,y)}
   for B,C in O(n,P,W[0][1:],K,x,y,[(x,y)]):q+=[(B,C,W[1:])]
   break

```

This solution is longer than the other Python answer, but significantly faster on the test cases.

Try it online!
> 1 votes

---
Tags: code-golf, grid
---


title: Can this list be balanced?

text:
# Question
Title: Can this list be balanced?
To check whether a list of non-negative integers is *balanced*, one can imagine putting respective weights on a board and then try to balance the board on a pivot such that the summarized *relative* weights left and right of the pivot are the same. The relative weight is given by multiplying the weight with its distance to the pivot (see law of the lever).

(Source: wikipedia)

This image corresponds to a list `[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]`. This list is balanced because the `5` has a distance of 20 to the pivot, the `100` a distance of 1 and `5*20 = 100 = 100*1`.

## Examples

```
 3 1 5 7
#########
     ^

```

In this case the pivot is directly under the `5`, the `3` has distance 2 and the `1` and `7` have distance 1. So both sides left and right of the pivot sum up to `7` (`3*2 + 1*1` on the left and `7*1` on the right) and therefore the list `[3, 1, 5, 7]` is balanced.

Note, however, that the pivot does not have to be placed under one of the list elements, but might also be placed in-between two list elements:

```
 6 3 1
#######
  ^

```

In this case the distances become `0.5, 1.5, 2.5, ...` and so on. This list is also balanced because `6*0.5 = 3 = 3*0.5 + 1*1.5`.

The pivot can only be placed exactly below one number or exactly in the middle between two numbers, and **not** e.g. at two-thirds between two numbers.

## Task

Given a list of non-negative integers in any reasonable format, output a `truthy` value if the list can be *balanced* and a `falsy` value otherwise.

You can assume that the input list contains at least two elements and that at least one element is non-zero.

This is a challenge, so the answer with the fewest amount of bytes in each language wins.

## Truthy Testcases

```
[1, 0]
[3, 1, 5, 7]
[6, 3, 1]
[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]
[10, 4, 3, 0, 2, 0, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 7, 7, 7]

```

## Falsy Testcases

```
[1, 2]
[3, 6, 5, 1, 12]
[0, 0, 2, 0, 1, 0]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[6, 3, 2, 4, 0, 1, 2, 3]
[4, 0, 0, 2, 3, 5, 2, 0, 1, 2, 3, 0, 0, 1, 2, 4, 3, 1, 3, 0, 0, 2]
[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]

```

---

A lot of related challenges where found while this challenge was sand-boxed: Is it a balanced number?, Equilibrium index of a sequence, Balance a set of weights on a seesaw, Balancing Words, Will I tip over? and Where does the pivot belong?

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

```
!%ys*VQUQs

```

Try it online

Saved 2 bytes thanks to Mr. Xcoder and Erik the Outgolfer.

### Explanation

```
!%ys*VQUQs
    *VQUQ    Multiply each input by its index.
  ys         Take twice the sum (to handle half-integer positions).
!%       sQ  Check if that's a multiple of the total weight.

```
> 7 votes

# Answer
# Wolfram Language (Mathematica), 36 bytes

```
IntegerQ[2#.Range[t=Tr[1^#]]/(t-1)]&

```

This is a center of mass problem in a coordinate system with the origin at one of the points and then you determine if the CM falls on a lattice point where the lattice width = 1/2.

Try it online!
> 4 votes

# Answer
# 05AB1E, 6 bytes

```
ƶO·IOÖ

```

Try it online!

### How?

```
ƶO·IOÖ ~ Full program. I = input.

ƶ      ~ Lift I. Multiply each element with its 1-based index.
 O     ~ Sum.
  ·    ~ Double.
     Ö ~ Is a multiple of?
   IO  ~ The sum of I.

```
> 4 votes

# Answer
# Jelly, 6 bytes

```
×JSḤọS

```

Try it online!

Well, looks like Leaky Nun pointed the pointless out.

Using Mnemonic's Pyth approach.

Returns a positive integer (truthy) or zero (falsy).
> 2 votes

# Answer
# , 34 bytes

```
function(n)!(n%*%seq(n)*2)%%sum(n)

```

Try it online!

Takes input as a vector. Ports mnemonic's answer. Returns a `1x1` matrix.
> 2 votes

# Answer
# Julia, ~~31~~ 27 bytes

*4 bytes saved thanks to @Dennis*

```
!n=2n[i=1:end]⋅i%sum(n)<1

```

Try it online!
> 2 votes

# Answer
# Python 2, 41 bytes

```
S=s=0
for n in input():S-=s;s-=n
1>>2*S%s

```

Output is via exit code, so **0** is truthy and **1** is falsy.

Try it online!
> 2 votes

# Answer
# Japt, 10 bytes

```
í* x*2 vUx

```

Try it online!

## Explanation:

```
 í* x*2 vUx
U            // Implicit Input                 [3, 1, 5, 7]
 í           // Pair the input with its index  [[3,0],[1,1],[5,2],[7,3]]
  *          // Multiply each item             [0,1,10,21]
    x        // Sum                            32
     *2      // Double                         64
        v    // Divisible by:
         Ux  //   Sum of Input                 16
             // Explicit Output                1

```

Returns `1` for truthy, `0` for falsy.
> 2 votes

# Answer
# Ruby, 47 bytes

*Saved 2 bytes thanks to Mr. Xcoder*

```
->k{(k.map.with_index{|x,i|x*i*2}.sum%k.sum)<1}

```

Try it online!
> 2 votes

# Answer
# C,  ~~140~~  137 bytes

```
float l,r;i,j,t;f(L,n)int*L;{for(i=t=-1;++i<2*n;t*=l-r)for(l=r=j=0;j<n;++j)l+=j<i/2.?L[j]*(i/2.-j):0,r+=j>i/2.?L[j]*(j-i/2.):0;return!t;}

```

Try it online!
> 1 votes

# Answer
# Python 3, 51 bytes

```
lambda k:sum(i*e*2for i,e in enumerate(k))%sum(k)<1

```

Try it online!
> 1 votes

# Answer
# Japt, ~~11~~ ~~10~~ 8 bytes

Originally inspired by Mnemonic's solution

```
x* vUx*½

```

Try it

~~1~~ 3 bytes saved thanks to ETHproductions.

---

## Explanation

Implicit input of array `U`. Reduce by addition (`x`), multiplying each element by its 0-based index (`*`) in the process. Check if the result is evenly divisible (`v`) by the sum of the original input (`Ux`) with each element being multiplied by 0.5 ().
> 1 votes

# Answer
# Perl 6, 23 bytes

```
{sum(1..*Z*$_)*2%%.sum}

```

Test it

Uses the algorithm from various other entries.

## Expanded:

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

    sum(

        1 .. *  # Range starting from 1

      Z*        # Zip using &infix:«*»

        $_      # the input

    ) * 2

  %%            # is divisible by

    .sum        # the sum of the input (implicit method call on ｢$_｣)
}

```
> 1 votes

# Answer
## C#, 71 bytes

---

**Golfed**

```
a=>{int i,s,S=s=i=0;while(i<a.Length){S-=s;s-=a[i++];}return 2*S%s<1;};

```

---

**Ungolfed**

```
a => {
    int
        i, s, S = s = i = 0;

    while( i < a.Length ) {
        S -= s;
        s -= a[ i++ ];
    }

    return 2 * S % s < 1;
};

```

---

**Full code**

```
using System;

namespace Namespace {
    class Program {
        static void Main( String[] args ) {
            Func<Int32[], Boolean> f = a => {
                int
                    i, s, S = s = i = 0;

                while( i < a.Length ) {
                    S -= s;
                    s -= a[ i++ ];
                }

                return 2 * S % s < 1;
            };

            List<Int32[]>
                testCases = new List<Int32[]>() {
                    new Int32[] {1, 0},
                    new Int32[] {3, 1, 5, 7},
                    new Int32[] {6, 3, 1},
                    new Int32[] {100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5},
                    new Int32[] {10, 4, 3, 0, 2, 0, 5},
                    new Int32[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
                    new Int32[] {7, 7, 7, 7},

                    new Int32[] {1, 2},
                    new Int32[] {3, 6, 5, 1, 12},
                    new Int32[] {0, 0, 2, 0, 1, 0},
                    new Int32[] {1, 2, 3, 4, 5, 6, 7, 8, 9},
                    new Int32[] {6, 3, 2, 4, 0, 1, 2, 3},
                    new Int32[] {4, 0, 0, 2, 3, 5, 2, 0, 1, 2, 3, 0, 0, 1, 2, 4, 3, 1, 3, 0, 0, 2},
                    new Int32[] {100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5},
                };

            foreach( Int32[] testCase in testCases ) {
                Console.WriteLine( $"{{ {String.Join(", ", testCase)} }}\n{f( testCase )}" );
            }

            Console.ReadLine();
        }
    }
}

```

---

**Releases**

* **v1.0** \- `71 bytes` \- Initial solution.

---

**Notes**

I might have, or might have not, blatantly "borrowed" Dennis Python 2 solution...
> 1 votes

# Answer
# Vyxal, 7 bytes

```
ż*∑d?∑Ḋ

```

Try it Online!

## How?

```
ż*∑d?∑Ḋ
ż*      # Multiply each by its 1-based index
  ∑     # Sum this
   d    # Double
      Ḋ # Is it divisible by...
    ?∑  # ...the sum of the input?

```
> 1 votes

# Answer
# APL (Dyalog), 15 bytes

```
0≡+⌿|(+⌿+⍨×⍳∘≢)

```

Try it online!

Looks very ungolfy to me...
> 0 votes

# Answer
# Haskell, 39 bytes

```
f l=2*sum(zipWith(*)l[0..])`mod`sum l<1

```

Try it online!
> 0 votes

# Answer
# Python 2, ~~78~~ 75 bytes

thanks to Mr. Xcoder for -3 bytes

```
lambda l:0in[sum(v*(i-y*2)for y,v in enumerate(l))for i in range(len(l)*2)]

```

Try it online!
> 0 votes

# Answer
# PHP, 139 128 bytes

```
<?php $a=explode(',',fgets(STDIN));for($i=0;$i<count($a)-.5;$i+=.5){$z=0;foreach($a as $k=>$v)$z+=($k-$i)*$v;if($z==0)die(1);}?>

```

Try it online!
> 0 votes

# Answer
# Julia 0.6, 25 bytes

```
~=sum
!x=~cumsum(2x)%~x<1

```

Try it online!
> 0 votes

# Answer
# Swift, 76 bytes

```
{var i=0,t=0;print($0.reduce(0){$0+($1*i,t+=$1,i+=1).0}*2%t<1)}as([Int])->()

```

Try it online!
> 0 votes

# Answer
# Perl 5, 55 + 1 (`a`) = 56 bytes

```
$.=0;map$.+=$p++*$_,@F;$#F+($p=$i-=.5)&&$.&&redo;say!$.

```

Try it online!
> 0 votes

---
Tags: code-golf, array, decision-problem, physics
---


title: Draw the Union Jack

text:
# Question
Title: Draw the Union Jack
# Preface

There are many "draw x flag" challenges, and upon searching it turns out there are no challenges to draw the union Jack! I feel like this would be a harder flag to draw but it should still be possible.

# Challenge

Draw the Union Jack. It can be outputted to a file in any freely available graphics file format or drawn onto the screen.

Dimensions shall be as below. Minimum size 600x300 pixels (or units if your language supports only scalable graphics.) Maximum error 1 pixel.

Colours shall be red, white and blue as defined by your language or its documentation, or #CC0000, #FFFFFF and #003399 per Wikipedia page.

# Answer
> 8 votes
# BBC BASIC

**Rev B, 234 bytes**

Instead of drawing one white and one red cross, we draw 100 progressively narrower crosses, switching from white background to red foreground at a coordinate of 60.

```
p=20761m=1049w=600h=300F.i=-1TO1V.29,w;h;18;4,m;134*i;0;m;w*i;-233;p;0;466;m;0;67*i;m;-466;h*i;p;932;0;18;1,m;511*i;h*i;25;89*i;0;29977;0;0;m;w*i;-h*i;28953;0;45*i;
N.F.c=-100TO0q=25881-c DIV60*512V.m;-c;-h;q;c;h;m;-w;-c;q;w;c;
N.

```

Download interpreter free at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

**Fully golfed, 249 bytes**

Single byte VDU codes e.g `25,0` combined into double-byte little endian e.g `25;` and maximum use of constants for common values. Keywords compressed to abbreviated form, e.g. `FOR`=\>`F.` (interpreter expands automatically.)

```
p=20761q=26393r=25881m=1049c=100w=600h=300F.i=-1TO1V.29,w;h;18;4,m;134*i;0;m;w*i;-233;p;0;466;m;0;67*i;m;-466;h*i;p;932;0;18;1,m;511*i;h*i;25;89*i;0;29977;0;0;m;w*i;-h*i;28953;0;45*i;
N.V.m;-c;-h;q;c;h;2m;-w;-c;q;w;c;m;-60;-h;r;60;h;m;-w;-60;r;w;60;

```

**Semigolfed**

Raw VDU codes. In BBC BASIC, characters can be sent to the VDU controller like `VDU65` (prints an A.) There are certain special characters particular to the BBC for graphics. These must be followed by several other bytes to specify coordinates, etc. Here we use `PLOT`=\>`VDU25`, `GCOL`=\>`VDU18`, `ORIGIN`=\>`VDU29`.

```
  c=100w=600h=300                                      :REM constants 100,width,height
  FORi=-1TO1                                           :REM loop -1 and 1 (0 draws nothing)
    VDU29,w;h;                                         :REM set origin (bring inside loop for golfing reasons)
    VDU18;4                                            :REM change to blue and draw triangles
    VDU25,4,134*i;0;25,4,w*i;-233;25,81,0;466;25,4,0;67*i;25,4,-466;h*i;25,81,932;0;
    VDU18;1                                            :REM change to red and draw parallelograms
    VDU25,4,511*i;h*i;25,0,89*i;0;25,117,0;0;25,4,w*i;-h*i;25,113,0;45*i;
  NEXT
  VDU25,4,-c;-h;25,103,c;h;25,4,-w;-c;25,103,w;c;      :REM draw white background rectangles
  VDU25,4,-60;-h;25,101,60;h;25,4,-w;-60;25,101,w;60;  :REM draw red foreground rectangles

```

First we draw half the diagonal parts: 2 blue triangles and 2 red parallelograms. Then we change the scale from -1 to +1 and draw the other half. Finally we draw the horizontal and vertical parts on top: 2 white rectangles to form a white cross, then 2 red rectangles. The image after the first iteration of the loop is shown below, along with the final image.

**Ungolfed code**

BBC basic remembers the last 2 locations of the graphics cursor. PLOT81 draws a triangle between the new coordinates specified and these last two locations. PLOT113 and PLOT117 draw a parallelogram in a similar way: three corners of the parallelogram have to be given in the order they are found going round the perimeter. The last three bits of the PLOT code define whether the given coordinates are absolute or relative, and whether foreground or background colour is used. The more significant bits define what type of shape is drawn (point, line, triangle, parallelogram, rectangle, etc.)

```
  ORIGIN600,300       :REM move the origin (which will be centre of flag) away from the corner of the screen.

  FORi=-1TO1          :REM at scales of -1 and 1, plot half each of the diagonal parts (i=0 plots nothing).
    GCOL0,4             :REM blue foreground colour
    PLOT4,134*i,0       :REM absolute move to peak of upper/lower triangle
    PLOT4,600*i,-233    :REM absolute move to left hand corner
    PLOT81,0,466        :REM relative move to right hand corner, plotting triangle

    PLOT4,0,67*i        :REM absolute move to peak of left/right triangle
    PLOT4,-466,300*i    :REM absolute move to lower corner
    PLOT81,932,0        :REM relative move to upper corner, plotting triangle

    GCOL0,1             :REM red foreground colour
    PLOT4,511*i,300*i   :REM absolute move to long edge of flag
    PLOT0,89*i,0        :REM relative move to corner of flag (top right / bottom left)
    PLOT117,0,0         :REM absolute move to centre of flag, plotting parallelogram (stripe)
    PLOT4,600*i,-300*i  :REM absolute move to corner of flag (bottom right / top left)
    PLOT113,0,45*i      :REM relative move to short edge of flag, plotting parallelogram (stripe)
  NEXT                :REM diagonal parts completed, now plot vertical/horizontal parts on top.

  PLOT4,-100,-300     :REM move to bottom left of vertical white stripe
  PLOT103,100,300     :REM move to top right corner, plot it in background colour (white)
  PLOT4,-600,-100     :REM move to bottom left corner of horizontal white stripe
  PLOT103,600,100     :REM move to top right corner, plot it in background colour (white)

  PLOT4,-60,-300      :REM move to bottom left of vertical red stripe
  PLOT101,60,300      :REM move to top right corner, plot it in foreground colour (red)
  PLOT4,-600,-60      :REM move to bottom left corner of horizontal red stripe
  PLOT101,600,60      :REM move to top right corner, plot it in foreground colour (red)

```

# Answer
> 3 votes
# SVG, 298 bytes

score excludes 3 unnecessary newlines added for clarity.

```
<svg xmlns="http://www.w3.org/2000/svg">
<path d="M67,0h466L0,267v-234L533,300h-466L600,33v232z" fill="blue"/>
<path d="M0,0v22L300,172L45,300h-45L600,0h-45L300,128L600,278v22z" fill="red"/>
<path d="M-10,110h270v-120h80v120h270v80h-270v120h-80v-120h-270z" fill="red" stroke="#fff" stroke-width="20"/>

```

Inspired by Siren's deleted answer (and in particular the saving in bytes from omitting `</svg>` at the end of the document), I came up with an SVG that is both dimensionally correct and slightly shorter.

It consists of a blue path and a red path (filled, without strokes) for the diagonal parts and a red path (filled, with 20 unit white border) for the final cross. Because of the thickness of the white border, the specified dimensions of the cross must exceed the required dimensions by 10 all around.

This works fine for me in Microsoft IE and Edge. Sometimes displays an "extra content at the end of the document" warning in Chrome.

Here's how it appears without and with the final cross. 8 points are required to describe the blue path, 10 points to describe the red path, and 12 points for the final cross. The intersections of straight lines within the first two paths do not have to be given.

# Answer
> 1 votes
# Logo, ~~260~~ 239 bytes

## (XLogo Interpreter)

I used the Java-based XLogo interpreter since it was one of the few Logo implementations I could find which supports setting the output window size.

The XLogo editor normally saves files as procedures which are meant to be called. This program is written to be pasted into the immediate window instead. This saves about 9 bytes.

```
window setscreensize[600 300]setsc 4 lt atan 2 repeat 2[repeat 2[setpc 7 setpw 60 fd 400 setpw 20 lt 90 fd 10 lt 90 setpc 1 fd 400 lt 90 fd 10 rt 90]lt asin .8]home wrap setpw 100 setpc 7 repeat 2[repeat 2[fd 600 lt 90]setpw 60 setpc 1] ht

```

Since exact colors weren't required, I regolfed this to use built-in color numbers which saved several bytes. If you want to see a version with exact RGB colors, check the revisions. I also substituted a trigonometric calculation with a shorter equivalent.

## Ungolfed with commentary

The only real trickery here is changing colors for the second pass of a loop, and taking advantage of the `wrap` feature which allows us to draw the horizontal stripes with very little effort. Since the flag height and width are both factors of 600, we can go forward 600 for either vertical or horizontal stripes and end up back at the center again. This avoids having separate cases for each, even if it does draw the vertical bar twice as often. We're saving code space, not clock-cycles.

```
to UnionJack
  #Initialize the screen
  window  #Allow the turtle to overshoot the boundary without reappearing on the opposite side
  setscreensize[600 300]
  setsc 4  #blue background

  lt atan 2 #Turn left, preparing to draw first diagonal
  repeat 2 [ #Draw 2 sets of main diagonal bars
    repeat 2 [ #Each main bar is made of 2 spokes
      setpc 7 setpw 60 #Use a wide white pen
      fd 400 #Draw past the corner of the window
      setpw 20 #Make the pen narrow
      lt 90 fd 10 lt 90 #Do a 10px U-turn
      setpc 1 #Switch to a red pen
      fd 400 #Draw back to the center.
      lt 90 fd 10 rt 90 #Do a 10 px S curve back to center, ready to draw the opposite spoke
    ] #Finish spoke
    lt asin .8 #Turn for the next bar.
  ] #Finish bar
  home #Return to a sane heading
  wrap #Makes the turtle wrap to the opposite side if it overshoots the boundary
  setpw 100 setpc 7 #Wide white pen
  repeat 2 [ #Draw 2 crosses
    repeat 2 [ #Each cross has 2 stripes
      fd 600 #Overshoot the boundary so that we end up where we started at the center, leaving a stripe behind
      lt 90 #Rotate to draw the next stripe
    ] #Finish the stripe
    setpw 60 setpc 1 #Change to a narrow red pen
  ] #Finish cross
  ht #Hide the turtle
end

```

# Answer
> 1 votes
# Processing, 312 bytes

This is the type of puzzle where Processing is pretty efficient.

```
int a=300,b=2*a,c=255,d=100;size(b,a);background(0,51,153);stroke(c);strokeWeight(60);line(0,a,b,0);line(0,0,b,a);stroke(c,0,0);strokeWeight(20);line(0,310,a,160);line(-22,0,a,160);line(a,139,b,-12);line(a,139,624,a);noStroke();fill(c);rect(250,0,d,b);rect(0,d,b,d);fill(c,0,0);rect(270,0,60,b);rect(0,120,b,60);

```

Results in:

# Answer
> 1 votes
# Postscript (175 bytes)

```
00000000: 880a 880a 928b 3020 3092 6b30 881e 9263  ......0 0.k0...c
00000010: 883c 3330 9263 883c 3092 6392 1692 142f  .<30.c.<0.c..../
00000020: 727b 2e38 8800 3092 9d7d 9233 2f77 7b31  r{.8..0..}.3/w{1
00000030: 8801 3192 9d7d 9233 924e 3220 3192 8b30  ..1..}.3.N2 1..0
00000040: 202e 3220 2e36 929d 3020 3088 1e33 3092   .2 .6..0 0..30.
00000050: 8088 0f31 3592 ad34 3592 8834 7b77 8800  ...15..45..4{w..
00000060: 2d32 2e36 3888 1e35 2e33 3792 8072 8800  -2.68..5.37..r..
00000070: 3088 1e31 2e37 3992 8039 3092 887d 9283  0..1.79..90..}..
00000080: 924d 881e 3135 92ad 327b 7788 fb88 e288  .M..15..2{w.....
00000090: 0a36 3092 8039 3092 887d 9283 327b 7288  .60..90..}..2{r.
000000a0: fd88 e236 883c 9280 3930 9288 7d92 83    ...6.<..90..}..

```

Non-tokenized version:

```
10 10 scale
0 0 moveto
0 30 lineto
60 30 lineto
60 0 lineto
closepath
clip
/r {.8 0 0 setrgbcolor} def
/w {1 1 1 setrgbcolor} def
gsave
2 1 scale
0 .2 .6 setrgbcolor
0 0 30 30 rectfill
15 15 translate
45 rotate
4 {w 0 -2.68 30 5.37 rectfill r 0 0 30 1.79 rectfill 90 rotate} repeat
grestore
30 15 translate
2 {
w
-5 -30 10 60 rectfill
90 rotate
} repeat
2 {
r
-3 -30 6 60 rectfill
90 rotate
} repeat

```

Output:

# Answer
> 1 votes
# HTML/CSS, 742 bytes

A very unclever CSS implementation using three HTML elements.

```
<style>body{margin:0;zoom:10}a,b{position:absolute;width:30px;height:30px;background:#012169;clip-path:inset(0)}a:after,a:before,b:after,b:before{position:absolute;content:'';width:60px;height:2px;background:#c00;border:0 solid #fff;border-width:3px 0 1px 0;transform-origin:0 3px}a:after,b:after{top:-3px;transform:rotate(26.56deg)}a:before,b:before{top:27px;transform:rotate(-26.56deg)}b{left:30px;transform:rotate(180deg)}i{position:absolute;background:#fff;width:60px;height:10px;top:10px}i:before{position:absolute;background:#c00;width:6px;height:30px;top:-10px;left:25px;border:0 solid #fff;border-width:0 2px 0 2px;content:''}i:after{position:absolute;top:2px;width:60px;height:6px;background:#c00;content:''}</style><a></a><b></b><i>
```

See it unminified on CodePen.

# Answer
> 1 votes
# C (gcc), ~~248~~ ~~229~~ 224 bytes

*-24 bytes thanks to @ceilingcat*

```
#define p putchar(c?c-1
i=-151,j,I,J;main(c){for(puts("P6 600 300 255 ");++i<150;)for(j=-301;++j<300;p?0:255:204))c=(c=fmin(I=abs(i),J=abs(j)))<30?0:c<50?:(c=i*j>0?J-2*I:2*I-J)>0&c<35?0:c*c<2704?:2,p?51:255:0),p?153:255:0);}

```

Try it online!

Outputs a PPM image.

# Answer
> 0 votes
# Python 2, 265 bytes

```
r="D\0\0"
b="\0\x173"
w="U"*3
N=20*(270*w+60*r+270*w)
L=190*[b]+60*[w]+40*[r]+20*[w]+190*[b]
j=''.join
F=lambda p:j([j(L[150-p*100+i:150+p*150+i:p])+20*w+60*r+20*w+j(L[345-p*145-i:345+p*105-i:p])for i in range(0,200,2)])
print"P6 600 300 85 "+F(-1)+N+36000*r+N+F(1)

```

Output as binary PPM, usage:

```
python golf_unionjack.py > unionjack.ppm

```

`L` represents a vertical slice of the diagonal parts and `F` uses the (sort of) symmetry to save code and calculate the indices for upper and lower part.

---
Tags: code-golf, kolmogorov-complexity, graphical-output
---


# Question
Title: Write a polyglot that prints the language's name
Your task is to write a program that executes in as many languages as possible, with as few characters as you can. To avoid trivial solutions, the program must print the name of the language it was run in.

## Scoring

Your program has to work in at least 5 languages. A program's score is given as:

$$\frac {\text{(number of languages)}^{1.5}} {\text{(length of program)}}$$

The highest score wins.

# Answer
## Bash, C, C++, Obj-C, Obj-C++, Perl, PHP, Ruby, 183 chars

score ~ 0.1236

For the C and C-like codes I owe a debt to @baby-rabbit. The others are inspired by the recognition that many languages have an `eval` statement that will grudgingly accept invalid syntax.

Outputs the language name to standard output. Sometimes generates a lot of error messages on standard error, so suppress them with `2>/dev/null` as you run them.

```
#if 0
'PHP<?/*';eval "print\$=?'Perl':'Ruby';echo Bash";exit
__END__
#endif
#include <stdio.h>
main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}//*/?>'

```

The php solution outputs `'PHP'` (including the single quotes), which may be bending the rules a little bit.

Last edit: shaved 12 chars from insight that `$=` is `false` in Ruby, `60` in Perl, and `print$=?...` is almost surely an error in Bash. Shaved 7 more from insight the Perl/Ruby/Bash test can now go into a single eval statement.

If the rules can tolerate more bending, I present this 8 language, 43 character solution (score 0.5262)

```
print("phperluarscriptrubypythoncatebg13");

```

for which the output includes the name of the interpreter for `php`, `perl`, `lua`, `rscript`, `ruby`, `python`, `cat`, and `rot13`.
> 42 votes

# Answer
# C, C++, BF, BASH and Ruby; 280 chars

Score is about 0.040

```
#include "stdio.h"
#define s "C"
#ifdef __cplusplus
#define s "C++"
#endif
#ifndef s
#"+++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts "Ruby"
exit
fi
echo "BASH"
exit
end
#endif
main(){puts(s);}

```

Note that I am using a Linux system.

The code is run or compiled with the following commands (the file's name is `test.c`)

C:

```
gcc test.c

```

When run with `./a.out`, output is `C`

C++:

```
c++ test.c

```

When run with `./a.out`, output is `C++`

BASH:

```
./test.c

```

Outputs: `BASH`

Ruby:

```
ruby test.c

```

Outputs: `Ruby`

BrainF\***:

Verified using the following:

Outputs: `brainfuck`

Note that if the JS debugger is used, then the first two minus signs need to be removed. They were included to offset the plus signs in the string literal `"C++"`. This was a very fun project, I'm working on adding more languages.

Just to add further clarity, here are my interpreter's/compiler's specs:

* gcc version 4.6.3
* ruby 1.9.3p194 (2012-04-20 revision 35410) \[x86\_64-linux\]
* GNU bash, version 4.2.24(1)-release (x86\_64-pc-linux-gnu)

**SIDE NOTE**

Using @baby-rabbit's trick I was able to extend my code to be executable in 7 languages (objective-C and objective-c++ being added). This is not my solution since I did copy some, but I thought I would show it off.

**Update 9.12** Added SmallTalk run with gnu-smalltalk!

**SmallTalk, C, C++, Objective-C, Objective-C++, BASH, BF, Ruby; 384 chars (Score: 0.059)**

```
#if (a)
##(true) ifTrue: ['SmallTalk' printNl]
##(ObjectMemory quit)
#"+++++++++++[>++++++++++>+++++++++<<-]>>-.<++++.>-.++++++++.<----.>---.<+++++++.>---.++++++++.<<++++++++++.[-]"
if [ 1 == 2 ];then
puts 'Ruby'
exit
fi
echo 'BASH'
exit
end
=begin
#endif
#include "stdio.h"
main(){puts(
#ifdef __OBJC__
"Objective-"
#endif
"C"
#ifdef __cplusplus
"++"
#endif
);}
#ifdef b
=end
#endif

```

In the above code you will need to rename the file to produce the langauge's name for objective-c, obj-c++, c and c++.
> 20 votes

# Answer
## bash, c, c++, obj-c, obj-c++; 134 chars; score=0.083

```
#if x
echo "bash"
exit
#endif
#include <stdio.h>
int main(){puts(
#ifdef __OBJC__
"obj-"
#endif
"c"
#ifdef __cplusplus
"++"
#endif
);}

```

rename file and run/compile as:

* sh file.sh
* cc file.c
* cc file.cpp
* cc file.m
* cc file.mm

(where cc is clang-421.10.42)
> 13 votes

# Answer
## Lua, Ruby, VimL, Sed, Befunge (129 chars; ~0.087 points)

Not sure if this one counts--the sed-part is embedded in the shebang line which is arguably a hack to get around the restriction. This also means that it should be run as an executable and not directly with `sed`.

I was lucky that all the other languages (sans Befunge) automagically ignores the shebang line (though apparently Ruby refuses to run the file if it has a shebang line that doesn't contain the string 'ruby' in it).

```
#!sed sanava;s/.*/sed/;q;ruby
--"".to_i#>"egnufeB">:#,_@
if 0
then
if IO
then
puts"Ruby"
else
print"Lua"
end
else
echo"VimL"
end

```

Sample usage:

```
% lua tmp/glot.poly
Lua
% ruby tmp/glot.poly
Ruby
% ./tmp/glot.poly
sed
% cfunge tmp/glot.poly       # Requires Befunge-98
Befunge

:source tmp/glot.poly        # from vim
VimL                         # displayed as message

```
> 11 votes

# Answer
# AsciiDots, Befunge-93, C, C++, \>\<\>, Funge-98, GolfScript, lua, MinkoLang, Python 2, Python 3, Ruby, vi (0.170444 points)

```
#/* ["39-egnufeB">:|;ooo"><>"
n,n=1,1--[[],0][1]#>52*,@
"""""GolfScript"
puts"Ruby\n"
__END__
:puts{"""
print("Python %d"%(3/2*2));
"""stoDiicsA"$\<ESC>dggivi<ESC>ZZ*/
#include<stdio.h>
main(){puts(sizeof'a'-1?"C":"C++");}
//>"Minkolang"9[O]."
//^}>"89-egnuF"#[v,<]"]]print"lua"--"""

```

\<ESC\> stands for the literal escape character 27

I know this is an old post, but it was interesting so I had to give it a shot :P
> 9 votes

# Answer
## BF, Bash, Batch, C, vi (163 characters; score ≈ .0686)

(`<ESC>` stands for ASCII code 27.)

```
rem (){ ((0));};true /*
rem ;goto(){ rem;}
rem ivi<ESC>ZZ'++++++++[>NUL ++++++++<NUL -]>NUL ++.++++.*/;main(){puts("C");}/*'
goto a
echo Bash
exit
:a
echo Batch
rem */

```

I tested this, as a batch file, with the MS-DOS 6.22 version of COMMAND.COM. By default, that interpreter mixes lines of source code with the output. To prevent that from happening, execute `echo off` before running the batch file.

To execute the vi code, which I have only tested using Vim, use the following command:

```
cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile

```
> 8 votes

# Answer
# Every Python Release, 18.37291 points

```
import sys
print('Python '+'.'.join(map(str,sys.version_info[:-2])))

```

Technically valid, if you consider all the python versions to be different languages. There are currently 116 python versions, which I believe gives me a score of around 18.37291.

(Also I understand if this isn't considered a valid answer, this was just for fun)
> 6 votes

# Answer
# bash, zsh, ksh, csh, tcsh, 15 chars, score 0.745

This one's a bit of a stretch since they're all related languages, but there are differences:

```
ps -ocomm= -p$$

```
> 5 votes

# Answer
# 16 languages, 348 bytes, score: 0.183908046

```
#include <stdio.h>
#if 0
#replace "C(gcc)" "C(ecpp)"
#replace "C++(gcc)" "C++(ecpp)"
#endif
#ifdef __clang__
#define d 2
#elif __TINYC__
#define d 4
#else
#define d 0
#endif // rk:start print: "rk" \
ps -ocomm= -p$$; exit;
int x=sizeof('a')%2+d;char*arr[]={"C(gcc)","C++(gcc)","C(clang)","C++(clang)","C(tcc)"};int main(){puts(arr[x]);}

```

---

This works in C(gcc), C++(gcc), C(ecpp), C++(ecpp), C(clang), C++(clang), C(tcc), sh, dash, bash, zsh, ksh, csh, tcsh, rk, and SIL.
> 4 votes

# Answer
## Bash, C, Gawk, Perl, vi (145 characters; score ≈ .077)

(`<BS>` stands for ASCII code 8. `<ESC>` stands for ASCII code 27.)

```
#define echo//<BS><BS><BS>vi<ESC>ZZ
#define BEGIN A()
#define B\
{
echo Bash ;exit;
#define C\
}
BEGIN {printf(A=="A"?"Perl":"Gawk");exit;}
main(){puts("C");}

```

To execute the vi code, which I have only tested using Vim, use this command:

```
cat /dev/null > tmpfile && vi -s polyglot.sh tmpfile > /dev/null 2>&1 && cat tmpfile

```
> 3 votes

# Answer
# Java, Lisp, Whitespace, Intercal, PHP, Befunge-98; score =.0189

This was originally an answer to this.

```
 ;\\0"egnufeB">:#,_@SSSTTTSTTTL
;TL
;SSSSSTTSTSSSL
;TL
;SSSSSTTSTSSTL
;TL
;SSSSSTSTSTSSL
;TL
;SSSSSTTSSTSTL
;TL
;SSSSSTSTSSTTL
;TL
;SSSSSTTTSSSSL
;TL
;SSSSSTTSSSSTL
;TL
;SSSSSTTSSSTTL
;TL
;SSSSSTTSSTSTL
;SSL
;L
;L
;L
;public class H{ public static void main(String []a){System.out.println("JAVA");}}
;/*
(print "LISP")
;*/
;//<?php
; echo "PHP"
;//?>
;/*
#|
DO ,1 <- #8
DO ,1 SUB #1 <- #110
DO ,1 SUB #2 <- #32
DO ,1 SUB #3 <- #72
DO ,1 SUB #4 <- #136
DO ,1 SUB #5 <- #88
DO ,1 SUB #6 <- #136
PLEASE DO ,1 SUB #7 <- #64
DO ,1 SUB #8 <- #80
PLEASE READ OUT ,1
PLEASE NOTE |#
;*/
;// PLEASE GIVE UP

```
> 3 votes

# Answer
## Befunge, 05AB1E (legacy), Vyxal, Red, Python 1, Vim, Zsh \- 71.5 / 114 characters ≈ 0.164 score

```
'a;# "egnufeB"\\,,,,,,,@"05AB1E",q', 2>2
'a;`Vyxal`,Q', 2>2#;echo Zsh
print 'Red quit;' * 0+'Python', 1>0#<0x1B>}dHiVim

```

Try it in Befunge! 05AB1E! Vyxal! Red! Python! Vim! Zsh!
> 3 votes

# Answer
This is a cheap selection of languages, but here goes:

## CoffeeScript, JScript, Mozilla Javascript (≈ JavaScript 1.3), ECMAScript Edition 5, ECMAScript Edition 3, 223 chars, score ≈ 0.0501)

```
a="undefined"
x="ECMAScript 3"
if(Array.prototype.map)
 x="ECMAScript 5"
if(typeof CoffeeScript!=a)
 x="CoffeeScript"
if(typeof uneval!=a)
 x="Mozilla JavaScript"
if(typeof WScript!=a)
 WScript.echo("JScript")
else alert(x)

```
> 2 votes

# Answer
## Windows Batch, TI-Basic, Golf-Basic 84, Quomplex, and GTB 5\*2/93 = 0.11

```
::¤Quomplex¤:"'*[]'":~"GTB":g;1:d`"GOLF-BASIC 84":g`1:"TI-BASIC":Lbl 1:End
echo Windows Batch

```

**How it works**

Windows Batch was the easiest, because `::` starts a comment. Fairly simple to implement.

TI-Basic doesn't support lowercase letters or backticks, causing it to skip the statements `d`"GOLF-BASIC 84":g`1`, which Golf-Basic evaulates, Displaying the message and forwarding to Label 1, where it is promptly ended. This is similar for GTB, with its handy display character, `~`. By the way, a string with no display will be put in `Ans`. If there are no Display commands following it, `Ans` will be outputted (not the case here).

Quomplex was snuck in at the beginning because its complex syntax won't allow for much to be skipped. All it does is add `"Quomplex"` to the output, and then for the mastery of the program...

**The Mastery of the Programming Syntax**

```
:"'*[]'"

```

Pure genius. Quomplex ignores `:` and takes `"'` and `'"` as strings, leaving it to output the stack and perish in an infinite while loop (`[]`). Meanwhile, Golf-Basic and TI-Basic take the whole `"'*[]'"` as a string, because `'` is a mathematical operator, not a string operator.
> 2 votes

# Answer
## JScript, EcmaScript Edition 3, 5, 6, 2016, Node, Mozilla JavaScript (score ≈ 0.1342)

This answer is originally based off Peter Olson's answer, but minus the *CoffeeScript* (as whitespace-significant languages can be horrible for golfing).

I also added *Node*, *ES6* and *ES2016* and golfed the code a little, almost tripling the original score.

```
$=this,y="EcmaScript ",x=$.module?"Node":$.uneval?"Mozilla JavaScript":"".padStart?y+2016:$.Map?y+6:[].map?y+5:y+3,($.WScript||$.alert)(x)

```
> 2 votes

# Answer
## PE/bash/x86/C/Ruby/Python2, 330 bytes

score ≈ 0.0445

xxd:

```
00000000: 4d5a 7544 3d27 5c27 273b 0a23 2f2a 0a27  MZuD='\'';.#/*.'
00000010: 3b65 6368 6f20 6261 7368 2023 273b 7072  ;echo bash #';pr
00000020: 696e 7420 2830 616e 6427 5275 6279 2729  int (0and'Ruby')
00000030: 6f72 2750 7974 686f 6e32 2723 4000 0000  or'Python2'#@...
00000040: 5045 0000 4c01 0100 b802 00cd 10b8 0013  PE..L...........
00000050: eb2e 0000 7000 0301 0b01 0000 7075 7473  ....p.......puts
00000060: 0000 0065 7869 7400 f000 0000 6d73 7663  ...exit.....msvc
00000070: 7274 0000 0000 4000 0400 0000 0400 0000  rt....@.........
00000080: bb0f 00bd 8c7c eb58 0400 0000 7838 3600  .....|.X....x86.
00000090: 0004 0000 0100 0000 0000 0000 0300 0000  ................
000000a0: 0000 0000 0000 0000 0000 0000 0000 0000  ................
000000b0: 0000 0000 0200 0000 0000 0000 0000 0000  ................
000000c0: 0d01 0000 0000 0000 2e74 6578 7400 0000  .........text...
000000d0: 4500 0000 f000 0000 4500 0000 f000 0000  E.......E.......
000000e0: b903 00ba 0000 cd10 ebfe 0000 0000 0000  ................
000000f0: 6840 0040 00ff 1501 0140 00ff 1505 0140  h@.@.....@.....@
00000100: 005a 0000 0061 0000 0000 0000 0000 0000  .Z...a..........
00000110: 0000 0000 0000 0000 006c 0000 0001 0100  .........l......
00000120: 0000 0000 0000 0000 0000 0000 0000 0000  ................
00000130: 0000 0000 002a 2f0d 6d61 696e 2829 7b70  .....*/.main(){p
00000140: 7574 7328 2243 2229 3b7d                 uts("C");}

```

source:

```
; nasm

base equ 0x400000

;
; DOS header
;
; The only two fields that matter are e_magic and e_lfanew

mzhdr:
    dw "MZ"              ; DOS e_magic
    jnz a
    db "='\'';",10,"#/*",10,"';echo bash #';print (0and'Ruby')or'Python2'#"
    times 64 - 4 - ($-$$) db 0
    dd 64                ; DOS e_lfanew

;
; NT headers
;

PE: dd "PE"              ; PE signature

;
; NT file header
;

filehdr:
    dw 0x014C            ; Machine (Intel 386)
    dw 1                 ; NumberOfSections
;    dd 0                 ; TimeDateStamp UNUSED
;    dd 0                 ; PointerToSymbolTable UNUSED
;    dd 0                 ; NumberOfSymbols UNUSED
a:
    mov ax,2        ; 3 bytes
    int 0x10        ; 2 bytes  ; clear screen
    mov ax,0x1300   ; 3 bytes
    jmp b           ; 2 bytes
    dw 0            ; 2 bytes

    dw opthdrsize        ; SizeOfOptionalHeader
    dw 0x103             ; Characteristics

;
; NT optional header
;

opthdr:
    dw 0x10B                    ; Magic (PE32)
;    db 0                        ; MajorLinkerVersion UNUSED
;    db 0                        ; MinorLinkerVersion UNUSED
;    dd 0                        ; SizeOfCode UNUSED
;    dd 0                        ; SizeOfInitializedData UNUSED
;    dd 0                        ; SizeOfUninitializedData UNUSED
puts_: db 0,0,"puts",0
exit_: db 0,0,"exit",0
    dd start                    ; AddressOfEntryPoint
;    dd 0                        ; BaseOfCode UNUSED
;    dd 0                        ; BaseOfData UNUSED
crt: db "msvcrt",0,0
    dd base                     ; ImageBase
    dd 4                        ; SectionAlignment
    dd 4                        ; FileAlignment
;    dw 0                        ; MajorOperatingSystemVersion UNUSED
;    dw 0                        ; MinorOperatingSystemVersion UNUSED
;    dw 0                        ; MajorImageVersion UNUSED
;    dw 0                        ; MinorImageVersion UNUSED
b:
    mov bx,0xF           ; 3 bytes  ; video page, video attribute
    mov bp,0x7C00+x86    ; 3 bytes
    jmp c                ; 2 bytes

    dw 4                        ; MajorSubsystemVersion
    dw 0                        ; MinorSubsystemVersion UNUSED
;    dd 0                        ; Win32VersionValue UNUSED
x86: db "x86",0
    dd 1024                     ; SizeOfImage
    dd 1                        ; SizeOfHeaders          nonzero for Windows XP
    dd 0                        ; CheckSum UNUSED
    dw 3                        ; Subsystem (Console)
    dw 0                        ; DllCharacteristics UNUSED
    dd 0                        ; SizeOfStackReserve
    dd 0                        ; SizeOfStackCommit
    dd 0                        ; SizeOfHeapReserve
    dd 0                        ; SizeOfHeapCommit UNUSED
    dd 0                        ; LoaderFlags UNUSED
    dd 2                        ; NumberOfRvaAndSizes    for Windows 10; UNUSED in Windows XP

;
; Data directories (part of optional header)
;
    dd 0, 0                     ; Export Table UNUSED
    dd idata, 0                 ; Import Table

opthdrsize equ $ - opthdr

;
; Code section header
;

    db ".text", 0, 0, 0         ; Name
    dd codesize                 ; VirtualSize
    dd code                     ; VirtualAddress
    dd codesize                 ; SizeOfRawData
    dd code                     ; PointerToRawData
;    dd 0                        ; PointerToRelocations UNUSED
;    dd 0                        ; PointerToLinenumbers UNUSED
;    dw 0                        ; NumberOfRelocations UNUSED
c:
    mov cx,3      ; 3 bytes  ; text length
    mov dx,0      ; 3 bytes  ; text position
    int 0x10      ; 2 bytes  ; print text
    jmp $         ; 2 bytes  ; enter infinite loop

    dw 0                        ; NumberOfLinenumbers UNUSED
    dd 0                        ; Characteristics UNUSED

;
; Code section data
;

align 4, db 0

code:

;
; Entry point
;

bits 32
start:
    push base + PE
    call [base + puts]
    call [base + exit]

;
; Import address table (array of IMAGE_THUNK_DATA structures)
;

iat:
puts:   dd puts_                ; Import puts by name
exit:   dd exit_                ; Import exit by name
        dd 0                    ; terminator

;
; Import table (array of IMAGE_IMPORT_DESCRIPTOR structures)
;

idata:
    dd 0                        ; OriginalFirstThunk UNUSED
    dd 0                        ; TimeDateStamp UNUSED
    dd 0                        ; ForwarderChain UNUSED
    dd crt                      ; Name
    dd iat                      ; FirstThunk
    times 5 dd 0                ; terminator

codesize equ $ - code

db "*/",13,"main(){puts(",34,"C",34,");}"

```

Try it online in bash/C/Ruby/Python2.
Portable Executable `polyglot.exe` was tested on Windows 10 2004 64-bit and Windows XP SP3 32-bit.
Raw x86 was tested in QEMU 6.2.0: `qemu-system-x86_64 -no-fd-bootchk -fda polyglot`.

Inspired by/based on αcτµαlly pδrταblε εxεcµταblε, which is a PE/bash/x86 polyglot. Also based on this hello world PE.

#### Portable Executable

Main differences from hello world:

* DOS and NT headers don't overlap here, NT header immediately follows DOS header
* `puts` and `exit` are imported by name

As mentioned in hello world PE answer, the minimal distance between the start of NT headers and end of file on Windows 10 is 264 bytes, so minimal PE file size with non-overlapping DOS and NT headers on Windows 10 is 64+264=328 bytes (64 == sizeof(IMAGE\_DOS\_HEADER)). It means that all but 2 bytes of C code at the end of the file are required for this file to work on Windows 10.

The program prints its own PE signature, which is kinda cute.

#### x86

αpε uses `jno 0x4a` `jo 0x4a` to jump to the main boot code. I ran out of space in the DOS header and didn't want to rearrange the code, so I use the less robust single `jnz a` instruction. This means I rely on BIOS to not set `bp` to `1` before calling boot sector (`M` in `MZ` is `dec bp`). QEMU and Bochs set `bp` to `0`. Unconditional `jmp` is not used because its code is `0xEB`, on the other hand almost all short conditional jumps have ASCII codes, see here.

Main code:

```
    mov ax,2
    int 0x10            ; clear screen

    mov ax,0x1300
    mov bx,0xF          ; video page, video attribute
    mov bp,0x7C00+x86
    mov cx,3            ; text length
    mov dx,0            ; text position
    int 0x10            ; print text

    jmp $               ; enter infinite loop

    x86: db "x86"

```

This code is split into 3 parts (`a:`,`b:`,`c:`) to fit inside unused fields of NT headers. It looks like both `b` and `c` would fit inside section header, but it breaks PE on Windows XP for some reason.

#### bash/C/Ruby/Python2

```
MZuD='\'';
#/*
';echo bash #';print (0and'Ruby')or'Python2'# ... */␍main(){puts("C");}

```

Pretty standard stuff:

* bash: `\` inside `''` does not escape
* C: allows single `#` on a line
* Ruby: `0` is truthy

Also, I used the fact that C treats `\r` as newline, unlike bash/Ruby/Python2 (link). This allows to use just `#` in bash/Ruby/Python2 to comment out the rest of the polyglot.
> 2 votes

# Answer
# JScript, EcmaScript Edition 3, 5, 6, 2016, 2017, Node, Mozilla JavaScript (score = .174193548387), CoffeeScript (as whitespace-significant languages can be horrible for golfing).

```
$=this,y="EcmaScript ",($.WScript||alert)(x=Object.values?y+2017:$.module?"Node":$.uneval?"Mozilla JavaScript":[].includes?y+2016:$.Map?y+6:[].map?y+5:y+3)

```
> 1 votes

---
Tags: code-challenge, polyglot
---


title: Emanresu numbers

text:
# Question
Title: Emanresu numbers
My userid is 100664. In binary this is `11000100100111000`.

An interesting property of this number is that it can be created entirely by concatenating strings which are repeated at least twice:

```
11  000  100100  111  000

```

The first few such numbers are \\$3,7,10,12,15,24,28,31,36,40,42, 43, 45,48,51,53,54,56,58,60,63,80,87,96,99,103,112,115,117,120,122,124,127\\$ (let me know if I've missed any as I worked these out by hand).

Your challenge is to calculate these. (Leading zeros don't count, e.g. `9 = 001001` is not part of the sequence.)

As with all challenges, you may either:

* Take a number \\$n\\$ and output the nth term
* Take a number \\$n\\$ and output the first n terms
* Take no input and output these forever

Here's a reference implementation courtesy of Bubbler

# Scoring

This is , shortest wins!

# Testcases

These are 0-indexed.

```
0 => 3
1 => 7
3 => 12
5 => 24
10 => 42
15 => 53
20 => 63
25 => 103

```

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

```
BŒṖŒɠṂ’ƊƇµ#

```

A full program that accepts a positive integer, \\$n\\$, from STDIN and prints a list of the first \\$n\\$ emanresu numbers.

**Try it online!**

### How?

```
BŒṖŒɠṂ’ƊƇµ# - Main Link: no arguments
          # - start with k=0 and count up, collecting the first n (from STDIN) k
              which are truthy under:
         µ  -   the monadic chain, f(k):
B           -     convert (k) to binary
 ŒṖ         -     all partitions (of the binary representation of k)
        Ƈ   -     filter - keep those (partitions) which are truthy under:
       Ɗ    -       last three links as a monad, f(partition):
   Œɠ       -         run-lengths of equal elements (e.g. 101,101,1,1,1,0 -> 2,3,1)
     Ṃ      -         minimum
      ’     -         decrement (vectorises) -> 0 is falsey, other numbers are truthy
                (a result of f(k) which is non-empty is truthy)

```
> 10 votes

# Answer
# Python 3, ~~78~~ 71 bytes

-7 thanks to m90, wasif, and ovs

```
import re
i=1
while[re.match('..((.+)\\2+)+$',bin(i))and print(i)]:i+=1

```

Try it online!

I feel like manually setting the index isn't optimal but idk how to avoid it in this situation.

Further optimizations:

Since bin(i) always prepends 0b to our string, and match always checks from the start, we can remove the slicing from \[2:\] and instead embed that in the regex.

By combining the match statement with an `and` for the print, it short circuits and only prints i if re.match returns something other than None.

And by wrapping the and statement in a list, it forces it to always be evaluated as true in our while condition.
> 7 votes

# Answer
# JavaScript, 63 bytes

```
for(n=1;;n++)/^((.+)\2+)+$/.test(n.toString(2))&&console.log(n)

```

Try it online!
> 5 votes

# Answer
# Retina, 56 bytes

```
{T`d`10`.1*$
^0*$
1$&
/^((.+)\2+)+$/&*\(`1
01
+`10
011
1

```

Try it online! Link is to verbose version of code. Outputs the infinite sequence. Explanation:

```
{

```

Repeat forever.

```
T`d`10`.1*$

```

Increment the current binary value.

```
^0*$
1$&

```

If it overflows, carry the `1`.

```
/^((.+)\2+)+$/&

```

Is this an Emanresu number?

```
*\(`

```

If so then print the result of the rest of the program but then restore the current binary value.

```
1
01
+`10
011
1

```

Convert from binary to decimal.
> 5 votes

# Answer
# Brachylog, 13 bytes

```
ℕ≜{ḃ~cḅ∋₁ᵐ&!}

```

Try it online!

Generates numbers infinitely.

```
ℕ≜               Choose a nonnegative integer.
   ḃ             Its binary representation
    ~c           can be partitioned such that
      ḃ          if runs of equal partitions are grouped,
         ᵐ       each group
       ∋₁        has a second element.
  {       & }    Output that integer
           !     once.

```

I had hoped to use `j` here, but it can't even get close.
> 5 votes

# Answer
# Stax, <sup>~~16~~</sup> 12 bytes

```
ï├1mìsM`0°ö≈

```

Run and debug it

Prints the sequence forever.

-4 bytes using the partitioning idea.
> 4 votes

# Answer
# Jelly,  ~~17~~  15 bytes

*Saved 2 bytes thanks to @Dudecoinheringaahing*

Takes an integer \\$n\\$ from STDIN and generates the first \\$n\\$ terms.

This is probably twice as long as it should be...

```
BŒṖ‘ḄŒɠ€ỊẸ€ẠṆø#

```

Try it online!
> 4 votes

# Answer
# Perl 5, 45 bytes

```
/^((.+)\2+)+$/&&say$.while$_=sprintf"%b",++$.

```

Try it online!
> 4 votes

# Answer
# Japt, 20 bytes

Outputs the first `n` terms. It's *really* annoying me that the RegEx takes up nearly ¾ of this solution but I can't seem to come up with a shorter, non-RegEx based one :\

```
È¤è"^((.+)%2+)+$"}jU

```

Try it

```
È¤è"^((.+)%2+)+$"}jU     :Implicit input of integer U
È                        :Function taking an integer as argument
 ¤                       :  To binary string
  è                      :  Count
   "^((.+)%2+)+$"        :    RegEx /^((.+)\2+)+$/
                 }       :End function
                  jU     :Get the first U integers that return a truthy value

```
> 3 votes

# Answer
# , ~~85~~ 81 bytes

```
while(T<-T+1)grepl("^((.+)\\2+)+$",Reduce(paste0,T%/%2^(0:log2(T))%%2))&&print(T)

```

Try it online!

A regex-based solution. Prints values indefinitely.

Thanks to @pajonk for saving 4 bytes!
> 3 votes

# Answer
# 05AB1E, 16 bytes

```
∞ʒb.œ2ìεγ€g2@P}à

```

Outputs the infinite sequence.

Try it online.

**Explanation:**

```
∞              # Push an infinite list of positive integers: [1,2,3,...]
 ʒ             # Filter this list by:
  b            #  Convert the current integer to binary
   .œ          #  Get all partitions of this binary string
     2ì        #  Prepend a 2 before each part (this is necessary because `γ` will
               #  ignore leading 0s, and thus incorrectly group "1" and "01" together)
       ε       #  Map each partition to:
        γ      #   Group adjacent equivalent elements together
         €g    #   Get the length of each group
           2@  #   Check for each length if it's >= 2
             P #   Check if all are truthy (by taking the product)
       }à      #  After the map: check if any partition is truthy (by taking the max)
               # (after which the filtered list is output implicitly as result)

```
> 3 votes

# Answer
# Vyxal `r`, 23 bytes

```
λbvS∑`^((.+)\\2+)+$`r;ȯ

```

Try it Online!

A juicy port of JavaScript. Man I do love me some regex in golfing languages. Takes `n` and outputs the first n terms.
> 2 votes

# Answer
# Vyxal, 10 bytes

```
ΠøṖ'ĠvḢA)ȯ

```

Try it Online!

Port of Jelly.

-2 bytes thanks to emanresu A and lyxal
> 2 votes

# Answer
# Julia 1.0, 65 bytes

```
!i=replace(bitstring(i+=1),r"((.+)\2+)"=>"")>""||println(i),!i;!1

```

Try it online!
> 1 votes

---
Tags: code-golf, sequence, binary
---


title: Not so triangular numbers

text:
# Question
Title: Not so triangular numbers
Let's consider the sequence \\$S\\$ consisting of one \\$1\\$ and one \\$0\\$, followed by two \\$1\\$'s and two \\$0\\$'s, and so on:

$$1,0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,...$$

(This is A118175: *Binary representation of n-th iteration of the Rule 220 elementary cellular automaton starting with a single black cell.*)

Given \\$n\>0\\$, your task is to output \\$a(n)\\$, defined as the number of \\$1\\$'s among the \\$T(n)\\$ first terms of \\$S\\$, where \\$T(n)\\$ is the \\$n\\$-th triangular number.

The first few terms are:

$$1,2,3,6,9,11,15,21,24,28,36,42,46,55,65,70,78,91,99,105,...$$

One way to think of it is to count the number of \\$1\\$'s up to the \\$n\\$-th row of a triangle filled with the values of \\$S\\$:

```
1 (1)
01 (2)
100 (3)
1110 (6)
00111 (9)
100001 (11)
1111000 (15)
00111111 (21)
000000111 (24)
1111000000 (28)
01111111100 (36)
...

```

## Rules

You may either:

* take \\$n\\$ as input and return the \\$n\\$-th term, 1-indexed
* take \\$n\\$ as input and return the \\$n\\$-th term, 0-indexed
* take \\$n\\$ as input and return the \\$n\\$ first terms
* take no input and print the sequence forever

This is a challenge.

# Answer
# Wolfram Language (Mathematica), 41 bytes

```
Sum[1-⌈s=√n⌉+Round@s,{n,#(#+1)/2}]&

```

Try it online!

-2 bytes from @ZippyMagician
> 7 votes

# Answer
# Jelly, 9 bytes

```
ḤR>)FŒHṪS

```

A monadic Link accepting \\$n\\$ which yields \\$a(n)\\$.

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

### How?

We can think of \\$S\\$ as being built in blocks of length \\$2i\\$ where each block is a string of \\$i\\$ ones followed by \\$i\\$ zeros: `10 1100 111000 ...`.

If we stop at \\$i=x\\$ and call the result \\$S\_x\\$ we know that \\$S\_x\\$ necessarily contains an equal number of ones and zeros.

We also know that the length of \\$S\_x\\$ will be \\$\sum\_{i=1}^{x}2i = 2 \sum\_{i=1}^{x}i = 2T(x)\\$.

So the value of \\$a(x)\\$ is the count of ones in the first half of \\$S\_x\\$.

An alternative way to get this same result is to subtract the count of the *zeros* in the first half of \\$S\_x\\$ from \\$T(x)\\$, and since \\$S\_x\\$ contains an equal number of ones and zeros this must also be the count of zeros in the second half of \\$S\_x\\$. Therefore we can form the complement of \\$S\_x\\$ and count the ones in its second half:

```
ḤR>)FŒHṪS - Link: integer, n
   )      - for each (i in [1..n]): e.g. i=3
Ḥ         -   double                       6
 R        -   range                        [1,2,3,4,5,6]
  >       -   greater than i?              [0,0,0,1,1,1]
    F     - flatten -> [0,1,0,0,1,1,0,0,0,1,1,1,...]
     ŒH   - split into two equal length parts
       Ṫ  - tail
        S - sum

```
> 7 votes

# Answer
# Husk, 8 bytes

```
Σ↑ṁṘḋ2NΣ

```

Try it online! or Verify first 12 values

Returns the \\$n^{th}\\$ value of the sequence, 1 indexed.

## Explanation

```
Σ↑ṁṘḋ2NΣ
  ṁ   N  map the following across natural numbers and concatenate
   Ṙḋ2   replicate [1,0] n times
 ↑       take all values
       Σ till the triangular number of the input
Σ        sum them

```
> 5 votes

# Answer
# Haskell, 48 bytes

```
f n=sum$sum[1..n]`take`do z<-[1..];[1,0]<*[1..z]

```

Try it online!

# Haskell, 48 bytes

```
sum.(take.sum.r<*>(([1,0]<*).r=<<).r)
r n=[1..n]

```

Try it online!
> 5 votes

# Answer
# Python 2, 47 bytes

```
f=lambda n,k=8:k>n*-~n*2or(-k**.5%2<1)+f(n,k+4)

```

Try it online!

**52 bytes**

```
lambda n:sum(-(k+1)**.5%1<.5for k in range(n*-~n/2))

```

Try it online!

Based on the formula for \\$S\\$ that user's noted from the OEIS page of A118175. We simplify it to the following, one-indexed using Booleans for 0/1: $$ S(k) = \mathrm{frac}(-\sqrt{k}) \< \frac{1}{2},$$ where \\$\mathrm{frac}\\$ takes the fractional part, that is the difference between the number and its floor. For example, \\$\mathrm{frac}(-2.3)=0.7\\$. This is equivalent to \\$\sqrt{k}\\$ being at most \\$\frac{1}{2}\\$ lower than its ceiling.

The code simply sums $$\sum\_{k=1}^{n(n+1)/2} S(k),$$ but shifting the argument \\$k\\$ by one to account for the zero-indexed Python range.

---

**57 bytes**

```
def f(n):N=n*-~n/2;a=round(N**.5);print(a+N-abs(a*a-N))/2

```

Try it online!

Outputs floats. A direct arithmetic formula. Thanks to Arnauld for -1 byte
> 5 votes

# Answer
# 05AB1E, ~~12~~ 9 bytes

```
LxL@˜2äнO

```

-2 bytes by taking inspiration from *@JonathanAllan*'s Jelly answer for generating the `[1,0,1,1,0,0,1,1,1,0,0,0,...]` list.

Outputs the \\$n^{th}\\$ value. (Thanks to *@ovs*.)

Try it online or verify the first 10 test cases.

**10 bytes version that outputs the infinite sequence instead:**

```
∞xL@˜∞£OηO

```

Try it online.

**Explanation:**

```
L           # Push a list in the range [1, (implicit) input]
            #  i.e. input=5 → [1,2,3,4,5]
 x          # Double each value (without popping)
            #  [2,4,6,8,10]
  L         # Convert each value to a [1,n] list as well
            #  [[1,2],[1,2,3,4],[1,2,3,4,5,6],[1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7,8,9,10]]
   @        # Check for each value in the [1,input] list that it's >= the values in the
            # inner ranged lists
            #  [[1,0],[1,1,0,0],[1,1,1,0,0,0],[1,1,1,1,0,0,0,0],[1,1,1,1,1,0,0,0,0,0]]
    ˜       # Flatten it
            #  [1,0,1,1,0,0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,1,0,0,0,0,0]
     2ä     # Split it into 2 equal-sized parts
            #  [[1,0,1,1,0,0,1,1,1,0,0,0,1,1,1],[1,0,0,0,0,1,1,1,1,1,0,0,0,0,0]]
       н    # Only leave the first item
            #  [1,0,1,1,0,0,1,1,1,0,0,0,1,1,1]
        O   # And sum this list
            #  9
            # (after which this sum is output implicitly as result)

∞           # Push an infinite list of positive integers
            #  [1,2,3,...]
 xL@˜       # Same as above
            #  [1,0,1,1,0,0,1,1,1,0,0,0,...]
     ∞      # Push an infinite list again
      £     # Split the list into parts of that size
            #  [[1],[0,1],[1,0,0],[1,1,1,0],...]
       O    # Sum each inner list
            #  [1,1,1,3,...]
        η   # Take the prefixes of that list
            #  [[1],[1,1],[1,1,1],[1,1,1,3],...]
         O  # Sum each inner list
            #  [1,2,3,6,...]
            # (after which the infinite list is output implicitly)

```
> 4 votes

# Answer
# Charcoal, ~~24~~ 13 bytes

```
ＩΣ∕⭆⊕Ｎ⭆10×ιλ²

```

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

```
     Ｎ          Input `n`
   ⭆⊕           Map over inclusive range
      ⭆10       Map over characters of literal string `10`
           λ    Current character
         ×      Repeated by
          ι     Outer index
  ∕         ²   First half of resulting string
 Σ              Digital sum (i.e. count `1`s)
Ｉ               Cast to string
                Implicitly print

```

Previous 24-byte more Charoal-y solution:

```
ＮθＧLθψ¤⭆θ⭆²⭆⊕ιλ≔№ＫＡ0θ⎚Ｉθ

```

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

```
Ｎθ

```

Input `n`.

```
ＧLθψ

```

Draw an empty right triangle of side `n`.

```
¤⭆θ⭆²⭆⊕ιλ

```

Fill it using the string `010011000111...`. (The string is always twice as long as the triangle.) Charcoal's fill paints the provided string into the area to fill (see for example Bake a slice of Pi). Note that the `0`s and `1`s are swapped.

```
≔№ＫＡ0θ

```

Get the number of `0`s that were actually printed.

```
⎚Ｉθ

```

Clear the canvas and print the result.
> 3 votes

# Answer
# K (oK), ~~30~~ ~~25~~ 24 bytes

-6 bytes thanks to coltim

```
{+/(x+/!x)#,/x{0,x,1}\1}

```

Try it online!

Returns the n-th term 1-indexed.
> 3 votes

# Answer
# Jelly, 11 bytes

```
⁵DxⱮRFḣRS$S

```

Try it online!

Takes \\$n\\$, outputs \\$a(n)\\$, 1-indexed

## How it works

```
⁵DxⱮRFḣRS$S - Main link. Takes n on the left
⁵           - 10
 D          - [1, 0]
    R       - [1, 2, ..., n]
   Ɱ        - For each i in [1, 2, ..., n]:
  x         -   Repeat [1, 0] i times
     F      - Flatten the array
         $  - Group the previous two commands into a monad T(n):
       R    -   [1, 2, ..., n]
        S   -   Sum
      ḣ     - Take the first T(n) elements of the sequence
          S - Take the sum, essentially counting the 1s

```
> 3 votes

# Answer
# APL+WIN, ~~26~~ 21 bytes.

minus 5 bytes thanks to Adam.

Prompts for integer:

```
+/(+/m)↑∊(m←⍳⎕)∘.⍴1 0

```

Try it online! Thamks to Dyalog Classic
> 3 votes

# Answer
# Python 2, 62 bytes

```
a=lambda n,k=1:-~n*n>k*k*2and k+a(n,k+1)or max(0,k-~n*n/2-k*k)

```

Try it online!

This is based on

$$ \begin{align} a(n) &= f(\frac{n\cdot(n+1)}{2}, 1) \\ \\ f(n, k) &= \begin{cases} k+f(n-2k, k+1), & \text{if $n \> k$} \\ \operatorname{max}(0, n), & \text{if $n \le k$} \end{cases} \end{align} $$

but the conditions and the base case are more convoluted to get this into a single recursive function.
> 3 votes

# Answer
# JavaScript (Node.js), ~~100~~ ~~89~~ ~~85~~ ~~84~~ 77 bytes

-11: Change `a**2` to `a*a` and simplify `1-Math.ceil(c)+Math.round(c)` to `Math.ceil(c)-c<0.5` (@xnor)

-4: Move `c=Math.sqrt(b+1)` inside `Math.ceil(c)` and omit the `f=` (@user)

-1: Change ...`c<0.5` to ...`c<.5` (@xnor)

-7: Remove unnecessary `(` and `)`, and change `Math.sqrt(`...`)` to ...`**.5` (@Samathingamajig)

```
a=>(x=0,Array((a*a+a)/2).fill().map((a,b)=>x+=Math.ceil(c=(b+1)**.5)-c<.5),x)

```

Try it online!
> 3 votes

# Answer
# Python 3, 69 bytes

```
lambda n:sum([j for i in range(1,n+1)for j in[1]*i+i*[0]][:n*-~n//2])

```

Try it online!
> 2 votes

# Answer
# Scala, ~~66 58~~ 51 bytes

```
n=>1 to n flatMap(i=>""*i+"\0"*i)take(n*n+n>>1)sum

```

Try it online

There is an unprintable character `0x01` inside the first quote.

An anonymous function that takes an integer `n` and returns the nth element of the sequence (1-indexed).
> 2 votes

# Answer
# C (gcc), ~~84~~ ~~82~~ 61 bytes

Saved 2 bytes thanks to ErikF!!!

```
c;p;f(n){for(c=p=0,n=n*-~n/2;n>2*p;n-=2*p++)c+=p;c+=n<p?n:p;}

```

Try it online!

Inputs a \\$1\\$-based number \\$n\\$ and returns the \\$n^{\text{th}}\\$ term.
> 2 votes

# Answer
# Haskell, 46 bytes

```
f n=sum[1|a<-[1..n],b<-[1..a],a*a-b<n*(n+1)/2]

```

Try it online!

---

**46 bytes**

```
f n=sum[max 0$min a$n*(n+1)/2-a*a+a|a<-[1..n]]

```

Try it online!

---

**48 bytes**

```
f n=sum[1|k<-[2,4..n*n+n],even$ceiling$sqrt$2*k]

```

Try it online!
> 2 votes

# Answer
# Haskell, 50 bytes

```
r?x|q<-sum[0..x]-r*r,r>q=min q 0|l<-r+1=l+l?x
(0?)

```

Try it online!

Slightly longer but complete different approach from the existing Haskell answer. This one is basically all arithmetic whereas the existing one builds the list from scratch.
> 2 votes

# Answer
# Vyxal `s`, 8 bytes

```
ƛdɾ<;fIt

```

Try it Online!
> 2 votes

# Answer
# Arn `-rlx`, 14 bytes

```
&♦r┬f½▀╔î¾rl¥Æ

```

Try it!

# Explained

Unpacked: `$.(|{|a{a>}\~:+}\`

```
            Mutate STDIN from N → [1, N]
$.                Partition down middle
  (
    |..\            Fold N with concatenation
          _             Where N is a variable; implied
     {                After mapping with block, key of `_`
       |..\
            ~:+             Where N is a one-range to _ * 2
        a{                Block with key of `a`
             a
           >                Is greater than
             _                Implied
        }                 End block
     }                End block
               Last entry, sum

```

Alternate 14 byte solution with the same flags: `$.(a{~:+a@>a}\):_`

# Arn, 23 bytes

```
W▀Q$µgˆÎ§Ò"ˆÞC5fbA┐V-7J

```

Try it! Thinking of adding a round fix to Arn, that'll help this pretty high byte count.

1-indexed, returns the Nth term. Based off of @J42161217's answer

# Explained

Unpacked: `+{1-(:^:/)+:v(0.5+:/}\~:-*++`

```
+...\ Fold with addition after mapping
  ~ Over the one-range to
    :-*++ n * (n + 1) / 2
{ Begin map, key of `_`
    1
  - Subtract
    (
      :^ Ceiling
        _ Implied
      :/ Square root
    )
  + Add
    :v(0.5+:/ Round `:/_`, ending implied
} End map

```
> 1 votes

# Answer
# , 25 bytes

```
(1#.2&!$&;1 0<@#"{~i.)@>:

```

Try it online!

```
(1#.2&!$&;1 0<@#"{~i.)@>:
(                    )@>. increment n by 1 and then
                   i.     for every i in 0 … n+1:
          1 0  #"{~         take i 1s and i 0s,
             <@             and box the result (;1 0;1 1 0 0;…)
    2&!                   T(n) by binominal(n+1, 2)
       $&;                raze the boxes to a list (1 0 1 1 0 0…)
                            and take the first T(n) elements
 1#.                      sum the list, i.e. count the 1s

```
> 1 votes

# Answer
# Retina 0.8.2, 41 bytes

```
.+
$*
1
$`1$.`$*00
((.)+?)(?<-2>.)+$
$1
1

```

Try it online! Link includes test cases. Explanation:

```
.+
$*
1
$`1$.`$*00

```

Create the string `101100111000`... up to `n` `1`s and `n` `0`s, which is twice as long as the desired triangle.

```
((.)+?)(?<-2>.)+$
$1

```

Delete the second half of the string.

```
1

```

Count the number of `1`s remaining.
> 1 votes

# Answer
# MATL, ~~15~~ 14 bytes

```
:"@:t~]vG:s:)z

```

Input is 1-based.

Try it online! Or verify the first values.

### How it works

```
       % Implicit input: n
:      % Range: [1 2 ... n].
"      % For each
  @    %   Push iteration index, k (goes from 1 to n)
  :    %   Range: gives [1 2 ... k]
  t    %   Duplicate
  ~    %   Negate, element-wise: gives [0 0 ... 0] (k zeros)
]      % End
v      % Concatenate everything into a column vector
G      % Push n again
:      % Range: [1 2 ... n]
s      % Sum: gives n-th triangular number, T(n)
:      % Range
)      % Index: keeps the first T(n) values
z      % Number of nonzeros
       % Implicit output

```
> 1 votes

# Answer
# MathGolf, ~~19~~ 12 bytes

```
╒♂░*mzyh½<iΣ

```

Outputs the 1-based \\$n^{th}\\$ value.

Try it online.

**Original 19 bytes answer:**

```
╒♂░*mzykæî‼<≥]╡imΣΣ

```

Outputs the 1-based \\$n^{th}\\$ value as well.

Try it online.

**Explanation:**

```
╒               # Push a list in the range [1, (implicit) input]
 ♂░             # Push 10, and convert it to a string: "10"
   *            # Repeat the "10" each value amount of times: ["10","1010","101010",...]
    m           # Map over each inner string:
     z          #  Revert sort its digits: ["10","1100","111000",...]
      y         # Join it together to a single string: "101100111000..."
       h        # Push its length (without popping the string itself)
        ½       # Halve it
         <      # Only keep the first length/2 amount of digits in this string
          i     # Convert the string to an integer
           Σ    # And sum its digits
                # (after which the entire stack joined together is output implicitly)

╒♂░*mzy         # Same as above
                # Get its prefixes (unfortunately there isn't a builtin for this):
       k        #  Push the input-integer
        æ       #  Loop that many times,
                #  using the following four characters as body:
         î      #   Push the 1-based loop index
          ‼     #   Apply the following two commands separated:
           <    #    Slice to get the first n items
           ≥    #    Slice to remove the first n items and leave the remainder
        ]       #  After the loop, wrap all values on the stack into a list
         ╡      # Remove the trailing item
          i     # Convert each string of 0s/1s to an integer
           mΣ   # Sum the digits of each inner integer
             Σ  # And sum the entire list together
                # (after which the entire stack joined together is output implicitly)

```
> 1 votes

# Answer
# , 55 bytes

```
sum(unlist(Map(rep,list(1:0),e=n<-1:scan()))[1:sum(n)])

```

Try it online!

Generates A118175 and sums the first \\$T(n)\\$ terms.
> 1 votes

# Answer
# Gaia, ~~12~~ ~~11~~ 10 bytes

```
┅2…&¦_2÷eΣ

```

Try it online!

Uses the observation from Jonathan Allan's answer to save a byte (so go upvote that), namely that constructing the complement sequence and counting the 1s in the *second* half is equivalent to counting the 1s in the first half.

```
		# implicit input n
┅		# push [1, 2, ..., n]
2…		# push [0,1]
&¦		# for each i in [1, 2, ..., n] repeat each element of [0,1] i times
_2÷		# flatten and divide into two sublists of equal length
eΣ		# take the second sublist and sum

```
> 1 votes

# Answer
# Desmos, 85 bytes

\\$\sum\_{n=1}^{x(x+1)/2}(1-\operatorname{ceil}(\sqrt{n})+\operatorname{round}(\sqrt{n}))\\$

```
\sum_{n=1}^{x(x+1)/2}(1-\operatorname{ceil}(\sqrt{n})+\operatorname{round}(\sqrt{n}))

```

I haven't been able to find a nice formula myself, so I used the \\$a(n) = 1 - \operatorname{ceil}(\sqrt{n+1}) + \operatorname{round}(\sqrt{n+1})\\$ formula provided on A118175's page.
> 1 votes

# Answer
# Raku, 40 bytes

```
{sum flat({1,0 Xxx++$}...*)[^sum 1..$_]}

```

Try it online!

* `{ ... } ... *` is an infinite sequence, where the bracketed expression is a function that generates each successive element.
* `++$` increments the anonymous state variable `$` each time the generating function is evaluated. The first time it's called, `++$` is 1, then 2, etc.
* `1, 0` is just a two-element list.
* `xx` is the replication operator. Prefixed with the cross-product metaoperator `X`, `Xxx` crosses the list `1, 0` with the incrementing value of `++$`, generating the sequence `(((1), (0)), ((1, 1), (0, 0)), ((1, 1, 1), (0, 0, 0)), ...)`.
* `flat` lazily flattens that infinite sequence into the given sequence S, ie: `1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, ...`.
* `[^sum 1..$_]` takes the first N elements from that sequence, where N is the sum of the numbers from 1 up to `$_`, the argument to the function.
* The leading `sum` sums the selected elements.
> 1 votes

# Answer
# Swift, 80 bytes

*Adapted from the Python 2 answer by @ovs*

```
func a(_ n:Int,_ k:Int=1)->Int{-(~n*n)>k*k*2 ? k+a(n,k+1):max(0,k-(~n)*n/2-k*k)}

```

And the un-golfed form:

```
func a(_ n: Int, _ k: Int = 1) -> Int {
    -(~n*n) > k*k*2
        ? k + a(n, k+1)
        : max(0, k - ~n*n/2 - k*k)
}

```

And here's some sample output.

```
print((1...10).map { a($0) })
// [1, 2, 3, 6, 9, 11, 15, 21, 24, 28]

```

It might actually be better to use a loop instead of recursion. Some limitations with closures (i.e. lambdas) in Swift forced me to use a function decl, which takes up a lot of space. :/
> 0 votes

# Answer
# CJam, 22 bytes

```
qi),:+{_)mqmo\mqi-}%:+

```

Uses `round(sqrt(n+1)) - floor(sqrt(n))` to calculate the `n`th position in the bit sequence. (Getting it as a repetition of numbers was smaller to generate, but one byte larger in the end to sum.)

Try it online!
> 0 votes

# Answer
# Red, 109 bytes

```
func[n][b:[[1]]loop n[append/only b head insert next
copy[0 1]last b]sum take/part load form b n + 1 * n / 2]

```

Try it online!

I know it's very long - I just wanted to see what the K solution (cortesy @coltim) would look like in Red :)
> 0 votes

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


title: Make an n-Juggler

text:
# Question
Title: Make an n-Juggler
I've been really interested with sequences that follow the property

\\$a(n+1) = a(n - a(n))\\$

recently, so here's another question about these sequences. In particular we are concerned with sequences from the integers to the natural numbers.

A periodic sequence with the above property is an **n**-Juggler if and only if it contains exactly **n** distinct values. For example the following sequence is a 2 juggler

```
... 2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1,2,2,1 ...

```

because it only contains the numbers `1` and `2`.

An example of a three juggler would be

```
... 3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5,3,5,3,5,1,5 ...

```

because it juggles `1`, `3`, and `5`.

# Task

Given **n \> 1** as input, output any **n**-Juggler.

You may output a sequence in a number of ways, you can

* output a function that indexes it.
* take an additional input of the index and output the value at that index.
* output a continuous subsection of the sequence that, with the given property *uniquely determines* the sequence.

This is so answers are scored in bytes with less bytes being better.

# Answer
> 5 votes
# Pyth, 5 bytes

```
t+*%E

```

Try the , ,  Jugglers.

Receives two numbers, **N** and **I**, separated by a newline and in this order. **I** is the index into the sequence.

This uses a quite simple formula: **N - 1 + N * (I % N)**. Its validity was confirmed by the OP.

# Answer
> 3 votes
# CJam, 9

How about this?

```
q~1$,=)*(

```

Try it online

Input is `n i` where `n` is the main input and `i` is the index you want to get the value for.

**Explanation:**

```
q~    read and evaluate the input (n and i)
1$    copy n
,=    basically this is a modulo (i%n) that avoids a negative result for negative i
)*    increment, then multiply by n
(     decrement

```

# Answer
> 1 votes
# Python 2, 20 bytes

```
lambda n,i:i%n*n+n-1

```

Try it online!

Same principle as Mr. Xcoder's answer

# Answer
> 1 votes
# Haskell, 17 bytes

```
n!i=i`mod`n*n+n-1

```

Try it online!

Another answer using Mr. Xcoder's idea. I wouldn't be able to answer the question otherwise to be honest. :P

# Answer
> 1 votes
# Vyxal, 4 bytes

```
%›*‹

```

Try it Online!

# Answer
> 0 votes
# Java 8, 15 bytes

```
n->i->i%n*n+n-1

```

Boring port of *@Mr.Xcoder*'s Pyth answer.

Try it here.

# Answer
> 0 votes
# Jelly, 5 bytes

```
Ɠ%×+’

```

Try it online!

Port of Mr. Xcoder's approach. The index I is in STDIN, N is an argument.

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