title: Do you know your 'KVZ's?

text:
# Question
Title: Do you know your 'KVZ's?
## **Concept**

In what ways can you scramble the English alphabet so that it can still be sung to the tune Twinkle Twinkle Little Star without ruining the tune?

## **Rules**

**Swapping**

Let's just assume the letters contained in each of the following sets can be swapped freely by default without ruining the tune:

* { A, J, K }
* { B, C, D, E, G, P, T, V, Z }
* { I, Y }
* { Q, U }
* { S, X, F }
* { M, N }
* Therefore H, L, O, R, and W are locked in place

**Output**

The program needs to output a single RANDOM string (or list of characters) containing the complete English alphabet in any order provided that order satisfies the conditions above. There should be no way for you to predict which string your program will output(if we ignore seeding), meaning you can't just hardcode it.

Your program must have some positive probability (not necessarily uniform) of generating each of the \\$ 9! \cdot 3! \cdot 3! \cdot 2! \cdot 2! \cdot 2! = 104509440 \\$ outputs.

There are no particular formatting restrictions regarding spacing, delimiters or case, just be consistent.

**Goal**

Fewest bytes wins!

## **Examples:**

* KCDBPSVHIAJLMNOZQRXGUEWFYT
* A,G,Z,V,P,X,C,H,Y,K,J,L,N,M,O,T,U,R,S,D,Q,B,W,F,I,E
* KVTDCFBHIJALNMOPURSZQGWXYE
* j c d e b x t h i k a l n m o g u r s v q p w f y z
* ABCDEFGHIJKLMNOPQRSTUVWXYZ

## **Nonexample:**

* HLWROABCDEFZXYGIJKMNPQTSVU

## **Proof of Concept: (Python3, 529 bytes)**

```
import random
g1 = ['A', 'J', 'K']
g2 = ['B', 'C', 'D', 'E', 'G', 'P', 'T', 'V', 'Z']
g3 = ['I', 'Y']
g4 = ['Q', 'U']
g5 = ['S', 'X', 'F']
g6 = ['M', 'N']
random.shuffle(g1)
random.shuffle(g2)
random.shuffle(g3)
random.shuffle(g4)
random.shuffle(g5)
random.shuffle(g6)
print(g1[0] + g2[0] + g2[1] + g2[2] + g2[3] + g5[0] + g2[4] + 'H' + g3[0] + g1[1] + g1[2] + 'L' + g6[0] + g6[1] + 'O' + g2[5] + g4[0] + 'R' + g5[1] + g2[6] + g4[1] + g2[7] + 'W' + g5[2] + g3[1] + g2[8])

```

# Answer
> 6 votes
# 05AB1E, 28 bytes

```
A.•¬=©ƶÓÄûkTVã”ØζÞ•Dás#€.rJ‡

```

Outputs as a single lowercase string.

Try it online or verify \\$n\\$ random outputs at once.

**Explanation:**

```
A                    # (a) Push the lowercase alphabet
 .•¬=©ƶÓÄûkTVã”ØζÞ•  # Push compressed string "ajk bcdegptvz iy qu sxf mn"
  Dá                 # (b) Duplicate it, and only keep the letters (removing the spaces)
    s#               # Swap to get the string again, and split it by spaces
      €.r            # Shuffle each substring randomly
         J           # (c) Join it back together to a single string
          ‡          # Transliterate all characters from (b) to (c) in string (a)
                     # (and output the result implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•¬=©ƶÓÄûkTVã”ØζÞ•` is `"ajk bcdegptvz iy qu sxf mn"`.

# Answer
> 7 votes
# Python 3, ~~140~~ ~~133~~ ~~124~~ 123 bytes

```
d=*map(set,'AJK BCDEGPTVZ IY QU SXF MN H L O R W'.split()),
print([d[int(c,16)].pop()for c in'0111141620075581394131a421'])

```

Try it online!

<sub>-1 byte, thanks to Jo King</sub>

---

# Python 2, ~~174~~ ~~170~~ 158 bytes

```
from random import*
s=''
for c in'abbbbebHcaaLffObdRebdbWecb':s+=choice(list(set(('AJK BCDEGPTVZ IY QU SXF MN '+c).split()['abcdef'.find(c)])-set(s)))
print s

```

Try it online!

# Answer
> 4 votes
# Ruby, 102 bytes

```
s=[*?A..?Z]*''
%w(AJK BCDEGPTVZ IY QU SXF MN).map{|e|a=e.chars.shuffle;s.gsub!(/[#{e}]/){a.pop}}
$><<s

```

Try it online!

# Answer
> 3 votes
# JavaScript - ~~421~~ ~~344~~ ~~328~~ ~~320~~ ~~306~~ ~~280~~ ~~277~~ ~~276~~ ... 176 Bytes

-77 Bytes - on my own
-18 Byte - thanks to @tsh and @Geza Kerecsenyi who made me see what @tsh initially pointed out too
-8 Bytes - thanks to @Geza Kerecsenyi
-14 Bytes - with help of @Geza Kerecsenyi
-28 Bytes - on my own
-3 Bytes - again with with help of @Geza Kerecsenyi
-1 Bytes - how could this happen...
**...**
-100 Bytes - @Kaiido killed it and via some steps before this whole thing got down to 176 Bytes

### Golfed:

```
c=[,'AJK','BCDEGPTVZ','IY','QU','SXF','MN'].map(s=>[...s]);alert([...'1222252H311L66O24R5242W532'].reduce((o,v)=>o+(+v?(p=>p.splice((Math.random()*p.length)|0,1))(c[v]):v),""))
```

or try it online!

# Answer
> 3 votes
# Pyth, ~~59~~ ~~57~~ 56 bytes

```
hMeD,Vs.SMJc"ajk bcdegptvz iy qu fsx mn h l o r w"dxLGsJ

```

Try it online!

Output is an array of lower case letters.

```
hMeD,Vs.SMJc"ajk bcdegptvz iy qu fsx mn h l o r w"dxLGsJ   Implicit: d=" ", G=<lowercase alphabet>
          Jc"ajk bcdegptvz iy qu fsx mn h l o r w"d        Chop the grouping string on spaces, store in J
                                                      sJ   Concatenate J into single string
                                                   xLG     Find the index of each letter in grouping string in the unaltered alphabet
       .SMJ                                                Shuffle each group in J
      s                                                    Concatenate into a single string
    ,V                                                     Pair the shuffled string with their 'correct' positions in the alphabet
  eD                                                       Order the pairs by the derived positions (last element of each pair)
hM                                                         Keep the letter from each pair (the first element)
                                                           Implicit print

```

# Answer
> 3 votes
# Perl 6, 76 bytes

```
{my@a='A'..'Z';<AJK BCDEGPTVZ IY QU SXF MN>>>.&{@a[.ords X-65].=pick(*)};@a}

```

Try it online!

Anonymous code block taking no arguments and returning a list of characters.

### Explanation:

```
{                                                                          } # Anonymous code block
 my@a='A'..'Z';      # Initialise @a as a list of the alphabet
               <AJK BCDEGPTVZ IY QU SXF MN>   # For each of the sets of letters
                                           >>.&{@a[.ords X-65].=       }  # Set those indexes
                                                                pick(*)   # To a random order
                                                                        ;@a  # And return

```

# Answer
> 3 votes
# , ~~93~~ 91 bytes

```
`^`=strsplit
L=LETTERS
for(s in el('AJK7BCDEGPTVZ7IY7QU7FSX7MN'^7)^'')L[L%in%s]=sample(s)
L

```

Try it online!

# Answer
> 2 votes
# Perl 5, ~~103 91~~ 85 bytes

```
map{my%l;@l{/./g}++;@k{/./g}=keys%l}AJK,BCDEGPTVZ,SXF,IY,QU,MN;say map$k{$_}||$_,A..Z

```

Try it online!

This code (ab)uses the fact that Perl's output of hash keys (`%l`) is random to create a mapping (`%k`) of all the modifiable letters to one of their possible counterparts. At output time, any key that doesn't exist is assumed to be unchanged.

# Answer
> 2 votes
# Jelly, 34 bytes

```
ØA“wẸXWỵḲ⁻ȦƙṄṇ’œ?µ“ĠQ’ḃ3ÄœṖ⁸Ẋ€Ẏị@Ụ

```

Try it online!

# Answer
> 2 votes
# Runic Enchantments, 210 bytes

```
>yy `AJK`06B$̤$@
>`BCDEGPTVZ`06B$$$$ $̤$y $ $y @
>̤`IY`06Byyy$yyy̤ @
> ̤`QU`06Byy̤ $y @
> ̤`FSX`06B $yy̤$yy@
>y̤ `MN`06Byyy $@
}}f}l3-[r\
3-[2'RA?rR1Kl'RAs]{1-:0)?\}l
> ̤`HLORW`06Bo$y $y$y$yy@ \~{{B͍

```

Try it online!

The randomization is *not uniform* as there isn't a good way to do that in Runic. Instead it randomly rotates each collection of letters (e.g. `[BCDEGPTVZ]` is one grouping) by some amount (e.g. rotating the above set by 4, where the top of the stack is at the right, the result would be `[BCDEGZPTV]`) and then randomly decides whether or not to reverse the stack. It performs these operations 15 times. As a result, all possible orderings are *possible* but not *equally likely.* (In the event that this is not enough, increasing it further costs zero bytes, up to 15000 shuffle loops).

This is the section of the code that handles the shuffling:

```
  v              vvvv           Loop counter

}}f}l3-[r\                      < Loop entry
[2'RA?r1KRl'RAs]{1-:0)?\}l3-
                       \~{{B͍    < loop exit

 ^^^^^^                         Randomly reverse
          ^^^^^                 Rotate by a random an amount

```

The rest of the code unrolls into this:

```
                     ABCDEFGHIJKLMNOPQRSTUVWXYZ
>      `AJK`08B      $        $$;
> `BCDEGPTVZ`08B      $$$$ $        $   $ $   $;
>         `IY`08B            $               $;
>          `QU`08B                   $   $;
>          `FSX`08B       $            $    $;
>            `MN`08B             $$;
>          `HLORW`08Bo      $   $  $  $    $;

^                                                   Create IPs
 ^^^^^^^^^^^^^^^^                                   Set letter groupings
                  ^^^                               Call shuffle function
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^    Print letters
                     ^                              Last letter group needs to be sorted

```

If the letters are left unshuffled (but once-reversed) by changing two bytes the alphabet is printed normally, which can be used to verify that all letter groupings print in the correct places. The whitespace shifting the `B` commands out of phase is so that all the IPs can use the function loop at the same time without colliding, and then getting them back into phase again.

To golf, first any space that could be removed on all lines was trimmed, then each two spaces were converted to a `y`, and every sequence of `yyyy` was converted to `̤` because `̤` and `yyyy` are the same amount of delay, but 2 bytes cheaper. The loop exit was also combined with the `HLORW` main program segment in order to save on the spacing bytes (12 bytes).

# Answer
> 1 votes
# Python 3, 149 bytes

```
a,b,i,q,s,m,h,l,o,r,w=(set(s)for s in["AJK","BCDEGPTVZ","IY","QU","SXF","MN",*"HLORW"])
print([eval(c).pop()for c in[*"abbbbsbhiaalmmobqrsbqbwsib"]])

```

Try it online!

Randomization by using pop() for letter set

# Answer
> 1 votes
# APL (Dyalog Extended), 55 bytes

Full program. Prints uppercase with a leading and trailing space, but no intermediary spaces.

```
{(?⍨∘≢⊇⊢)@(∊∘⍺)⊢⍵}/⌈'AjkBcdegptvzIyQuSxfMn'(⊂⍤⊢,⍨∊⊂⊣)⎕A

```

Try it online!

`⎕A` the uppercase alphabet

`'AjkBcdegptvzIyQuSxfMn'(``)` apply the following anonymous tacit function with that as right argument and the indicated string as left argument:

for the left argument,

partition it, beginning a new segment where

the left arguments characters are members of the right argument (i.e. on uppercase letters)

`,⍨` append

enclose (to treat it as a single element)
the
right argument

uppercase everything

`{``}/` reduce by the following anonymous lambda, giving …`"QU"λ("SXF"λ("MN"λ"A-Z"))`:

`⊢⍵` on the right argument (the scrambling-in-progress alphabet)

`(``)@(∊∘⍺)` apply the following anonymous tacit function to the subset that is a member of the left argument (a rhyme group)

on that subset

reorder it to be

`?⍨` a random permutation
of length
tally of letters in the subset

# Answer
> 1 votes
# Charcoal, 43 bytes

```
ＦαＦ⪪”＆↖(vＪf#Ｓ»↖ιηa↷Ｎ↖⪪νＰ´↑x‖υ” Ｆ№κι‽Φκ¬№ＫＡμ

```

Try it online! Link is to verbose version of code. Charcoal has no shuffling operators, but I came up with a method of sampling without replacement. Explanation:

```
Ｆα

```

Loop over each letter of the alphabet.

```
Ｆ⪪”＆↖(vＪf#Ｓ»↖ιηa↷Ｎ↖⪪νＰ´↑x‖υ”

```

Split the string `AJK BCDEGPTVZ IY QU SXF MN H L O R W` on spaces and loop over the substrings.

```
Ｆ№κι

```

Loop over the number of times the current letter appears in the substring. (I use a loop because a conditional would need an `else` caluse. Alternatively I could have filtered on the substring containing the current letter for the same byte count.)

```
‽Φκ¬№ＫＡμ

```

Print a random character but exclude ones that have already been printed.

# Answer
> 0 votes
# Retina, 80 bytes

```
K`1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z
~(K`123456
.
?O`$&.¶
)`¶$
[blank line]
\d
[blank line]

```

Try it online!

Probably not the most golfed method, but I'll submit it anyway.

**Explanation:**

```
K`1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z

```

Set the working string to `1A2B2C2D2E5F2GH3I1J1KL6M6NO2P4QR5S2T4U2VW5X3Y2Z`. There is a number before each letter in a group, for example `A`, `J` and `K` all have `1` before them.

```
~(

```

Mark a section of code that will produce some retina code, then run it afterwards.

```
K`123456

```

Set the working string to `123456`

```
.
?O`$&.¶

```

Replace each character with `?O`{character}.¶`

```
)`¶$
[blank line]

```

Remove the trailing newline and finish the group to generate the code. The group will generate the code:

```
?O`1.
?O`2.
?O`3.
?O`4.
?O`5.
?O`6.

```

`{n}.` matches all instances of number *n* followed by a character. `?O` sorts each instance randomly, and this is done for all character sets.

```
\d
[blank line]

```

Finally, remove all numbers and implicitly output the generated string.

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


title: Find X,Y,Z coordinates from index

text:
# Question
Title: Find X,Y,Z coordinates from index
## Introduction

I began studying the Collatz Conjecture

And noticed these patterns;
0,1,2,2,3,3...A055086, and 0,1,2,0,3,1...A082375,
in the numbers that go to 1 in one odd step,
5,10,20,21,40,42...A062052
Related like so;
A062052()(n) = ( 16\*2^A055086(n) - 2^A082375(n) ) /3

The formula for A055086 is $$\lfloor\sqrt{4n + 1}\rfloor - 1$$

and the formula for A082375 is $${\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor - 1 - \left\lfloor \frac12 \left(4\left\lfloor x\right\rfloor + 1 -\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor^2\right)\right\rfloor}$$

So the formula for A062052 most likely is

$$\frac{8\cdot2^{\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor} - 2^{\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor - 1 - \left\lfloor \frac12 \left(4\left\lfloor x\right\rfloor + 1 -\left\lfloor\sqrt{4\left\lfloor x\right\rfloor+1}\right\rfloor^2\right)\right\rfloor}}{3}$$

Then I looked at numbers going to 1 in two steps, like 3,6,12,13,24,26...
Where I found another pattern that I could not find a formula for on OEIS

```
long nth(int n){if(n>241)return -1;return (((1<<Y[n]+5)-(1<<1+Y[n]-((Z[n]&1)+Z[n]*3)))/3-(1<<Y[n]-2*X[n]-(2*(Z[n]&1)+Z[n]*3)))/3;}

```

With `X[],Y[] and Z[]` being these lookup-tables

```
 int[]X=new int[]{
 0,
 0,
 0,  1,
 0,  1,
 0,  1,  2,
 0,  1,  2,                              0,
 0,  1,  2,  3,                          0,                          0,
 0,  1,  2,  3,                          0,  1,                      0,
 0,  1,  2,  3,  4,                      0,  1,                      0,  1,
 0,  1,  2,  3,  4,                      0,  1,  2,                  0,  1,
 0,  1,  2,  3,  4,  5,                  0,  1,  2,                  0,  1,  2,
 0,  1,  2,  3,  4,  5,                  0,  1,  2,  3,              0,  1,  2,                  0,
 0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,              0,  1,  2,  3,              0,              0,
 0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,  4,          0,  1,  2,  3,              0,  1,          0,
 0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,          0,  1,  2,  3,  4,          0,  1,          0,  1,
 0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,          0,  1,  2,      0,  1,
 0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,  5,      0,  1,  2,      0,  1,  2,
 0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  0,  1,  2,      0,
 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  0,  1,  2,  3,  1, 2
 };
 int[]Y=new int[]{
 0,
 1,
 2,  2,
 3,  3,
 4,  4,  4,
 5,  5,  5,                              5,
 6,  6,  6,  6,                          6,                          6,
 7,  7,  7,  7,                          7,  7,                      7,
 8,  8,  8,  8,  8,                      8,  8,                      8,  8,
 9,  9,  9,  9,  9,                      9,  9,  9,                  9,  9,
10, 10, 10, 10, 10, 10,                 10, 10, 10,                 10, 10, 10,
11, 11, 11, 11, 11, 11,                 11, 11, 11, 11,             11, 11, 11,                 11,
12, 12, 12, 12, 12, 12, 12,             12, 12, 12, 12,             12, 12, 12, 12,             12,             12,
13, 13, 13, 13, 13, 13, 13,             13, 13, 13, 13, 13,         13, 13, 13, 13,             13, 13,         13,
14, 14, 14, 14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14,         14, 14,
15, 15, 15, 15, 15, 15, 15, 15,         15, 15, 15, 15, 15, 15,     15, 15, 15, 15, 15,         15, 15, 15,     15, 15,
16, 16, 16, 16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16,     16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17,     17,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18
};
int[]Z=new int[]{
0,
0,
0,  0,
0,  0,
0,  0,  0,
0,  0,  0,                              1,
0,  0,  0,  0,                          1,                          2,
0,  0,  0,  0,                          1,  1,                      2,
0,  0,  0,  0,  0,                      1,  1,                      2,  2,
0,  0,  0,  0,  0,                      1,  1,  1,                  2,  2,
0,  0,  0,  0,  0,  0,                  1,  1,  1,                  2,  2,  2,
0,  0,  0,  0,  0,  0,                  1,  1,  1,  1,              2,  2,  2,                  3,
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,              2,  2,  2,  2,              3,              4,
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,  1,          2,  2,  2,  2,              3,  3,          4,
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,          2,  2,  2,  2,  2,          3,  3,          4,  4,
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,          3,  3,  3,      4,  4,
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,  2,      3,  3,  3,      4,  4,  4,
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,      3,  3,  3,  3,  4,  4,  4,      5,
0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  5, 5
};

```

## Challenge

The challenge is to write a "reasonably fast" function or expression that replaces, and extends these lookup tables to index 719 or more.
Think of the lookup tables as a 3D structure of boxes. Pictured is the top 720 boxes of this structure.

## Input

An integer which is the index of a cube in the structure. You can assume the input will be in the range 0 to 719 inclusive.

## Output

The x,y,z coordinates for the given index. Assuming the input is between 0 and 719 the output ranges are x, 0 to 13 y, 0 to 27 z, 0 to 8

It's fine to accept and return larger indexes correctly just not required.

## Examples

```
    i  ->   x   y   z
    0  ->   0,  0,  0
   12  ->   0,  5,  1
   30  ->   4,  8,  0
   65  ->   2, 11,  1
  100  ->   0, 13,  2
  270  ->   1, 19,  3
  321  ->   1, 20,  6
  719  ->   1, 27,  8

```

If you collapse the z-coordinate, then the structure is indexed top-down left right like shown below; Examples are marked in square brackets \[\]

```
Y,Z 0,
 0   | [0]
 1   |  1
 2   |  2   3
 3   |  4   5
 4   |  6   7   8                                1,
 5   |  9  10  11                                 |[12]                           2,
 6   | 13  14  15  16                             | 17                             | 18
 7   | 19  20  21  22                             | 23  24                         | 25
 8   | 26  27  28  29 [30]                        | 31  32                         | 33  34
 9   | 35  36  37  38  39                         | 40  41  42                     | 43  44
10   | 45  46  47  48  49  50                     | 51  52  53                     | 54  55  56                    3,
11   | 57  58  59  60  61  62                     | 63  64 [65] 66                 | 67  68  69                     | 70                4,
12   | 71  72  73  74  75  76  77                 | 78  79  80  81                 | 82  83  84  85                 | 86                 | 87
13   | 88  89  90  91  92  93  94                 | 95  96  97  98  99             [100] 101 102 103                |104 105             |106
14   |107 108 109 110 111 112 113 114             |115 116 117 118 119             |120 121 122 123 124             |125 126             |127 128
15   |129 130 131 132 133 134 135 136             |137 138 139 140 141 142         |143 144 145 146 147             |148 149 150         |151 152
16   |153 154 155 156 157 158 159 160 161         |162 163 164 165 166 167         |168 169 170 171 172 173         |174 175 176         |177 178 179        5,
17   |180 181 182 183 184 185 186 187 188         |189 190 191 192 193 194 195     |196 197 198 199 200 201         |202 203 204 205     |206 207 208         |209    6,
18   |210 211 212 213 214 215 216 217 218 219     |220 221 222 223 224 225 226     |227 228 229 230 231 232 233     |234 235 236 237     |238 239 240 241     |242     |243
19   |244 245 246 247 248 249 250 251 252 253     |254 255 256 257 258 259 260 261 |262 263 264 265 266 267 268     |269[270]271 272 273 |274 275 276 277     |278 279 |280
20   |281 282 283 284 285 286 287 288 289 290 291 |292 293 294 295 296 297 298 299 |300 301 302 303 304 305 306 307 |308 309 310 311 312 |313 314 315 316 317 |318 319 |320[321]
  X->|  0   1   2   3   4   5   6   7   8   9  10 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4 |  0   1   2   3   4 |  0   1 |  0   1

```

Note that at even y-coordinates the structure expands in the x-direction, and at 0 and 5 mod 6 in the z-direction.

# Rules

This is code-golf, the shortest code in bytes wins.

**Reasonably fast** As an additional requirement although not a competition of fastest code,
the code must still be shown to compute coordinates in a reasonable amount of time.
\\$\ O(n)\\$ or less time-complexity with regards to index is valid by default

Alternatively may for example use try it online or similar website and run a loop through all coordinates under 720 without exceeding the time limit of a minute, printing is optional.
Any time-complexity is valid as long as actual time is reasonably low.

Lookup tables are allowed but included in byte-count so aim to make them sparse if you choose to use them.

# Example code

EDIT: Look at Nick Kennedy's solution

Original example;

```
coord coords(int index){
int a=0,b=0,c=0;
int x=0,y=0,z=0;
long n,k,one;
n = k = 3;
int t=0;
while(t<index){
int s=0;k++;n=k;
while(n>1 && s<4){ n/=n&-n;n=n*3+1; n/=n&-n;s++;}
if(s==2)t++;
}
n=k;
one=n&-n;k = one;while(k>1){k>>=1;c++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;b++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;a++;}
coord r;
r.x = (b-c-1)>>1;
r.y = a-5;
r.z = (a-b-2)/6 +(a-b-4)/6;
return r;
}

```

Try it online! Note it's too slow!

# Answer
> 4 votes
# Jelly, 31 bytes

```
5,1ṁ9ĖŒṙṚḊḊḊ$Ƭz0ZUṬ€€ỊŒṪ’ṙÞ1ị@‘

```

A monadic link accepting an integer in \\$\[0,719\]\\$ which yields a list of three integers \\$\[X, Y, Z\]\\$.

**Try it online!**

Or see the test-suite (which completes in around 12-20s on TIO)

### How?

Builds a lookup table and indexes into it:

```
5,1ṁ9ĖŒṙṚḊḊḊ$Ƭz0ZUṬ€€ỊŒṪ’ṙÞ1ị@‘ - Link: integer, n
5,1                             - pair literal = [5,1]
   ṁ9                           - mould like 9 = [5,1,5,1,5,1,5,1,5]
     Ė                          - enumerate = [[1,5],[2,1],[3,5],[4,1],[5,5],[6,1],[7,5],[8,1],[9,5]]
      Œṙ                        - run-length-decode = [1,1,1,1,1,2,3,...,7,7,7,7,7,8,9,9,9,9,9]
        Ṛ                       - reverse = [9,9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1]
         Ḋ                      - dequeue = [9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1]
             Ƭ                  - collect until a fixed-point:
            $                   -   last two links as a monad:
          Ḋ                     -     dequeue
           Ḋ                    -     dequeue
                                - } = [[9,9,9,9,8,7,7,7,7,7,...,3,2,1,1,1,1,1],[9,9,8,7,...],[8,7,...],...,[1,1],[]]
              z0                - transpose with filler zero
                Z               - transpose
                 U              - reverse each list
                  Ṭ€€           - un-truth each int (e.g. 5 -> [0,0,0,0,1])
                     Ị          - insignificant? (abs(x)<=1) (e.g. [0,0,0,0,1]->[1,1,1,1,1])
                      ŒṪ        - truthy multi-dimensional 1-indexed indices
                        ’       - decrement (i.e. all the [X,Y,Z] values)
                          Þ     - sort by:
                         ṙ 1    -   the list value rotated left by one (i.e. by [Y,Z,X])
                              ‘ - increment (n) (since Jelly is 1-indexed)
                             @  - with swapped arguments:
                            ị   -   index into

```

# Answer
> 5 votes
# Python 3, ~~150~~ 140 bytes

```
def f(n):
 a=b=x=y=z=0
 for i in range(n):
  a=x-~x<y--~z//2*6+z%2
  b=z<y//6+-~y//6
  x=-~x*a
  y+=not(a|b)
  z+=b>a
  z*=a|b
 return x,y,z

```

Try it online!

Has \\$O(n)\\$ complexity. TIO footer prints first 720 values in about 0.5 seconds.

Thanks to @ElPedro and @PrincePolka for each saving 5 bytes!

# Answer
> 3 votes
# JavaScript, ~~93~~ 85 bytes

A port of Nick's Python solution.

```
n=>(g=x=>n--?g(x<y+~z/2n*6n+z%2n>>1n?++x:z<y/6n-~y/6n?++z-z:z=++y-y):[x,y,z])(y=z=0n)

```

Try It Online!

Saved 8 bytes thank to Arnauld's suggestion of using BigInts, plus a couple of other tweaks.

# Answer
> 2 votes
# Jelly, ~~54~~ 41 bytes

```
HĊ×6_Ḃ{ạHḞ;;‘$:6SƊ}
<Ḋç/$T;3ḢṬ
0x3Ç+×¥$⁸¡

```

Try it online!

Loosely a Jelly translation of my Python 3 answer but much slower. Still \\$O(n)\\$ though. Outputs `[x, z, y]`.

---
Tags: code-golf, math, integer, restricted-time
---


# Question
Title: Calculate the points in a "sjoelen"-game
Okay, so yesterday was 2nd Christmas day and my (grand)parents and me had a game of "sjoelen", as it is called in the Netherlands. The inner programmer came up in me, but just when I had the answer, I lost it. I want you to remake it.

*The rules:*

You have a wooden plank, a *sjoelbak*, with 4 boxes, each with their own number. When a *schijf* (A puck-like object) goes in one of the boxes you get the points above that box.

When there is a *schijf* in all 4 of the boxes, you don't get 10 but you get 20 points.

*Example:*

From left to right: 3 5 4 3
Each box has at least 3 *schijven* (Plural of *schijf*) so that is 20 * 3 = 60 points.

Resulting values: 0 2 1 0
0\*2 + 2\*3 + 1\*4 + 0\*1 = 10 points.

Which makes a total of 60+10 = 70 points.

*The input:*
The amount of *schijven* from left to right, ie "4 5 4 5", \[4,5,4,5\], "4\n5\n4\n5", whatever you like.

*The output:*
The amount of points, ie 84, as output, variable, return or on top of the stack, whatever you like.

As in each and every code golf, you can not use external scripts and the code with the least bytes wins.

PS: As you may have already noticed, I'm Dutch. Feel free to edit possible grammar mistakes.

# Answer
# CJam, ~~23 21~~ 20 bytes

```
q~_$0=f+1m>{X):X*+}*

```

I might be able to golf a couple of bytes off this.

Input is like

```
[3 5 4 3]

```

Output is the score

```
70

```

**How it works**

```
q~                         "Read the input and evaluate into an array";
  _$0=                     "Copy the array, sort it and get the minimum number";
                           "This minimum is the number of common schijven";
      f+                   "Increment each of the schijven by the common schijven number";
        1m>                "Take 1 element from the end of the array and put";
                           "it in the beginning";
           {      }*       "Reduce the elements of the array based on this block";
            X):X           "Increment and update the value of X (initially 1)";
                *          "Multiply the number of schijven with X";
                 +         "Add it to current score";

```

**Algorithm**

* Since I have right shifted the number of schijven, the score order now becomes `[1 2 3 4]`.
* Moreover, using the fact that `1 + 2 + 3 + 4 = 10`, I simply add the minimum common schijven to each one to get the effect of bonus `10` score.
* Now when I reduce, I get 2 elements initially on stack, the first one, which I ignore is the one with a score of `1` each, then I multiply the second one with `2` and add it to first. In the next iteration, I get the current sum and score `3` schijven. And so on.

Try it online here
> 8 votes

# Answer
# APL (Dyalog Classic), ~~16~~ ~~13~~ 12 bytes

-3 thanks to @Adám

```
(+/+\)1⌽⌽+⌊/

```

Try it online!

`⌽+⌊/` reverse(arg) + min(arg)

`1⌽` rotate 1 to the left

`+\` partial sums

`+/` sum
> 8 votes

# Answer
# Piet, 240 (30\*8) codels, 138 containing actual code

Codel size 10, for better visibility

Test examples:

```
D:\codegolf\npiet-1.3a-win32>npiet sjoelen_point_count_cs10.png
? 3
? 5
? 4
? 3
70
D:\codegolf\npiet-1.3a-win32>npiet sjoelen_point_count_cs10.png
? 4
? 5
? 4
? 5
84

```

Flow display:

Using my own shorthand for easier handling and compact display. It shows the general program flow, not the exact locations of the codels.

```
NOP ADD DIV GRT DUP INC END
 0   +   /   >   =   c   ~
PSH SUB MOD PTR ROL OUN
 X   -   %   #   @   N
POP MUL NOT SWI INN OUC
 ?   *   !   $   n   C

1X!nnnn=5X2X@=5X2X@=5X2X@=5X1X@**
       0                        *
       0       @+5X1X@1X-4X1X@  !
       0       -             0  !
       0       X1!X1X6+*==X40000#  <--pointer if top of stack=1 (all boxes full,
       0                     0  2      add 20 points, decrement count for all boxes)
       0000-X1@X1X2-X1@X1X3-X1  X  |  pointer if top of stack=0 (not all boxes full,
                                *  V   add 2a+3b+4c+d)
           ~N++++*X4@X2X3*X3@X1X2

```

Full explanation:

```
      (score=0)  a   b   c   d
      1 PSH NOT INN INN INN INN

      ..... sort and duplicate the numbers .....
**1** DUP 5 PSH 2 PSH ROL DUP 5 PSH 2 PSH ROL DUP 5 PSH 2 PSH ROL DUP 5 PSH 1 PSH ROL

      ( a*b*c*d ) (convert to boolean) 1 if all boxes are full, 0 if at least one box is empty
      MUL MUL MUL NOT NOT

      change direction if 1 (**2**)
      go straight ahead if 0 (**3**)
      PTR

      ( compress 20=4*4+4 )       (0-1=-1/ neg. roll) score+20
**2** 4 PSH DUP DUP MUL ADD 6 PSH 1 PSH NOT 1 PSH SUB ROL ADD

      (put score back to bottom of stack) ... a=a-1, b=b-1, c=c-1, d=d-1 ...
      5 PSH 1 PSH ROL 1 PSH SUB 4 PSH 1 PSH ROL 1 PSH SUB 3 PSH
      1 PSH ROL 1 PSH SUB 2 PSH 1 PSH ROL 1 PSH SUB

      loop to **1**

      (   a*2   )               (   b*3   )               (  c*4  )
**3** 2 PSH MUL 2 PSH 1 PSH ROL 3 PSH MUL 3 PSH 2 PSH ROL 4 PSH MUL

      +2a +3b +d +score
      ADD ADD ADD ADD

      output score
      OUN

```

Save the image and try it out in this online Piet interpreter:

PietDev online Piet interpreter
> 8 votes

# Answer
# R, ~~41~~ 40 chars

```
b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1))

```

Usage:

```
> b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1))
1: 4 5 4 5
5:
Read 4 items
[1] 84
> b=min(a<-scan());sum(5*b+(a-b)*c(2:4,1))
1: 3 5 4 3
5:
Read 4 items
[1] 70

```

In the last example, `a` is vector `3 5 4 3`, `a-b` is `0 2 1 0`, which we multiply with vector `2 3 4 1` thus giving `0 6 4 0` which we add with `5*b` giving `15 21 19 15` (`5*b` being recycled for each member of the added vector, hence effectively adding `4*5*b`), which we finally sum, thus giving `70`.
> 7 votes

# Answer
# Mathematica, ~~38~~ ~~32~~ ~~23~~ 20 bytes

```
(#+Min@#).{2,3,4,1}&

```

(With help from *swish*)

Use by tacking the input on to the end:

```
(#+Min@#).{2,3,4,1}&@{3,5,4,3}

70

```

Alternate (36 bytes):

```
20*Min@#+Total[(#-Min@#)*{2,3,4,1}]&

```
> 7 votes

# Answer
# J, ~~23~~ 22 chars

```
   (+/ .*&2 3 4 1@(+<./))

```

Example:

```
   test =. 3 5 4 3
   (+/ .*&2 3 4 1@(+<./)) test
70

```

Try it here.

(23 long explicit function definition: `v=:3 :'+/+/\.3|.y+<./y'`)
> 5 votes

# Answer
# JavaScript (ES6), ~~93~~ 47 bytes

```
s=(a,b,c,d)=>10*Math.min(a,b,c,d)+a*2+b*3+c*4+d

```

Usage: `s(1, 2, 3, 4)`

How it works: the function looks for the smallest number in the arguments, and multiplies that by `10` (not with `20`) and adds the rest of the score. It's not necessary to multiply by `20` and substract parts from the score to continue the calculation.

Thanks to edc65 for sharing improvements!

Un-golfed:

```
function score(a, b, c, d) {
    return 10 * Math.min(a, b, c, d) + a * 2 + b * 3 + c * 4 + d;
}

```
> 5 votes

# Answer
# Pyth, 15

```
sm*hd+@QtdhSQUQ

```

Input should be given comma separated on STDIN, e.g.

```
3,5,4,3

```

This uses the same trick that many other solutions have used, of adding the minimum to each element to account for the bonus. The minimum is `hSQ` in the above code. To account for multiplying by 2, 3, 4, and 1, I map d over the list \[0,1,2,3\], and multiply the (d-l)th element of the input by d+1. Thus, the -1th element is multiplied by 1, the zeroth by 2, the first by 3 and the second by 4. Then I sum.
> 5 votes

# Answer
# Ostrich v0.1.0, ~~48~~ 41 characters (way too long)

```
.$0={}/:n;{n-}%)\+1:i;{i*i):i;}%{+}*20n*+

```

This is simply the same as the old version below, except that instead of using `@` to rotate the whole stack, `)\+` (right uncons) is used instead.

Old version:

```
.$0={}/:n;{n-}%{}/{4@}3*1:i;]{i*i):i;}%{+}*20n*+

```

I have actually discovered two bugs in my very newly implemented language, annotated in the description below. (The language is currently very, very similar to Golfscript, so if you know Golfscript it should be fairly easy to read.

```
.$0=   get min value (for the *20 thingy)
{}/    *actually* get min value (BUG: `array number =' returns a single-element array...)
:n;    store as n
{n-}%  subtract this value from all array elements
{}/    dump array onto stack
{4@}3* rotate stack so that instead of 2 3 4 1, multipliers are 1 2 3 4
       (BUG: negative rotations don't work)
1:i;   set i (the multiplier) to 1
]{i*   multiply each array element by i
i):i;  increment i
}%     (do the previous 2 lines over each array element)
{+}*   add up all the array elements
20n*+  add 20*n (the min value we got in line 1)

```

Expects input as an array on STDIN, because I'm a doorknob and forgot to implement I/O in v0.1.0.

Solving an actual problem in Ostrich is nice, because it shows me exactly how much more stuff I need to add to the language :D
> 4 votes

# Answer
# Python 2, 43 bytes

```
lambda i:i[1]-i[3]+2*(sum(i)+i[2]+5*min(i))

```

Inspired by @user2487951's answer.
> 4 votes

# Answer
# Haskell, 40

```
g l@[a,b,c,d]=2*a+3*b+4*c+d+10*minimum l

```

instead of removing the minimum number from the rest and adding additional `20`s, this adds additional `10` for the minimum number.
> 3 votes

# Answer
# Jagl Alpha 1.2 - 20 bytes

Input is in stdin in format `(3 4 5 6)`, output is left on stack:

```
T~dqZ*S1 5r]%{U*}/b+

```

~~Waiting for a response from the original poster about the output format. Since input is specified as *"whatever you like"*, I am going to assume that my input can be an array on the top of the stack.~~ Now takes input on stdin.

Explanation:

```
T~                            Get input from stdin and evaluate
  dqZ*                      Duplicate, get minimum, and multiply that by 10
      S1 5r]                Swap (so array is on top), push range 1-5 exclusive, and rotate
            %{U*}/          Zip arrays together, and multiply each pair
                  b+P       Get the sum of that, add the common minimum, and print

```
> 3 votes

# Answer
# Matlab, 27

Took me a while to understand that it is single player game. With the help of anonymous function

```
f=@(N)N*[2;3;4;1]+10*min(N)

```

which is invoked with row vector

```
f([3 5 4 3]) == 70
f([7 7 9 7]) == 148

```
> 3 votes

# Answer
# Java, 84 bytes

```
int A(int[]a){int m=9;for(int i:a)m=i<m?i:m;return 10*m+a[3]+2*a[0]+3*a[1]+4*a[2];}

```

I have the idea this can be golfed any further, but this is it for now.

Call with `A(new int[]{3,5,4,3})`, output is returned as int (Because `System.out.println()` would double the bytes)

Ungolfed

```
int getScore(int[] input){
    int min=9;

    for(int x:input) {
        if(x<min){
            min=x;
        }
    }

    return 10*min + 2*input[0] + 3*input[1] + 4*input[2] + 1*input[3];
}

```
> 2 votes

# Answer
# GolfScript, 22 bytes

```
~3,{1$>~;}%+$(11*+{+}*

```

Reads input from stdin, in the format `[3 5 4 3]`. Writes output to stdout. (If taking the input as an array on the stack is allowed, the leading `~` may be omitted for a total of 21 bytes.)

This uses a somewhat different strategy than the CJam / Pyth / etc. solutions: I first build an array with 2 copies of the first input value, 3 of the second, 4 of the third and one of the fourth. Then I sort this array, pull out the smallest element, multiply it by 11 and sum it with the other elements.
> 2 votes

# Answer
## Python 2, 51

Uninspired, but short:

```
l=input()
print l[0]*2+l[1]*3+l[2]*4+l[3]+10*min(l)

```

More pythonic:

```
l=input()
print sum(map(lambda x,y:x*y,l,[2,3,4,1]))+10*min(l)

```
> 2 votes

# Answer
# Julia, ~~48~~ 35 characters

~~`function p(m);sum([2 3 4 1].*m)+10minimum(m);end`~~

in compact assignment form:

```
p(m)=sum([2 3 4 1].*m)+10minimum(m)

```

Example:

```
julia> p([3 5 4 3])
70

```
> 2 votes

# Answer
# Javascript, 97 bytes

```
a=prompt().split(" "),b=Math.min.apply(1,a);alert(20*b+2*(a[0]-b)+3*(a[1]-b)+4*(a[2]-b)+(a[3]-b))

```
> 2 votes

# Answer
# Javascript, ES6, 57

```
f=(a,b,c,d)=>a*b*c*d?20+f(--a,--b,--c,--d):a*2+b*3+c*4+d

```

I wanted to see how recursion would turn out, and while it is definitely not the shortest answer, I felt like it turned out well.

**`a*b*c*d`**: It takes the input values and finds the product of all of them, and evaluate that as a Boolean expression for an inline if statement. This will return false if one or more of the values is 0, and true for any other value.

**`20+f(--a,--b,--c,--d)`**: If it returns true, the function returns 20 (for the *schijven* set) plus the recursive call of the function for all of the values minus one (To remove that *schijven* set). In this way it will recursively loop through until at least one of the boxes is empty.

**`a*2+b*3+c*4+d`** After at least one box it empty, the else part of the inline if statement will run. It just returns the points for the remaining *schijven* in the boxes.

Thus at the end all of the 20 point *schijven* sets, and the remanding points are summed up and returned from the function, producing the answer.
> 1 votes

# Answer
# Haskell 42 chars

```
f l=10*minimum l+sum(zipWith(*)[2,3,4,1]l)

```
> 1 votes

# Answer
# HPPPL (HP Prime Programming Language), ~~58~~ 57 bytes

The * between 10 and min isn’t necessary, so I removed it.

```
EXPORT s(m)
BEGIN
return sum([2,3,4,1].*m)+10min(m);
END;

```

HPPPL is the programming language for the HP Prime color graphing calculator/CAS.

Example runs:

If it doesn’t have to be a program, then it’s realizable in a ~~40~~ 39 bytes one-liner:

```
m:=[3,5,4,3];sum([2,3,4,1].*m)+10min(m)

```
> 1 votes

# Answer
# Staq, 72 characters

```
't't't't{aii*XX}$&iia$&ia$&a+XX+XX+|{mxx}{lxX}{k>?m!l}kkk&iiqi&ii*s*t|+:

```

Example run:

```
Executing D:\codegolf\Staq\sjoelen codegolf.txt

3
5
4
3
70

Execution complete.
>

```

Staq has two stacks, one active, one passive. The `|` command switches the active stack to passive and vice versa.

Everything between curly braces defines a function, the first letter after the opening brace is the function name, the rest until the closing brace is the function itself. Overriding functions, recursion and nested functions are possible. `{aii}` would define a function *a* that would increment the top of the stack twice. Every following instance of `a` in the code will be replaced by `ii`.

Comments inside *Staq* prorams: `&` adds a zero on top of the stack, `[` instructs the pointer to jump to the corresponding `]` if the top of the stack is zero, `x` deletes the topmost value on the stack. So, comments can be written into the code in the form of `&[here is a comment]x`

Explanation (also executable):

```
'                                      &[input number]x
 t                                     &[copy top of active stack to passive stack]x
  t't't                                &[input next three numbers and copy them to the passive stack]x
       {aii*XX}                        &[define function a (increment twice, multiply the two topmost values, then delete the second value on the stack twice)]x
               $                       &[move top value to the bottom of the stack]x
                &ii                    &[put zero on top of the stack, incremment twice]x
                   a                   &[function a]x
                    $&ia$&a
                           +           &[put sum of the two topmost values on top of the stack]x
                            XX         &[delete second stack value, twice]x
                              +XX+
                                  |    &[switch active/passive stack]x
{mxx}                                  &[define function m: delete two topmost stack values]x
     {lxX}                             &[define function l: delete topmost stack value, then delete second value of remaining stack]x
          {k>?m!l}                     &[define function k: boolean top > second value? put result on top of the stack, if top>0 then execute m, if top = 0 then execute l]x
                  kkk&ii
                        q              &[put square of top value on top of the stack]x
                         i&ii
                             *         &[multiply two topmost values and put result on top of the stack]x
                              s        &[move bottom stack value to the top]x
                               *t|+
                                   :   &[output result]x

```

https://esolangs.org/wiki/Staq

The program uses one stack (initially active) to calculate 2a+3b+4c+d, and the second stack (initially passive) to calculate 10 times the minimum of the input values. Then both results are summed up and displayed.
> 1 votes

# Answer
# PowerShell for Windows, ~~48~~ 47 bytes

-1 byte thanks to mazzy

```
$args|%{$a+=++$i%4*$_+$_}
$a+10*($args|sort)[0]

```

Try it online!
> 1 votes

---
Tags: code-golf, board-game
---


title: Subdivide-Sum Sequence

text:
# Question
Title: Subdivide-Sum Sequence
Consider the digits of any integral base above one, listed in order. Subdivide them exactly in half repeatedly until every chunk of digits has odd length:

```
Base    Digits              Subdivided Digit Chunks
2       01                  0 1
3       012                 012
4       0123                0 1 2 3
5       01234               01234
6       012345              012 345
7       0123456             0123456
8       01234567            0 1 2 3 4 5 6 7
9       012345678           012345678
10      0123456789          01234 56789
11      0123456789A         0123456789A
12      0123456789AB        012 345 678 9AB
...
16      0123456789ABCDEF    0 1 2 3 4 5 6 7 8 9 A B C D E F
...

```

Now, for any row in this table, read the subdivided digit chunks as numbers in that row's base, and sum them. Give the result in base 10 for convenience.

For example...

* for base 3 there is only one number to sum: 0123 = 123 = **510**
* for base 4 there are 4 numbers to sum: 04 \+ 14 \+ 24 \+ 34 = 124 = **610**
* base 6: 0126 \+ 3456 = 4016 = **14510**
* base 11: 0123456789A11 = **285311670510**

# Challenge

Write a program that takes in an integer greater than one as a base and performs this subdivide sum procedure, outputting the final sum **in base 10**. (So if the input is `3` the output is `5`, if the input is `6` the output is `145`, etc.)

Either write a function that takes and returns an integer (or string since the numbers can get pretty big) *or* use stdin/stdout to input and output the values.

The shortest code in bytes wins.

# Notes

* You may use any built in or imported base conversion functions.
* There is no upper limit to the input value (besides a reasonable `Int.Max`). The input values don't stop at 36 just because *"Z"* stops there.

*p.s. this is my fiftieth question :)*

# Answer
# CJam, 17 15

```
q5*~W*&/\,/fb:+

```

Works if there is a trailing newline in the input.

A more obvious version for those who don't know `x & -x`:

```
q5*~(~&/\,/fb:+

```

### How it works

```
q5*~               " Push 5 times the input as numbers. ";
W*&/               " Calculate n / (n & -n). (Or n / (n & ~(n-1))) ";
\,                 " List the digits. ";
/                  " Split into chunks. ";
fb:+               " Sum in the correct base. ";

```
> 4 votes

# Answer
## Python, ~~82~~ 78

```
def f(b):G=b^b&b-1;return sum(b**(b/G-i-1)*(G*i+(G-1)*b/2)for i in range(b/G))

```

**Huh?**

* The number of digit groups that the subdivison yields, ***G***, is simply the greatest power of two that divides the number of digits (i.e. the base), ***b***. It's given by *G = b ^ (b & (b - 1))*, where *^* is bitwise-XOR. If you're familiar with the fact that *n* is a power of two iff *n & (n - 1) = 0* then it should be pretty easy to see why. Otherwise, work out a few cases (in binary) and it'll become clear.
* The number of digits per group, ***g***, is simply *b / G*.
* The first digit group, *012...(g-1)*, as a number in base *b*, is .
* The next group, *g(g+1)...(2g-1)*, as a number in base *b*, is the sum .
* More generally, the *n*-th group (zero-based), as a number in base *b*, ***an***, is .
* Recall that there are *G* groups, hence the sum of all groups is
which is what the program calculates.
> 11 votes

# Answer
# Haskell, ~~74~~ ~~69~~ 55

```
f n=sum[(n-x)*n^mod(x-1)(until odd(`div`2)n)|x<-[1..n]]

```

examples:

```
*Main> map f [2..15]
[1,5,6,194,145,22875,28,6053444,58023,2853116705,2882,2103299351334,58008613,2234152501943159]

```
> 2 votes

# Answer
# CJam (snapshot), 19 bytes

```
li__,\mf2m1+:*/fb:+

```

Note that the latest stable release (0.6.2) has a bug that can cause `mf` to return Integers instead of Longs. Quite paradoxically, this can be circumvented by casting to integer (`:i`).

To run this with CJam 0.6.2 (e.g., with the online interpreter), you have to use the following code:

```
li__,\mf:i2m1+:*/fb:+

```

Alternatively, you can download and build the latest snapshot by executing the following commands:

```
hg clone http://hg.code.sf.net/p/cjam/code cjam-code
cd cjam-code/
ant

```

### Test cases

```
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 3; echo
5
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 4; echo
6
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 6; echo
145
$ cjam <(echo 'li__,\mf2m1+:*/fb:+') <<< 11; echo
2853116705

```

### How it works

```
li                     " N := int(input()) ";
   _,                  " A := [ 0 1 ... (N - 1) ] ";
  _  \mf               " F := factorize(N) ";
        2m1+           " F := F - [2] + [1] ";
            :*         " L := product(F) ";
              /        " A := A.split(L) ";
               fb      " A := { base(I, N) : I ∊ A } ";
                 :+    " R := sum(A) ";

```
> 2 votes

# Answer
## CJam, 41 bytes

This is basically Ell's solution in CJam:

```
ri:B__(^2/):G/,{_BBG/@-(#G@*G(B2/*+*}/]:+

```

Try it online here

---

**My original submission:**

Doesn't work correctly for base 11 and above

```
ri:B2%BB{2/_2%!}g?B,s/:i:+AbBb

```

Will try to see if I can get it to work for base 11 and above, without increasing the size much.
> 1 votes

# Answer
## Mathematica, 114 bytes (or 72 bytes)

Hm, this got longer than I thought:

```
f@b_:=Tr[#~FromDigits~b&/@({Range@b-1}//.{a___,x_List,c___}/;EvenQ[l=Length@x]:>Join@@{{a},Partition[x,l/2],{c}})]

```

And ungolfed:

```
f@b_ := Tr[#~FromDigits~
     b & /@ ({Range@b - 1} //. {a___, x_List, c___} /;
       EvenQ[l = Length@x] :> Join @@ {{a}, Partition[x, l/2], {c}})]

```

Alternatively, if I just port Ell's nifty formula, it's 72 bytes:

```
f=Sum[#^(#/g-i-1)(g*i+(g-1)#/2),{i,0,#/(g=Floor[BitXor[#,#-1]/2+1])-1}]&

```
> 1 votes

# Answer
# J - 22 char

Function taking a single argument (call it `y` for the purposes of this golf) on the right.

```
+/@(#.i.]\~-%2^0{1&q:)

```

First we use `1&q:` to get the number of times `y` is divisible by 2, and then divide `-y` by 2 that many times. This gives us the negative of the width that we need to split things into, which is perfect, because `]\` will take overlapping pieces if the argument is positive, and non-overlapping if it's negative.

So then we split up `i.y`—the integers from 0 to `y-1`—into vectors of these widths, and use `#.` to convert them from base `y` to base 10. Finally, `+/` does the summing, and we're done.

Examples: (input at the J REPL is indented, output is flush left)

```
   +/@(#.i.]\~-%2^0{1&q:) 6
145
   f =: +/@(#.i.]\~-%2^0{1&q:)
   f 11
2853116705
   (,: f every) 1+i.14   NB. make a little table for 1 to 14
1 2 3 4   5   6     7  8       9    10         11   12            13       14
0 1 5 6 194 145 22875 28 6053444 58023 2853116705 2882 2103299351334 58008613
   f every 20 30 40x     NB. x for extended precision
5088086 7455971889417360285373 368128332
   ":"0 f every 60 240 360 480 720 960x   NB. ":"0 essentially means "align left"
717771619660116058603849466
3802413838066881388759839358554647144
37922443403157662566333312695986004014731504774215618040741346803890772359370271801118861585493594866582351161148652
256956662280637244030391695293099315292368
2855150453577666748223324970642938808770913717928692581430408703547858603387919699948659399838672549766810262282841452256553202264
17093564446058417577302441219081667908764017056

```
> 1 votes

# Answer
## JavaScript, ~~99~~ 89 bytes

```
function f(n){m=n/(n&-n);for(r=s=i=0;;){if(!(i%m)){r+=s;s=0;if(i==n)return r;}s=s*n+i++}}

```

or

```
function g(n){c=n&-n;for(s=i=0;i<n/c;++i)s+=Math.pow(n,n/c-i-1)*(c*i+(c-1)*n/2);return s}

```

The second function is similar to Ell's one. The first one uses a more traditional approach. Both are 89 characters in size.

Try here: http://jsfiddle.net/wndv1zz8/1/
> 0 votes

# Answer
# Jelly, ~~10~~ 9 bytes

```
Ḷœs&N$ðḅS

```

Try it online!

Essentially just a translation of jimmy23013's CJam answer, except using `n & -n` directly as the number of chunks to split into.

```
        S    The sum of
Ḷ            the range from 0 to the input minus one
 œs          split into sublists of length equal to
   &         the input bitwise AND
    N$       its negation
      ðḅ     with each sublist converted from base-the-link's-argument.

```

(The `ð` has nothing to do with mapping:  just vectorizes over its left argument, and `ð` is there to separate `ḅS` off as a new dyadic chain which takes the result of `ḶœsÇ` as its left argument and the argument to the main link as its right argument.)
> 0 votes

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


title: Emulate a 7-segment display

text:
# Question
Title: Emulate a 7-segment display
# Task

The task is to display any of the 128 possible states of a 7-segment display.

Your program should accept a string of 7 characters ("bits") that are either `0` or `1`. First bit of input corresponds to segment A of the following illustration, the second to B, etc (ignore `dp`):

How you represent the display is up to you -- a single Unicode or ASCII symbol, ASCII art, grafically, or whatever you can come up with. However, each input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

# Rules

* Codegolf
* As I said, any kind of output is allowed, but it would be nice if you specified it.
* Input can be stdin or command line argument.

# Examples

### Input

```
1101101

```

### Output

As ASCII/Unicode:
```
2

```
Different kinds of ASCII art (I'm not too good at this)
```
 _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---

```

# Answer
## J (51)

```
1 2 1#"1[5 3$' #'{~,|:>0;(88707#:~7#7){>".&.>1!:1[1

```

output:

```
1101101
 ##
   #
 ##
#
 ##

```
> 5 votes

# Answer
## C, 106

**Size is 74 chars if allowed to rename program "W00WG5WW1GW66WG4WW2GW33WG"**

```
main(int i,char**s){
    for(s[0]="W00WG5WW1GW66WG4WW2GW33WG";i=*s[0]++;putchar(s[1][i&7]-49?i==71?10:32:42));
}

```

running:

```
./a.out 1101101
 **
   *
 **
*
 **

```

notes:

'W' and 'G' (0x47 and 0x57) are chosen such that the value & 7 = 7, i.e they safely index the null character that terminates the input string.
> 16 votes

# Answer
## Brainfuck - 224

```
++++++++++[>+>+++<<-]
>>++>,>,>,>,>,>,>,
<<<<<<<.
>[<+.->-]<<.
>>
>>>>>[<<<<<+<+>>>>>>-]<<<<<<.>[<->-]<.>>[<<+.->>-]<<<.>.
>>>>>>>[<<<<<<<+.->>>>>>>-]<<<<<<<<.
>>>>>>[<<<<+<+>>>>>-]<<<<<.>[<->-]<.
>>>[<<<+.->>>-]<<<<.>.
>>>>[<<<<+.>]

```

Prints using Exlamation points:

```
 !
! !
 !
! !
 !

```

Not the most readable, but not too horrible either.

Surprised at how close this is to not being last place.
> 15 votes

# Answer
# Postscript 121 107

```
1 12 moveto{}5 0{0 -5 rmoveto}0 5 0 5 -5 0 0 -5 0 -5 5 0
n{49 eq{rlineto}{rmoveto}ifelse exec}forall stroke

```

requires `n` to be defined as the string to process so invoke like

```
gs -g7x14 -sn=1101101 lcd.ps

```

to get

the complete set is
> 13 votes

# Answer
## Mathematica: ~~135~~ ~~129~~ 118, image display

```
Image[MorphologicalComponents@Import@"http://goo.gl/j3elE" /.
      Thread[Range@7 -> IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &

```

spaces added "for clarity"

**Edit**

For those picky fellow site users: Without using an external mask:

```
Image[MorphologicalComponents[ColorNegate@Rasterize@8, CornerNeighbors -> False] /.
    Thread[Range@7 ->IntegerDigits[#, 2, 7][[{7, 2, 6, 1, 3, 5, 4}]]]] &

```
> 11 votes

# Answer
## APL, ~~58~~ 55

```
' _|'[1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]]

```

Example input:

```
1101101

```

Output:

```
 _
 _|
|_

```

---

`⍞='1'` takes the input as a character array and converts it to a numeric array.

`1 2 2 1 2 2 1×⍞='1'` converts that array to: `0` for blank, `1` for `_`, `2` for `|`

`(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` assign that array to variable `x` and reorder to represent segments F, G, B, E, D, C

`0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` concatenates a blank, segment A and another blank to the front

`3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` reshape to a 3x3 matrix

`1+3 3⍴0,x[1],0,(x←1 2 2 1 2 2 1×⍞='1')[6 7 2 5 4 3]` converts to 1-based indexing

Finally uses the string `' _|'` to convert indicies into characters

---

## Edit

```
' _|'[1+3 3⍴(0,1 2 2 1 2 2 1×⍞='1')[1 2 1 7 8 3 6 5 4]]

```

Shaved off 3 chars by concatenating a `0` to front the array and using duplicate indicies, preventing a variable assignment
> 10 votes

# Answer
## PHP 66 bytes

```
<?for(;11>$i;)echo++$i&3?$argv[1][md5(¡æyÚ.$i)%8]?$i&1?~ƒ:_:~ß:~õ;

```

A slight improvement using an `md5` magic formula, but requires 3 additional binary bytes:
`¡`, `æ`, and `Ú` are characters 161, 230, and 218 respectively. It should work as is if copied directly, and saved as an ANSI format.

---

## PHP 73 (70) bytes

```
<?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?'|':_:' ':'
';

```

If you'll allow me three binary characters, this can be reduced to **70 bytes**:

```
<?for($s=327638584;3<$s;)echo++$i&3?$argv[1][7&$s/=8]?$i&1?~ƒ:_:~ß:~õ;

```

where `ƒ`, `ß`, and `õ` are characters 131, 223, and 245 respectively.

Receives input as a command line argument. Sample usage:

```
$ php seven-seg.php 1101101
 _
 _|
|_

$ php seven-seg.php 0111011

|_|
 _|

```
> 9 votes

# Answer
## JavaScript + jQuery + HTML + CSS (~~210~~ 201)

This solution uses CSS sprites and the image provided as an example:

### HTML (3)

```
<a>

```

### CSS (~~82~~ 71)

Thanks to xem for the "*background:url*" trick:

```
a{background:url(//bit.ly/VesRKL);width:13px;height:23px;display:block}

```

### JavaScript (125 after removing newlines added here for readability)

```
i=prompt();
x=-parseInt(i.substr(0,3),2)*23;
y=-parseInt(i.substr(3),2)*13.75;
$('a').css('background-position',y+'px '+x+'px');

```

---

Online test: http://jsfiddle.net/zhqJq/3/
> 7 votes

# Answer
# R (65 chars):

```
plot((3^(1i*1.5:-4.5)*(1:7!=7)),col=strsplit(readline(),'')[[1]])

```

Relies on some loose approximations for some transcendental nuumbers ...
> 6 votes

# Answer
# Python 2 - 65

```
s=raw_input()+'0\n'
for i in`0x623C239E38D2EAA1`:print s[int(i)],

```

Example:

```
echo 1101101|python2 7seg.py
0 1 0
0 0 1
0 1 0
1 0 0
0 1 0

```
> 6 votes

# Answer
**PostScript: 53 binary, 87 ASCII 52 binary, 86 ASCII**

Hexdump of the program using binary tokens:

```
$ hexdump -C lcd_binary.ps
00000000  28 34 34 30 34 30 38 30  34 30 34 30 30 30 30 34  |(440408040400004|
00000010  30 34 30 34 34 34 34 34  38 34 38 30 38 29 7b 7d  |0404444484808){}|
00000020  92 49 6e 7b 92 70 31 92  04 92 96 92 6b 92 63 92  |.In{.p1.....k.c.|
00000030  a7 7d 92 49                                       |.}.I|
00000034

```

Download this file to try it out.

Using ASCII tokens:

```
(4404080404000040404444484808){}forall
n{not 1 and setgray moveto lineto stroke}forall

```

First `forall` loop puts all required coordinates on the stack. The coordinates are stored in a string to minimize required space. The coordinates are in reverse order, i.e. the last 4 chars are for segment A. We draw a line from `(0,8)` to `(4,8)` for this segment (actually, we have to add 48 to all coordinates, because `forall` puts all ASCII codes on the stack).

The second `forall` loops through all the `0`s and `1`s in the input string and turns them into a gray value. `0`s are drawn white (gray value 1) and `1`s are drawn black (gray value 0). Then we use the coordinates that the first `forall` loop left on the stack to draw the lines.

Invoke the program using Ghostscript, just like Geoff Reedy's:

```
gs -sn=1101101 lcd.ps

```

This displays:
> 5 votes

# Answer
## APL ~~101 86 73~~ 69

```
m←45⍴' '⋄m[¯40+⎕av⍳(⍎∊3/' ',¨⍕⍞)/')*+16;EJOQRSAFK-27=>?']←'⎕'⋄9 5⍴m

```

Input is from the screen via ⍞

```
1101101

```

Which produces a 9x5 character matrix composed of blanks and ⎕ as follows:

```
 ⎕⎕⎕
     ⎕
     ⎕
     ⎕
 ⎕⎕⎕
⎕
⎕
⎕
 ⎕⎕⎕

```

The seven digit number is converted into a partition vector to select the ⎕ co-ordinates.
> 4 votes

# Answer
## Mathematica ~~112~~ ~~103~~ ~~100~~ ~~96~~ 88, using Graphs

```
HighlightGraph[z=GridGraph@{3,2},Pick[EdgeList[z][[{3,4,1,2,6,7,5}]],Characters@#,"1"]]&

```

```
Using it to show a calculator display

l = {7-> 7, 1-> 6, 0-> 63, 8-> 127, 9-> 111,3 -> 79, 5-> 109,  2-> 91, 4-> 102, 6-> 125};
GraphicsRow[
  HighlightGraph[z = GridGraph[{3,2}, EdgeStyle-> {White}, GraphHighlightStyle-> {"Thick"}],
    EdgeList[z][[{3, 4, 1, 2, 6, 7, 5}]][[IntegerDigits[#, 2, 7] Range@7]]] & /@
            (IntegerDigits[8736302] /. l)]

```
> 4 votes

# Answer
## Python (107)

Definitely more golfable.

```
a=map(int,raw_input())
for i in(0,6,3):print' .. '*a[i]+('\n'+' .'[a[5-i/6]]+'  '+' .'[a[1+i/6]])*(2*(i!=3))

```

Output:

```
1101101
 ..
   .
   .
 ..
.
.
 ..

```

Explanation:

```
a is a list of booleans extracted from the input.
When you multiply a string with a number, it will return the string repeated (number) times.
If that number happens to be zero, it returns an empty string.
i is iterated through 0 (pos A), 6 (pos G), and 3 (pos D).
' .. ' will print either section A, G, or D, depending on the value of i.
([string here])*(2*(i!=3)) will print [string here] twice only if i!=3.
Breaking down [string here]:
 - '\n' will print a newline for each repetition.
 - '  ' is the null space between horizontal sections.
 - ' .'[(bool)] will return either ' ' if (bool) is 0, and '.' if (bool) is 1.
 - 5-i/6 will return 5 if i=0 and 4 if i=6. a[5] is section F and a[4] is section E.
 - 1+i/6 will return 1 if i=0 and 2 if i=6. a[1] is section B and a[2] is section C.

```
> 3 votes

# Answer
# Python 2.7 (93 chars):

```
print (' {0}\n{5} {1}\n {6}\n{4} {2}\n {3}').format(*map(lambda x:int(x)and'*'or' ',raw_input()))

```

### Explanation:

With the stdin input, use a makeshift ternary operator to give `*` for true and a space for false. Take those values and plug them into a format statement that's in the format of the 7 digit display. It'd be at most 83 characters if the display worked like this:

```
 a
b c
 d
e f
 g

```

but the ordering makes it longer. Anyone have a way around this?

### Example:

```
$ ./7seg.py
111000

 *
  *

  *

$ ./7seg.py

1111111

 *
* *
 *
* *
 *

```
> 3 votes

# Answer
I thought we needed a lispy answer...

# Clojure, 159 chars

```
(print(apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec(read-line))[0 5 1 6 4 2 3])))" ")))))))

```

The above will run in the REPL and provide the correct answer. For example:

```
1111111
 o
o o
 o
o o
 o

```

Throwing numbers at it with small modifications:

```
(doseq [i ["1111110" "0110000" "1101101" "1111001" "0110011" "1011011" "1011111" "1110000" "1111111" "1111011"]]
(println (apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec i)[0 5 1 6 4 2 3])))" ")))))))
(println))

```

yields:

```
 o
o o

o o
 o

  o

  o

 o
  o
 o
o
 o

 o
  o
 o
  o
 o

o o
 o
  o

 o
o
 o
  o
 o

 o
o
 o
o o
 o

 o
  o

  o

 o
o o
 o
o o
 o

 o
o o
 o
  o
 o

nil

```

Not easy to read, but they're there!
> 3 votes

# Answer
## Javascript 123

```
s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ─│'[~i%2&(A=+s[+m[~~(i/2)]])+(A&+'110'[i%3])];console.log(o)

```

I can bring the character count lower (101) if we use only one character for the "on" state, but it is less legible:

```
s=prompt(i=o='');for(m=' 0516423';i++<15;i%3==0?o+='\n':1)o+=' ■'[~i%2&s[+m[~~(i/2)]]];console.log(o)

```
> 3 votes

# Answer
# Postscript 136

Not winner, but a different approach.

```
15 string exch{1 and 255 mul}forall
[7 3 9 13 11 5 1]{count 1 sub index 3 1 roll exch put}forall
3 5 8[.02 0 0 .05 0 0]{}image showpage

```

Expects the input string to be on the stack:

```
$ echo '(1101101)'|cat - 7seg.ps |gs -sDEVICE=png16 -sOutputFile=6c.png -

```

This one's even worse. **294** to make a "binary" bitmap. I took me a while to remember that each row is padded to an even byte. So a 3x5 bitmap is five bytes with the 3 msb bits significant.

```
2#1101101
(12345)exch
2 copy 64 and 0 exch put %A
2 copy 2 and 6 bitshift 2 index 32 and or 1 exch put %F B
2 copy 1 and 6 bitshift 2 exch put %G
2 copy 4 and 5 bitshift 2 index 16 and 1 bitshift or 3 exch put %E C
2 copy 8 and 3 bitshift 4 exch put
pop
3 5 1[.02 0 0 .02 0 0]{}image showpage

```

Output is just as ugly as the other one. :(

Alright here's one that looks good. **190**

Edit: It was upside-down and backwards. Fixed now.

```
(1101101)
{neg 49 add 255 mul
1 string dup 0 4 3 roll put}forall
(\377){@/g/f/e/d/c/b/a}{exch def}forall
@ a a @
b @ @ f
b @ @ f
@ g g @
c @ @ e
c @ @ e
@ d d @
4 7 8[.01 0 0 .01 0 0]{}image showpage

```
> 2 votes

# Answer
# Mathematica 264

Getting the output to look right required many bytes, so no cigar this time. But here's the verbose (264 chars) code anyway.

```
{a, b, c, d, e, g} = {{-1, 5}, {1, 5}, {1, 3}, {1, 1}, {-1, 1}, {-1, 3}};
f@n_ := Graphics[{Yellow, Thickness[.1], CapForm["Round"],
   Line /@ {{g, c}, {g, a}, {g, e}, {e, d}, {d, c}, {c, b}, {b, a}}[[Flatten@
   Position[IntegerDigits[n, 2, 7], 1]]]},
   Background -> Blue, PlotRange -> {{-1, 1}, {1, 5}}, PlotRangePadding -> 1]

```

The complete set of characters:

```
GraphicsGrid[Partition[Table[f[p], {p, 0, 128}], 16]]

```

The digits:

```
{f[63], f[6], f[91], f[79], f[102], f[109], f[125], f[7], f[127], f[111]}

```
> 2 votes

# Answer
**PHP - 155 characters**

```
<?php
$y=array("   \n"," - \n","   \n","  |\n","|  \n","| |\n"); $x = $argv[1]; echo $y[$x[0]].$y[2*$x[6]+$x[2]+2].$y[$x[7]].$y[2*$x[5]+$x[3]+2].$y[$x[4]];

```

it would be 150 characters if we use php 5.4 type array declaration, but i dont have that installed on my laptop so couldn't test it.

**Sample out puts.**

**Explanation:**

First i divided the 7 segment display to Five rows and 3 columns. With 1st, 3rd and 5th row havimg '-' in the middle column, and space otherwise.

The 2nd and 4th row has a pipe '|' character in the first and last column. Now the presence of these character should be guided by the input values.

I created a lookup table, which is basically two lookup table. First one for the calculation of values for 1st, 3rd and 5th row. And another one at offset 2 ( 3rd item ) for calculation of rows 2nd and 4th.
> 2 votes

# Answer
# Java - 204 characters

```
class A{public static void main(String[]a){char[]c=new char[7];for(int i=0;i<7;i++)c[i]=a[0].charAt(i)==49?i%3==0?95:'|'):32;System.out.printf(" %c %n%c%c%c%n%c%c%c",c[0],c[5],c[6],c[1],c[4],c[3],c[2]);}}

```

Sample output:

```
 _
 _|
|_

```

Formatted properly:

```
class A {
    public static void main(String[] a) {
        char[] c = new char[7];
        for (int i = 0; i < 7; i++)
            c[i] = a[0].charAt(i) == 49 ? (i % 3 == 0 ? 95 : '|') : 32;
        System.out.printf(" %c %n%c%c%c%n%c%c%c", c[0], c[5], c[6], c[1], c[4], c[3], c[2]);
    }
}

```

Really wish I could avoid that for loop, but I tried a few other things and they were all longer. There's probably a better way to do this, but this is my first attempt at code golf. (And Java's like the worst language for it, which is why I thought it would be interesting.) Even Brainfuck has me beat, but at least my output looks nicer.

EDIT: can get rid of "public" on class, saves me 7 chars!

And thanks, daniero, for showing me printf! (18 chars saved)

Rewrote the output format, changed character literals to decimal, 12 chars saved.
> 2 votes

# Answer
## VBA - 263

It's ugly but it works, I think. I am having trouble viewing the proper bit order, so I'm inferring from others' answers. Even if that piece is wrong, the code length should remain the same.

```
Sub d(b)
Dim c(1 To 7)
For a=1 To 7
c(a)=Mid(b,a,1)
Next
x=" - "
y="|"
z=" "
w="   "
v=vbCr
MsgBox IIf(c(1)=1,x,w) & v & IIf(c(6)=1,y,z) & z & IIf(c(2)=1,y,z) & v & IIf(c(7)=1,x,w) & v & IIf(c(5)=1,y,z) & z & IIf(c(3)=1,y,z) & v & IIf(c(4)=1,x,w)End Sub

```
> 1 votes

# Answer
**VBScript - 178 characters**

```
m=Split("2 7 11 10 9 5 6")
s=" _ "&vbCr&"|_|"&vbCr&"|_|"
For x=1 To 7
If Mid(WScript.Arguments.Item(0),x,1)=0 Then r=m(x-1):s=Left(s,r-1)&" "&Right(s,Len(s)-r)
Next
MsgBox s

```
> 1 votes

# Answer
# VBA, 188 characters

Note that the one has to *type* 188 characters if only including mandatory whitespace -- the IDE expands it out when you copy it into the VBA editor.

```
Sub f(i)
Dim c() As Byte
m=Split("1 6 10 9 8 4 5")
c=StrConv(" _  |_| |_|",128)
c(3)=10
c(7)=10
For x=1 To 7
If Mid(i,x,1) = 0 Then c(m(x-1))=32
Next
MsgBox StrConv(c,64)
End Sub

```

Sadly, VBScript doesn't have a strongly typed Byte array, or that one could be much shorter using this method.
> 1 votes

# Answer
# CJam - 29

```
l0N]s7078571876784728737Ab\f=

```

CJam is a new language I am developing, similar to GolfScript - http://sf.net/p/cjam. Here is the explanation:

`l` reads a line from the input
`0` is the number 0
`N` is a variable preinitialized to the newline string
`]` gathers the elements on the stack into an array
`s` converts a value (the array) to string, thus appending a zero and a newline to the given input
`7078571876784728737` is a number (the same number I used in python, but it was in hex there)
`A` is a variable preinitialized to 10
`b` does a base conversion, generating the array \[7 0 7 8 ... 3 7\]
`\` swaps the last two values on the stack
`f=` applies the `=` operator (here, indexed array access) on the input string (plus zero and newline) and each number 7, 0, 7, ...
The index 7 corresponds to the appended zero, and 8 corresponds to the appended newline.

My python solution does exactly the same thing (except the digit separation is done via string conversion)
> 1 votes

# Answer
# Javascript (ECMAScript 2016) - 108 bytes

```
console.log(([a,b,c,d,e,f,g]=[...prompt()].map((x,i)=>+x?'_||'[i%3]:' '),` ${a}
${f}${g}${b}
${e}${d}${c}`))

```

This *probably* can be golfed further, but I can't think of anything.
> 1 votes

# Answer
# JavaScript, 148 bytes

```
e=>(e[0]==1?" #\n":"\n")+(e[5]==1?"#":" ")+(e[1]==1?" #\n":"\n")+(e[6]==1?" #\n":"\n")+(e[4]==1?"#":" ")+(e[2]==1?" #\n":"\n")+(e[3]==1?" #\n":"\n")

```

Try it online! <sub>(Footer is Node.js to read `.input.tio`)</sub>

Accepts input of ABCDEFG in binary flags and returns:

```
 #
# #
 #
# #
 #

```
> 1 votes

# Answer
# SmileBASIC, 136 bytes

```
DIM A[7,2]COPY A,@L@L?DATA.,1,1,3,4,3,6,1,4,0,1,0,3,1INPUT X$FOR I=0TO 6M=I MOD 3GBOX A[I,1],A[I,0],A[I,1]+!M,A[I,0]+!!M,-VAL(X$[I])NEXT

```

Output is graphical.
> 0 votes

# Answer
# PHP 5.6, 65 bytes plain ASCII

```
for(;$p++<9;)echo$argn[_707561432[$p]]?"||_"[$p%3]:" ","\n"[$p%3];

```

or, without a trailing linebreak, but with some bitwise fun:

```
for(;$p++<11;)echo$argn[_70785618432[$p]]?L|Sx[$p&1]:a^kAAA[$p&3];

```

Run as pipe with `-nR` or try them online.

**breakdown 1**

```
for(;$p++<9;)echo           # loop through positions
    $argn[_707561432[$p]]   # map position to input bit
        ?"||_"[$p%3]            # if set: underscore in 2nd column, pipe symbol else
        :" "                    # else space
    ,"\n"[$p%3]             # add newline every 3 columns
;

```

**breakdown 2**

```
for(;$p++<11;)echo          # loop through positions
    $argn[_70785618432[$p]] # map position to input bit (bit 8 for EOL, never set)
        ?L|Sx[$p&1]             # if set: underscore in the middle, pipe symbol else
        :a^kAAA[$p&3]           # else: newline in 4th column, space else

```
> 0 votes

# Answer
# 05AB1E, 4 bytes

```
C₄+ç

```

Try it online or verify all possible inputs.

See the *verify all possible inputs* link above to see the mapping used for each input.

**Explanation:**

This abuses the rules where it states:

> How you represent the display is up to you -- **a single Unicode or ASCII symbol**, ASCII art, grafically, or whatever you can come up with. However, **each input must have it's own distinct output.**

```
C       # Convert the (implicit) input from binary to integer
 ₄+     # Increase it by 1000
   ç    # Convert it to a unicode character with this value (and output implicitly)

```

---

Alternative more in the spirit of the challenge using the output-format:

```
 -
| |
 -
| |
 -

```

### 38 bytes:

```
Σ•L7×•Nè}εi" -| | "14∍2ôNèëðº]J24S5∍£»

```

Can definitely be golfed..

Try it online or verify all possible inputs.

**Explanation:**

```
Σ       }          # Sort the (implicit) input-digits by:
 •L7×•Nè           #  The digit at the same index in the compressed integer 1367524
                   #   i.e. "1101101" → ["1","0","1","1","1","0","1"]
ε                  # Then map each digit to:
 i                 #  If it's a 1:
  " -| | "         #   Push string " -| | "
          14∍      #   Lengthen it to size 14: " -| |  -| |  -"
             2ô    #   Split it into parts of 2: [" -","| ","| "," -","| ","| "," -"]
               Nè  #   Index into it
 ë                 #  Else (it's a 0):
  ðº               #   Push "  " (two spaces) instead
    ]              # Close both the if-else and map
                   #  i.e. ["1","0","1","1","1","0","1"]
                   #   → [" -","  ","| "," -","| ","  "," -"]
J                  # Join everything together to a single string
                   #  i.e. [" -","  ","| "," -","| ","  "," -"] → " -  |  -|    -"
 24S               # Push [2,4]
    5∍             # Lengthened to size 5: [2,4,2,4,2]
      £            # Split the string into parts of that size
                   #  i.e. " -  |  -|    -" → [" -","  | "," -","|   "," -"]
       »           # Join by newlines (and output implicitly)
                   #  i.e. [" -","  | "," -","|   "," -"] → " -\n  | \n -\n|   \n -"

```

See this 05AB1E tip of mine (*section How to compress large integers?*) to understand why `•L7×•` is `1367524`.
> 0 votes

---
Tags: code-golf
---