title: A, Buzz, C, D, E, Fizz, G

text:
# Question
Title: A, Buzz, C, D, E, Fizz, G
A simple FizzBuzz using strings.

**Given**

* 1 word or phrase (string)
* 2 unique characters

**Output**

The word or phrase with each occurrence of the first character replaced with fizz and each of the second character replaced with buzz

**Rules**

* The first letter in both Fizz and Buzz must remain capitalized
* For the rest of the words fizz and buzz, you must match the case of the replaced character (if no case then keep lowercase)
* If given characters are not in the phrase, output the original phrase

**Test Cases**

```
Given: Hello, h, l
Output: FIZZeBuzzBuzzo

Given: test, a, b
Output: test

Given: PCG rocks!,  , !
PCGFizzrocksBuzz

Given: This
Is
SPARTA!,
, S
Output: ThiBuzzFizzIBuzzFizzBUZZPARTA!

Given: FizzBuzz, a, b
Output: FizzBUZZuzz

```

This is code-golf so the shortest code, in bytes, wins!

**Note**

Technically handling the newline case (This Is SPARTA!) is a part of the challenge. However, I will not void an answer for not including it, as it is very challenging or even impossible in some languages.

# Answer
> 2 votes
# Jelly, 34 bytes

```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦

```

**Try it online!**

### How?

```
Œl=€⁹Œl¤ȧ€"“¡Ṭ4“Ụp»o"/ȯ"Œu⁹Œln$T¤¦ - Main link: characters, string
Œl                                 - lowercase the characters
       ¤                           - nilad followed by link(s) as a nilad:
    ⁹                              -     right argument, the string
     Œl                            -     lowercase
  =€                               - equals (vectorises) for €ach (a list of 2 lists that identify the indexes of the string matching the characters regardless of case)
           “¡Ṭ4“Ụp»                - dictionary strings ["Fizz", "Buzz"]
          "                        - zip with
        ȧ€                         -     logical and (non-vectorising) for €ach (replace the 1s with the words)
                     /             - reduce with:
                    "              -     zip with:
                   o               -         logical or (vectorises) (make one list of zeros and the words)
                                   - implicit right argument, string
                       "           - zip with:
                      ȯ            -     logical or (non-vectorising) (replace the zeros with the original characters from the string)
                                 ¦ - apply...
                        Œu         -     uppercase
                                   - ...to the indexes (the words at indexes):
                                ¤  -     nilad followed by link(s) as a nilad:
                          ⁹        -         right argument, the string
                              $    -         last two links as a monad (i.e. the string on both sides):
                           Œl      -             lowercase
                             n     -             not equals (vectorises)
                               T   -         truthy indexes (the indexes of the capital letters in the string)

```

# Answer
> 6 votes
## Python 3, ~~180~~ ~~174~~ ~~168~~ ~~160~~ 152 bytes

```
from sys import*
J=''.join
L=str.lower
s,a,b=J(stdin).split(', ')
print(J('FBFBiuIUzzZZzzZZ'[L(k)==L(b)::2][k!=L(k)::2]*(L(k)in L(a+b))or k for k in s))

```

This is just a more golfed version of Stephen's answer, in Python 3. This chips away 42% of his bytes. Python 2 would save one byte on the print, but such is the price of progress. This handles newlines properly.

Thanks to Blckknight for saving 8 bytes on input.

# Answer
> 4 votes
# Python, 109 bytes

```
lambda s,w:"".join([c,"Fizz","Buzz","BUZZ","FIZZ"][-~w.lower().find(c.lower())*-~(-2*c.isupper())]for c in s)

```

Try it online!

---

Takes the two characters as a single string

*Edit: Added testcase to TIO link, newline works too*

# Answer
> 2 votes
# Bash 4.4 + GNU sed, ~~70~~ ~~228~~ ~~222~~ 227 bytes

```
IFS=;alias e=echo;K=`sed $([[ $2 != '
' ]]&&e "s/${2,}/Fizz/g;s/${2^}/FIZZ/g"||:)$([[ $3 != '
' ]]&&e ";s/${3,}/Buzz/g;s/${3^}/BUZZ/g"||:)<<<"$1"`;[[ $2 = '
'||$3 = '
' ]]&&e ${K//$'\n'/`[[ $2 = '
' ]]&&e Fizz||e Buzz`}||e "$K"

```

Apparently `alias e=echo` throws an error if referenced in Bash 4.3 or below, the version TIO is apparently using. Therefore, the longer and equivalent Bash 4.3 code is given in the below TIO test suite for the sake of testing. This passes all of the test cases, so that is nice.

Try it online!

# Answer
> 2 votes
# Python 2, 271, 261 bytes

```
import fileinput as f
a=''
for m in f.input():a+=m
a=a.split(', ')
l=L=list(a[0])
for i in range(0,len(a[0])):
 j,k=l[i].lower(),l[i].istitle()
 if j==a[1].lower():
  L[i]='FIZZ'if k else'Fizz'
 elif j==a[2].lower():
  L[i]='BUZZ'if k else'Buzz'
print''.join(L)

```

Try it online!

Wow this one was a doozie! It turns out python won't accept multi-line inputs so `fileinput` must be used.

edit: should pass all cases now :)

# Answer
> 2 votes
# MATLAB/Octave, ~~106~~ ~~102~~ 111 bytes

```
@(a,b,c)regexprep(a,num2cell([lower([b c]) upper([b c]) '1234']),{'2','4','1','3','FIZZ','Fizz','BUZZ','Buzz'})

```

This could probably be optimised further.

It uses a simple Regex replacement. However an intermediate step is required by replacing the input characters with numbers first. This is so that if the second input replace letter was contained in `Fizz` that the `Fizz` doesn't then get replaced when the next regex is performed.

This of course assumes there are no numbers in the input. However given the question says the input is a word or phrase I feel that this is an acceptable assumption.

The code will handle new lines in the input correctly.

You can Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 92 bytes

Takes input as a string and an array of two characters. Supports newlines.

```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s

```

### Test cases

```
f=(s,[a,b],r='Fizz')=>a?f(s.replace(RegExp(a,'gi'),m=>m<'a'?r.toUpperCase():r),[b],'Buzz'):s

console.log(f("Hello", ['h', 'l']))
console.log(f("test", ['a', 'b']))
console.log(f("PCG rocks!", [' ', '!']))
console.log(f(`This
Is
SPARTA!`, [`
`, 'S']))
console.log(f("FizzBuzz", ['a', 'b']))
```

# Answer
> 2 votes
## GNU sed, 135 + 1(r flag) = 136 bytes

By default, a sed script is executed as many times as there are input lines. To handle multi-line input, I use a loop to append all possible remaining lines to the first, without starting a new cycle.

```
:r
$!N
$!br
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz:
s:^:,:
:
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:
s:,(.):\1,:
/,;.F/!t
s:,.*::

```

**Try it online!**

The replacement table used on line 4, needs to be in that exact order, i.e. 'Fizz' and 'Buzz' after their upper-case forms. This is because the sed regex `.*`, used during the table lookup, is greedy. If the current char needed to be replaced is not a letter (no case), then the lowercase string is needed (matched last).

Since sed has no data types, I use a character delimiter to iterate a string. It will mark my current position and in a loop I shift it from left to right. Fortunately, I can use `,` for this, since it is the input data delimiter.

**Explanation:**

```
:r                                                 # reading loop
$!N                                                # append next input line
$!br                                               # repeat till EOF
s:, (.), (.):;\u\1FIZZ;\l\1Fizz;\u\2BUZZ;\l\2Buzz: # create replacement table
s:^:,:                                             # append my string delimiter
:                                                  # main loop
s:,(.)(.*;\1)(...)(.):\3,\4\2\3\4:                 # apply char replacement, if any
s:,(.):\1,:                                        # shift delimiter to right
/,;.F/!t                                           # repeat till end of string
s:,.*::                                            # print only the final string

```

# Answer
> 1 votes
# Pyth - 25 bytes

```
sXzsrBQ1scL2rB"FizzBuzz"1

```

Test Suite.

# Answer
> 0 votes
# Haskell, 114 bytes

```
u=Data.Char.toUpper
p[f,b]x|f==u x="Fizz"|b==u x="Buzz"|2>1=[x]
q x y|u y<y=x|2>1=u<$>x
r x=concatMap$q=<<p(u<$>x)

```

`r` takes the fizz and buzz characters as a 2 element list as the first argument, and the input string as the second argument. Newlines and unicode should be handled appropriately, although the function is unfortunately not total (allowing for invalid inputs saved 5 bytes).

# Answer
> 0 votes
# Mathematica, 94 bytes

```
a=ToLowerCase;b=ToUpperCase;StringReplace@{a@#->"Fizz",b@#->"FIZZ",a@#2->"Buzz",b@#2->"BUZZ"}&

```

Anonymous function. Takes two strings as input and returns a function which takes a string as input and returns a string as output as output. It must be called in the format `prog["c1", "c2"]["s"]`, where `"s"` is the target string and `"c1"` and `"c2"` are the two characters. Could probably be golfed further.

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


# Question
Title: Compute the most efficient binary function
Today, we'll be computing the most efficient binary function. More specifically, we'll be computing the function which, when an expression is created from applying the function to the constant input 0 or its own output, can represent all positive integers with the shortest possible expressions, placing higher priority on the smaller integers.

This function is built as follows:

For each integer, starting at 1 and going upwards, choose the shortest expression which we have not yet assigned an output to, and make that integer the output of that expression. Ties in expression length will be broken by smaller left argument, and then by smaller right argument. Here's how it works:

* Initially, 1 is unassigned. The shortest unassigned expression is `f(0, 0)`, so we'll set that to 1.
* Now, 2 is unassigned. The shortest unassigned expressions are `f(f(0, 0), 0)` = `f(1, 0)` and `f(0, f(0, 0))` = `f(0, 1)`. Ties are broken towards smaller left argument, so `f(0, 1) = 2`.
* The shortest unassigned expression remaining is `f(f(0, 0), 0)` = `f(1, 0)`, so `f(1, 0) = 3`.
* Now, we're out of expressions with only 2`f`s and 3`0`s, so we'll have to add one more of each. Breaking ties by left argument, then right argument, we get `f(0, 2) = 4`, since `f(0, f(0, f(0, 0))) = f(0, f(0, 1)) = f(0, 2)`.
* Continuing, we have `f(0, 3) = 5`, `f(1, 1) = 6`, `f(2, 0) = 7`, `f(3, 0) = 8`, `f(0, 4) = 9`, ...

Here's a table I filled out for the first few values:

```
    0  1  2  3  4  5  6  7  8
 /---------------------------
0|  1  2  4  5  9 10 11 12 13
1|  3  6 14 15 37 38 39 40 41
2|  7 16 42 43
3|  8 17 44 45
4| 18 46
5| 19 47
6| 20 48
7| 21 49
8| 22 50

```

Another way to look at it is that each output has a size, equal to the sum of the sizes of its inputs plus one. The table is filled out in order of increasing size of output, ties broken by minimizing left input then right input.

Your challenge is, given two non-negative integers as input, compute and output the value of this function. This is code golf. Shortest solution, in bytes, wins. Standard loopholes are banned.

# Answer
# Haskell, 110 bytes

```
f q=head[i|let c=[(-1,0)]:[[(f a,f b)|n<-[0..k],a<-c!!n,b<-c!!(k-n)]|k<-[0..]],(p,i)<-zip(concat c)[0..],p==q]

```

The argument here is taken to be the tuple `(x,y)`. Pretty similar to the answer above, but the lookup list holds just the pairs of left and right indices instead of the trees.
> 6 votes

# Answer
Wow! I actually managed to make an efficient computation algorithm. I did not expect this at first. The solution is quite elegant. It repeatedly deduces more and more, then recurses all the way down to the base case of 0. In this answer the C(n) function denotes the Catalan numbers.

The crucial first step is acknowledging that there are C(0) = 1 values of length zero (namely 0 itself), C(1) = 1 values of length one (namely f(0, 0)), C(2) = 2 values of length two (f(0, f(0, 0)) and f(f(0, 0), 0)).

This means that if we're looking for the nth expression, and we find the biggest k such that C(0) + C(1) + ... + C(k) \<= n then we know that n has length k.

But now we can continue! Because the expression we look for is the n - C(0) - C(1) - ... - C(k) th expression in its length class.

Now we can use a similar trick to find the length of the left segment, and then the rank within that subsection. And then recurse on those ranks we found!

It found that f(5030, 3749) = 1542317211 in the blink of an eye.

# Python, noncompeting

```
def C(n):
    r = 1
    for i in range(n):
        r *= 2*n - i
        r //= i + 1
    return r//(n+1)

def unrank(n):
    if n == 0: return 0

    l = 0
    while C(l) <= n:
        n -= C(l)
        l += 1

    right_l = l - 1
    while right_l and n >= C(l - 1 - right_l) * C(right_l):
        n -= C(l - 1 - right_l) * C(right_l)
        right_l -= 1

    right_num = C(right_l)

    r_rank = n % right_num
    l_rank = n // right_num

    for sz in range(l - 1 - right_l): l_rank += C(sz)
    for sz in range(right_l): r_rank += C(sz)

    return (unrank(l_rank), unrank(r_rank))

def rank(e):
    if e == 0: return 0
    left, right = e

    l = str(e).count("(")
    left_l = str(left).count("(")
    right_l = str(right).count("(")
    right_num = C(right_l)

    n = sum(C(sz) for sz in range(l))
    n += sum(C(sz)*C(l - 1 - sz) for sz in range(left_l))

    n += (rank(left) - sum(C(sz) for sz in range(left_l))) * C(right_l)
    n += rank(right) - sum(C(sz) for sz in range(right_l))

    return n

def f(x, y):
    return rank((unrank(x), unrank(y)))

```

I'm fairly certain I'm doing a bunch of unnecessary computation and a lot of middle steps could be removed.
> 6 votes

# Answer
# Python 3, 154 bytes

```
b=lambda n:[(l,r)for k in range(1,n)for l in b(k)for r in b(n-k)]+[0]*(n<2)
def f(x,y):r=sum((b(n)for n in range(1,x+y+3)),[]);return r.index((r[x],r[y]))

```

It's not very fast nor very golfy, but it's a start.
> 5 votes

---
Tags: code-golf, integer, function
---


title: Hello World - but alphabetically

text:
# Question
Title: Hello World - but alphabetically
*This challenge sounds too simple to not already exist, so let me know if it is a duplicate.*

## The task

Print `Hello, world!`

## The rules

Your code has to be in "byte order". This means that every character / byte has a higher or equal byte value than the preceding character / byte.

Exceptions to this rule are the whitespace characters, which may occur anywhere.

The usual loopholes are not allowed.

**Edit**: Using built-in functions / constants resolving to `Hello, world!` is not allowed.

**Edit 2**: The output may be a(n anonymous) function returning the string, an expression resolving to the string, or any other way you think should be allowed.

### example

`HW` is valid: `0x48 (H) <= 0x57 (W)`
`print` is invalid: `0x72 (r) > 0x69 (i)`
but `PRint` is valid: `0x50 (P) <= 0x52 (R) <= 0x69 (i) <= 0x6e (n) <= 0x74 (t)`

## The scoring

This is so the score is the number of characters / bytes. The lower the score, the higher the ranking.

# Answer
> 15 votes
# WhiteSpace, 146 bytes

Since all whitespace may occur everywhere, this is is just the golfed Hello World program. Since whitespace doesn't show properly here, take the following program and replace all `.` by spaces, `>` by tabs and `;` by newlines.

```
...;..>>..>.>.;..>>>>;...>;...>>>;...>..;..>>.>..;..>>..>.>>;..>>>>>>>;...>..;...>;.;...>>>.;..>>...>>;;..;.;.;>.>;...>>.>.>>;>...>;..;.;;;..>;;;;

```

# Note

I didn't golf this, LukStorms did. His answer can be found here.

# Answer
> 15 votes
# Headsecks - ~~124~~ 82 chars

*Thanks to @MartinEnder for pointing me to a smaller hello-world!*

Headsecks looks to be the right language for the job, because its brainfuck except that it takes each character mod 8.

```
 +19AISYchpx£¨°»ÁËÐÞàèðøĀĈĐĘĦīİĸŀňŐŘŠŨųŻƀƈƐƘƠƪƲƺǁǏǒǟǣǫǴǸȃȈȐțȤȫȴȼɀɋɓɜɠɫɱɹʃʉʑʞʣʩʴʺ˂ˏ

```

You can try it by going here: https://repl.it/G2I5/1, then here: https://sange.fi/esoteric/brainfuck/impl/interp/i.html

# Answer
> 13 votes
# CJam, 784 bytes

```
"

"
"
"')`er~

```

Try it online!

Not winning anything with that byte count, but this was still fun to make.

**Explanation**

The first large string encodes `Hello, world!` using only whitespace. Each character is mapped to a tab, a space, and a number of linefeeds equal to its codepoint minus 32.

Next, the string is transliterated by replacing tabs with `'` and linefeeds with `)`. This results in many sequences of a literal space character followed by some number of increments. The string is eval'ed with `~`, pushing the spaces and incrementing them to proper characters.

The stack is implicitly output at the end of the program.

---
Tags: code-golf, restricted-source, hello-world
---


title: Zeroes in interval

text:
# Question
Title: Zeroes in interval
Your task is to write a function or program that takes two non-negative integers `i` and `k` (`i``k`), and figure out how many zeroes you'd write if you wrote all whole numbers from `i` to `k` (inclusive) in your base of choice on a piece of paper. Output this integer, the number of zeroes, to stdout or similar.

`-30%` if you also accept a third argument `b`, the integer base to write down the numbers in. At least two bases must be handled to achieve this bonus.

* You may accept the input in any base you like, and you may change the base between test cases.
* You may accept the arguments `i`, `k` and optionally `b` in any order you like.
* Answers must handle at least one base that is not unary.

Test cases (in base 10):

```
i k -> output
10 10 -> 1
0 27 -> 3
100 200 -> 22
0 500 -> 92

```

This is code-golf; fewest bytes win.

# Answer
> 17 votes
## Jelly, 1 byte

```
¬

```

This uses base `k+2`, in which case there's a single 0 iff `i` is 0. It takes two arguments, but applies the logical NOT to only the first one.

If we don't want to cheat:

### 7 bytes - 30% = 4.9

*-1.1 points by @Dennis*

```
rb⁵$¬SS

```

This gets the bonus.

```
             dyadic link:
r            inclusive range
 b⁵$           Convert all to base input.
    ¬          Vectorized logical NOT
     S         Sum up 0th digits, 1st digits, etc.
      S        Sum all values

```

# Answer
> 8 votes
# Python 2, 36 bytes

```
lambda a,b:`range(a,b+1)`.count('0')

```

Credit to **muddyfish** for the \`\` trick.

# Answer
> 6 votes
# 05AB1E, ~~3~~ 1 byte

Uses base `k+2` like the Jelly answer, Code:

```
_

```

Explanation:

```
_  # Logical NOT operator

```

**3 byte non-cheating version:**

Code:

```
Ÿ0¢

```

Explanation:

```
Ÿ    # Inclusive range
 0¢  # Count zeroes

```

---

The bonus gives me **3.5 bytes** due to a bug:

```
ŸB)0¢

```

Explanation:

```
Ÿ      # Inclusive range
 B     # Convert to base input
  )    # Wrap into an array (which should not be needed)
   0¢  # Count zeroes

```

Uses CP-1252 encoding.

# Answer
> 5 votes
# Japt, 3 bytes

```
+!U

```

Uses base `k+2`, as the Jelly answer. There is a zero iff `i==0`. Test it online!

### Better version, ~~10~~ 8 bytes

```
UòV ¬è'0

```

This one uses base 10. Test it online!

### Bonus version, ~~14~~ 12 bytes - 30% = 8.4

```
UòV msW ¬è'0

```

Sadly, with the golfing I did, the bonus is no longer worth it... Test it online!

### How it works

```
UòV msW ¬è'0   // Implicit: U = start int, V = end int, W = base
UòV            // Create the inclusive range [U..V].
    msW        // Map each item by turning it into a base-W string.
        ¬      // Join into a string.
         è'0   // Count the number of occurances of the string "0".

```

# Answer
> 5 votes
## ES6, ~~91~~ 86 - 30% = 60.2 bytes

```
(i,k,b=10)=>([...Array(k+1-i)].map((_,n)=>(i+n).toString(b))+'0').match(/0/g).length-1

```

Or save 3 (2.1) bytes if b doesn't need to default to 10.

Best non-bonus version I could do was 65 bytes:

```
(i,k)=>([...Array(k+1).keys()].slice(i)+'0').match(/0/g).length-1

```

Edit: Saved 5 bytes by using @edc65's zero-counting trick.

# Answer
> 4 votes
## Seriously, 10 bytes

```
'0,,u@xεjc

```

Explanation:

```
'0,,u@xεjc
'0,,u       push "0", i, k+1
     @x     swap i and k+1, range(i, k+1)
       εjc  join on empty string and count 0s

```

Try it online!

With bonus: 11.9 bytes

```
'0,,u@x,╗`╜@¡`Mεjc

```

Try it online!

Explanation:

```
'0,,u@x,╗`╜@¡`MΣc
'0,,u@x             push "0", range(i, k+1)
       ,╗           push b to register 0
         `   `M     map:
          ╜@¡         push b, push string of a written in base b
               Σc   sum (concat for strings), count 0s

```

# Answer
> 4 votes
# Ruby, 46 - 30% = 32.2 bytes

You could probably golf this more, but at least I get the 30% bonus!

```
->i,k,b{((i..k).map{|a|a.to_s b}*"").count ?0}

```

...or without the bonus (27 bytes.)

```
->i,k{([*i..k]*"").count ?0}

```

Tips are welcome, still learning this whole "Ruby" thing.

# Answer
> 3 votes
# CJam, ~~12~~ ~~10~~ 3 bytes

```
li!

```

This uses the shortcut @ThomasKwa does.

If this is not allowed, then here is a 10 byte answer.

```
q~),>s'0e=

```

Nice and short! Works like @Mego's Seriously answer.

Thanks @Dennis!

Had fun writing my first CJam answer!

Try it here!

# Answer
> 3 votes
# T-SQL, 394 Bytes (No bonus)

I figure *'why not*', right?

```
DECLARE @i INT, @k INT SET @i = 100 SET @k = 200  WITH g AS (SELECT @i AS n UNION ALL SELECT n+1 FROM g WHERE n+1<=@k ) SELECT LEN(n) AS c FROM (SELECT STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '') FROM g FOR XML PATH ('')) ,1,0,'') n ) a OPTION (maxrecursion 0)

```

And the friendly one:

```
-- CG!

DECLARE @i INT, @k INT
SET @i = 100
SET @k = 200

WITH g AS
(
    SELECT @i AS n
    UNION ALL
    SELECT n+1 FROM g WHERE n+1<=@k
)

SELECT LEN(n) AS c FROM
(
    SELECT
        STUFF((SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(n, 1, ''), 2, ''), 3, ''), 4, ''), 5, ''), 6, ''), 7, ''), 8, ''), 9, ''), ' ', '')
FROM g FOR XML PATH ('')) ,1,0,'') n
) a

OPTION (maxrecursion 0)

```

# Answer
> 2 votes
# Pyth, 6.3 bytes, with bonus (9 bytes - 30%)

```
/sjRQ}EE0

```

Explanation:

```
  jRQ     - [conv_base(Q, d) for d in V]
     }EE  - inclusive_range(eval(input), eval(input))
 s        - sum(^, [])
/       0 - ^.count(0)

```

Try it here

Or 7 bytes without the bonus:

```
/`}EE\0

```

Explanation:

```
  }EE   - inclusive_range(eval(input), eval(input))
 `      - repr(^)
/    \0 - ^.count("0")

```

Try it here

Or use a test suite

# Answer
> 2 votes
# Brachylog, 26 bytes

```
,{,.e?}?:1frcS:0xlI,Sl-I=.

```

Takes input as a list `[i,k]`.

### Explanation

```
,{    }?:1f                § Unify the output with a list of all inputs which verify the
                           § predicate between brackets {...} with output set as the input
                           § of the main predicate

  ,.e?                     § Unify the input with a number between i and k with the ouput
                           § being the list [i,k]

           rcS             § Reverse the list and concatenate everything into a single
                           § number (we reverse it to not lose the leading 0 if i = 0 when
                           § we concatenate into a single number). Call this number S.

              :0xlI        § Remove all occurences of 0 from S, call I the length of this new
                           § number with no zeros

                   ,Sl-I=. § Output the length of S minus I.

```

# Answer
> 2 votes
# Julia, 48 bytes - 30% = 33.6

```
f(i,k,b)=sum(j->sum(c->c<49,[base(b,j)...]),i:k)

```

This is a function that accepts three integers and returns an integer. One of the arguments specifies the base, so this qualifies for the bonus.

Ungolfed:

```
function f(i, k, b)
    # For each j in the inclusive range i to k, convert j to base
    # b as a string, splat the string into a character array, and
    # compare each character to the ASCII code 49 (i.e. '1'). The
    # condition will only be true if the character is '0'. We sum
    # these booleans to get the number of zeros in that number,
    # then we sum over the set of sums to get the result.
    sum(j -> sum(c -> c < 49, [base(b, j)...]), i:k)
end

```

Implementing the bonus yields a score just barely better than the not implementing it (34 bytes):

```
f(i,k)=sum(c->c<49,[join(i:k)...])

```

# Answer
> 2 votes
# Seriously, 2 bytes

This might be taking the Jelly answer trick to the limit, but here is a simple 2 byte Seriously answer.

```
,Y

```

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 50 (71 - 30%)

```
(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

```

*No bonus, base k+2* is 10 bytes `(i,k)=>+!i`

*No bonus, unary* is 8 bytes `(i,k)=>0`

**TEST**

```
f=(n,k,b)=>eval("for(o=0;n<=k;++n)o+=n.toString(b)").match(/0/g).length-1

function go() {
  var i=I.value.match(/\d+/g)
  R.textContent = f(i[0],i[1],i[2])
}

go()
```

```
i,k,b:<input id=I value='0,500,10' oninput="go()">
<span id=R></span>
```

# Answer
> 2 votes
# PHP, 50 Bytes

supports decimal only

```
<?=substr_count(join(range($argv[1],$argv[2])),0);

```

## supports decimal and binary with Bonus 63

```
<?=substr_count(join(array_map([2=>decbin,10=>""][$argv[3]],range($argv[1],$argv[2]))),0);

```

## supports decimal,hexadecimal, octal and binary with Bonus 77.7

```
<?=substr_count(join(array_map([2=>decbin,8=>decoct,10=>"",16=>dechex][$argv[3]],range($argv[1],$argv[2]))),0);

```

## supports base 2 - 36 with Bonus 78.4

```
<?=substr_count(join(array_map(function($i){return base_convert($i,10,$_GET[2]);},range($_GET[0],$_GET[1]))),0);

```

# Answer
> 1 votes
# Python 3, 52.

Tried to implement the bonus, but it doesn't seem to be worth it.

```
lambda a,b:''.join(map(str,range(a,b+1))).count('0')

```

With test cases:

```
assert f(10, 10) == 1
assert f(0, 27) == 3
assert f(100, 200) == 22
assert f(0, 500) == 92

```

# Answer
> 1 votes
## Lua 74 bytes

```
z,c=io.read,""for a=z(),z()do c=c..a end o,b=string.gsub(c,"0","")print(b)

```

There's gotta be a more effective way to do this...

I thought I was really onto something here:

```
c,m,z=0,math,io.read for a=z(),1+z()do c=c+((m.floor(a/10))%10==0 and 1 or a%100==0 and 1 or a%10==0 and 1 or 0) end print(c)

```

But alas... It keeps getting longer and longer as I realize there's more and more zeroes I forgot about...

# Answer
> 1 votes
## PowerShell, ~~56~~ ~~54~~ ~~51~~ ~~48~~ 42 bytes

```
param($i,$k)(-join($i..$k)-split0).count-1

```

Takes input, creates a range with `$i..$k` then `-join`s that together into a string, followed by a regex `-split` command that separates the string into an array by slicing at the `0`s. We encapsulate that with `().count-1` to measure how many zeros. That's left on the pipeline, and output is implicit.

*Saved 6 bytes thanks to @ConnorLSW*

Try it online!

---

Base-handling in PowerShell is limited and doesn't support arbitrary bases, so I'm not going for the bonus.

# Answer
> 1 votes
# Jolf, 7 bytes

Replace  with `\x11`. Try it here!

```
Zl♂sjJ0
   sjJ  inclusive range between two numeric inputs
  ♂      chopped into single-length elements
Zl    0  and count the number of zeroes
        implicitly printed

```

# Answer
> 1 votes
# APL, 22 bytes

```
{+/'0'⍷∊0⍕¨(⍺-1)↓⍳⍵}

```

This is a monadic function that accepts the range boundaries on the left and right and returns an integer.

Ungolfed:

```
           (⍺-1)↓⍳⍵}  ⍝ Construct the range ⍺..⍵ by dropping the first
                      ⍝ ⍺-1 values in the range 1..⍵
       ∊0⍕¨           ⍝ Convert each number to a string
{+/'0'⍷               ⍝ Count the occurrences of '0' in the string

```

Try it here

# Answer
> 1 votes
## Haskell, 29 bytes

```
i#k=sum[1|'0'<-show=<<[i..k]]

```

I'm using base 10.

Usage example: `100 # 200` -\> `22`

How it works: turn each element in the list from `i` to `k` into it's string representation, concatenate into a single string, take a `1` for every char `'0'` and sum those `1`s.

# Answer
> 1 votes
# MATL, 7 (10 bytes − 30% bonus)

```
2$:i:qYA~z

```

**Try it online!**

This works in release 11.0.2, which is earlier than this challenge.

### Explanation

```
2$:      % implicitly input two numbers and generate inclusive range
i:q      % input base b and generate vector [0,1,...,b-1]
YA       % convert range to base b using symbols 0,1,...,b-1. Gives 2D array
~        % logical negation. Zeros become 1, rest of symbols become 0
z        % number of nonzero elements in array

```

# Answer
> 1 votes
# Matlab: 27 bytes

```
@(q,w)nnz(num2str(q:w)==48)

```

creates a vector from lower number to larger one, then converts all numbers to string and counts all the '0' symbols.

# Answer
> 1 votes
# Perl 6, 23 bytes

```
{+($^i..$^k).comb(/0/)}

```
1. creates a Range ( `$^i..$^k` )
2. joins the values with spaces implicitly ( `.comb` is a Str method )
3. creates a list of just the zeros ( `.comb(/0/)` )
4. returns the number of elems in that list ( `+` )

### Usage:

```
my &zero-count = {…}

for (10,10), (0,27), (100,200), (0,500), (0,100000) {
  say zero-count |@_
}

```

```
1
3
22
92
38895

```

# Answer
> 1 votes
# Mathematica, 39 bytes, 27.3 with bonus

```
Count[#~Range~#2~IntegerDigits~#3,0,2]&

```

# Answer
> 1 votes
# C# 112 Bytes

```
int z(int i,int k)=>String.Join("",Enumerable.Range(i,k-i+1)).Count(c=>c=='0')

```
1. Create a string with numbers from the first number up to the last number
2. Count the zero characters in the string

# Answer
> 1 votes
# PHP, 84 bytes \*.7=58.8 (bases 2 to 36)

```
for(;($v=$argv)[2]>$a=$v[1]++;)$n+=substr_count(base_convert($a,10,$v[3]),0);echo$n;

```

or

```
for(;($v=$argv)[2]>$v[1];)$n+=substr_count(base_convert($v[1]++,10,$v[3]),0);echo$n;

```

takes decimal input from command line arguments; run with `-r`.

# Answer
> 0 votes
# Java 8, 102 bytes - 30% = 71.4

Why not.

```
(i,k,b)->{int j=0;for(;i<=k;i++)for(char c:Integer.toString(i,b).toCharArray())if(c==48)j++;return j;}

```

Without the bonus, 96 bytes (so the bonus actually improves my score!):

```
(i,k)->{int j=0;for(;i<=k;i++)for(char c:String.valueOf(i).toCharArray())if(c==48)j++;return j;}

```

This implements the following:

```
interface Function {
    public int apply(int i, int k, int b);
}

```

# Answer
> 0 votes
## Clojure, ~~50~~ 49 bytes

```
#(count(re-seq #"0"(apply str(range %(inc %2)))))

```

Oh regex is shorter than filtering. Original:

```
#(count(filter #{\0}(apply str(range %(inc %2)))))

```

Very basic, uses the set of character `\0` to remove others and counts how many were found.

---
Tags: code-golf, number, base-conversion, counting
---


title: The branch predictor challenge

text:
# Question
Title: The branch predictor challenge
Every day, every minute, ... every microsecond, many decisions are made by your computer. In high-level languages, these typically take the form of statements like `if`, `while` and `for`, but at the most basic level there exist machine language instructions called branch/jump instructions. Modern processors queue instructions up in a pipeline, and this means that the processor needs to decide whether to fill the pipeline with instructions immediately following a branch (i.e. it is not *taken*) or the instructions at the branch destination.

If the processor does not guess correctly, the instructions which have been wrongly entered into the pipeline need to be ignored and the correct instructions must be fetched, causing a delay. The job of the branch predictor is to try and guess whether the branch will be taken to avoid the costly action of refilling the pipeline.

You must write a predictor that will, given a sequence of past decisions, guess the next decision correctly. Your program can be written in any language, provided you specify the link to its interpreter if it's an obscure/golfing language. It must take the past actual history as its first command-line argument, but it will not be provided for the first guess of the sequence. You must then return your guess by printing it to stdout. A decision is of the form "y" or "n". Each test case is a sequence of 72 decisions, so you can assume that the specified history argument will never be longer than 71 characters. For example, the "Alternating 1" test:

```
ynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynyn

```

You will be disqualified if your program:

* does not return a result within one second
* does not return either a `y` or `n` (new lines don't matter and are ignored)
* attempts to modify any code or file associated with this challenge, including other contender's code
* contains anything otherwise malicious

You may use a file for persistence if you wish, but it must be uniquely named and conform to the above.

This is a , not . Victory will be granted by the branch predictor predictor to the contender whose solution successfully predicts the most branches in the whole test suite. Tests:

```
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,All yes
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn,All no
ynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynynyn,Alternating 1
nnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyynnyy,Alternating 2
yyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnnyyynnn,Alternating 3
nnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyy,Alternating 4
yyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnn,Alternating 5
nnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyyyyyyyyyy,Alternating 6
yyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnnyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnn,Alternating 7
yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn,Alternating 8
yynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyynyyn,2-1
ynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnnynnn,1-3
nyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyy,5-1
nnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnnynnnnnnnnnnny,1-11
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyynyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,35-1
yynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnnyynnnn,2-4
ynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnnynnyyynyynnn,1-2-3
ynynynynynynynynynynynynynynynynynynyyyyyyyyyyyyyyyyyynnnnnnnnnnnnnnnnnn,A1/A7
yyyyyynnnnnnyyyyyynnnnnnyyyyyynnnnnnnnyynnyynnyynnyynnyynnyynnyynnyynnyy,A5/A2
nnnnnnnnnnnnyyyyyyyyyyyynnnnnnnnnnnnyyyynnnnyyyynnnnyyyynnnnyyyynnnnyyyy,A6/A4
nyyyyynyyyyynyyyyynyyyyynyyyyynyyyyynyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy,5-1/35-1
yyynnnyyynnnyyynnnnyyyyyyyyyyyyyyyyyyyyyyynyyyyynyyyyyyynnnnyynnnnyynnnn,A3/Y/5-1/2-4
yynnnnyynnnnyynnnnnyynnnynnyyynyynnnnnnynnnynnnynnnynnyynyynyynyynyynyyn,2-4/1-2-3/1-3/2-1

```

The full set of tests and runner program are situated at this GitHub repository. Simply add your predictor to `src/predictors.txt` in the form `<name>,<command to run>` and run `main.py`. I have provided two very basic predictors already for simple testing. I would recommend a column width of at least 92 when running the runner for nice output. If you happen to spot any bugs with it, please let me know. :)

# Answer
# Compressor (Ruby), score 1502/1656 ≈ 90.7%

```
require 'zlib'
input = $*[0].to_s.chomp
recent_input = input[-35..-1] || input
puts recent_input.chars.uniq.min_by { |char| [Zlib::Deflate.deflate(input+char,9).size,-input.count(char),-input[-10..-1].to_s.count(char)] } || ?y

```

Checks whether the current string would be more compressible if 'y' or 'n' were added to the end. If equally compressible, use the one that's shown up the most.
> 14 votes

# Answer
# DéjàVu (Mathematica), score 503/552 ≈ 91.123%

```
If[Length[$ScriptCommandLine] < 2, Print["y"]; Exit[]];
input = Characters[$ScriptCommandLine[[2]]] /. {"y" -> 1, "n" -> 0};
For[test = Length[input], !
   ListQ[ker = FindLinearRecurrence[input[[-test ;;]]]], test--];
Print[LinearRecurrence[ker, input[[-test ;; Length[ker] - test - 1]],
     test + 1][[-1]] /. {1 -> "y", _ -> "n"}];

```

Looks for a linear recurrence in the pattern, and computes the next term. For testing, save as `DéjàVu,MathematicaScript -script <file>`.
> 7 votes

# Answer
# Historian (Kotlin), score 1548/1656 ≈ 93.478%

Predicts the future from the past.

```
fun main(args : Array<String>) {
    if (args.size == 0) {
        println('y')
        return
    }
    val history = args[0].reversed()
    var bestLength = 0
    var ys = 0
    var ns = 0
    for (i in 1..history.length-1) {
        var length = 0
        var j = i
        while (j < history.length) {
            if (history[j] == history[j - i]) {
                length++
            } else {
                break
            }
            j++
        }
        if (length > bestLength) {
            bestLength = length
            ys = 0
            ns = 0
        }
        if (length == bestLength) {
            if (history[i - 1] == 'y') {
                ys++
            } else {
                ns++
            }
        }
    }
    println(if (bestLength == 0) history[0] else if (ys >= ns) 'y' else 'n')
}

```

Compile with: `kotlinc Historian.kt`
Run with: `kotlin HistorianKt`
> 2 votes

# Answer
## Pattern-Finder (Java), score 1570/1656 (≈94.8%) ~~1532/1656 (≈92.5%)~~

Slight improvements for complex patterns.

```
public class Main {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.print("y");
            return;
        }
        System.out.print(new Pattern(args[0]).getNext());
    }

}

class Pattern {

    private String pattern;
    private int index;
    private int length;

    public Pattern(String string) {
        setPattern(string);
    }

    private void setPattern(String string) {
        if (string.length() == 0) {
            this.pattern = "y";
            this.index = 0;
            this.length = 1;
            return;
        }
        if (string.length() == 1) {
            this.pattern = string;
            this.index = 0;
            this.length = 1;
            return;
        }
        if (string.startsWith("ynnyyy")) {
            this.pattern = "ynnyyynyynnn";
            this.index = string.length() % 12;
            this.length = 12;
            return;
        }
        this.length = 0;
        char first = string.charAt(0);
        char current = first;
        boolean hasReverse = false;
        while (length < string.length() - 1 && !(hasReverse
                && current == first)) {
            hasReverse |= current != first;
            length++;
            current = string.charAt(length);
        }
        if (!(hasReverse && current == first)) {
            this.pattern = Character.toString(current);
            this.index = 0;
            this.length = 1;
            return;
        }
        this.pattern = string.substring(0, length);
        int i = length;
        while (i <= string.length() - length) {
            if (!string.substring(i, i + length).equals(pattern)) {
                setPattern(string.substring(i));
                return;
            }
            i += length;
        }
        this.index = string.length() % i;
        if (!string.substring(i).equals(pattern.substring(0, index))) {
            setPattern(string.substring(i));
        }
    }

    public char getNext() {
        char result = pattern.charAt(index);
        index = (index + 1) % length;
        return result;
    }

}

```
> 1 votes

# Answer
**Factorio (Python3), score 1563/1656 ≈ 94.38%**

Factors the sequence from left to right into a series of repeating and alternating patterns. Primarily favours longer match lengths, but chooses repeating over alternating patterns and shorter over longer cycle lengths in case of a tie.

```
def main():
    if len(sys.argv) < 2:
        print('y')
        sys.stdout.flush()
        return
    history = sys.argv[1]
    while history:
        score = 0
        period = 0
        l = 0
        for p in range(1, len(history)):
            if history[0] == history[p]:
                m = lambda a, b: a == b
                s0 = 1
            else:
                m = lambda a, b: a != b
                s0 = 0
            s = 0
            for i in range(len(history)):
                j = i + p
                if j < len(history):
                    if not m(history[i], history[j]):
                        break
                    s += 1
            if s > score or s == score and s0 > score0:
                score = s
                score0 = s0
                period = p
                match = m
                l = j
        if period == 0:
            print(history[0])
            sys.stdout.flush()
            return
        if l >= len(history):
            break
        l = (l // period) * period
        history = history[l:]
    print('y' if match(history[-period], 'y') else 'n')
    sys.stdout.flush()

if __name__ == '__main__':
    main()

```
> 1 votes

# Answer
# Repeater (Python), score 1173/1656 ≈ 70.83%

This predictor simply guesses yes if there's no history, otherwise repeats the previous actual outcome.

```
import sys

if len(sys.argv) == 1:
   print "y"
else:
   print sys.argv[1][-1:]

```

# !Repeater (Python), score 483/1656 ≈ 29.17%

If there's no history this predictor will guess no, otherwise will repeat the opposite of the last actual outcome.

```
import sys

if len(sys.argv) == 1:
   print "n"
else:
   if sys.argv[1][-1:] == "y":
      print "n"
   else:
      print "y"

```

# 2-toucher (Python), score 1087/1656 ≈ 65.64%

If there were at least two previous outcomes that were the same, or there has been one outcome so far, this predictor will choose the same. If there is no history, it will choose "y". If there were at least two outcomes and the most recent two were not the same, it will choose the opposite of the most recent.

```
import sys

if len(sys.argv) == 1:
   print "y"
elif len(sys.argv[1]) == 1:
   print sys.argv[1][-1:]
else:
   l = len(sys.argv[1])

   if sys.argv[1][l - 2:l - 1] == sys.argv[1][-1:]:
      print sys.argv[1][-1:]
   else:
      if sys.argv[1][-1:] == "y":
         print "n"
      else:
         print "y"

```
> 0 votes

# Answer
I would leave a comment, but the 50 rep requirement prevents me.

Was able to get a small improvement on @histocrat's answer

# Compressor (Ruby), score 1504/1656 ≈ 90.82%

```
require 'zlib'
input = $*[0].to_s.chomp
recent_input = input[-35..-1] || input
puts recent_input.chars.uniq.min_by { |char| [Zlib::Deflate.deflate(input+char,9).size,-input[-3..-1].to_s.count(char),-input.count(char)] } || ?y

```

I tweaked it in a number of different ways, and a +0.12% improvement was the best I found.
> 0 votes

---
Tags: test-battery
---


# Question
Title: Dancing arrays. Output them with some forward-backward moves
The task is to create a program (or a function), which outputs array elements in the order, determined by two numbers **F** and **B**. **F** is number of elements to print, **B** is the rollback distance (from last printed element). Each element must be printed on separate line and blank line must be inserted after each rollback. Run till the end of array. If endless loop or backward progression requested, program should print nothing and exit. Same for empty arrays.

**F** and **B** cannot be negative numbers. Be positive while dancing!

For example, if given:

```
array is 2, 3, 5, 7, 11, 101, 131;
F is 4;
B is 1;

```

then output must be:

```
2
3
5
7

5
7
11
101

11
101
131

```

Init array, **F** and **B** as you like.

Shortest code wins. Imperative beauty will be enjoyed.

**Test cases:**

```
Empty array.
Any F.
Any B.

```

Produces no output (array is empty).

---

```
Array: [42]
F = 0;
B = 1;

```

Produces no output (zero elements to print).

---

```
Array: [42, 17, 84]
F = 2;
B = 1;

```

Produces no output (endless printing).

---

```
Array: [7, 16, 65]
F = 2;
B = 3;

```

Produces no output (will be moving backward to negative indices).

---

```
Array: [7, 16, 65]
F = 2;
B = 0;

```

Output:

```
7
16

16
65

```

---

```
Array: [7, 16, 65]
F = 3;
B = 2;

```

Output:

```
7
16
65

```

(no rollback, end of array is reached).

---

```
Array: [7, 16, 65]
F = 17;
B = 15;

```

Output:

```
7
16
65

```

(run till the end)

---

```
Array: [7, 16, 65]
F = 17;
B = 16;

```

Output:

```
7
16
65

```

Whole array can be printed in first iteration, run till the end is working, even if F and B form endless-loop condition.

# Answer
> 1 votes
# Python 2, ~~135~~ ~~128~~ 126 bytes

Pretty naive solution:

```
a,f,b=input()
b+=1
l=len(a)
i=0
e=min(l,f)
while f>b:
    print'\n'.join(map(str,a)[i:e])+'\n';i=e-b
    if e==l:f=b
    e=min(l,e+f-b)

```

Try it online!

Input format is `[array], F, B` except you can also use `()`. (You can't use `{}` because that's unordered; thanks to Felipe Batista for pointing that out because I forgot).
Output format is as specified in the challenge, with a single trailing newline at the end of all output and no leading whitespace.

-7 bytes by changing `if f>b: while 1:` to `while f>b`
-2 bytes by changing `break` to `f=b` because that causes the `while` loop to exit.

# Answer
> 1 votes
# JavaScript, 119 bytes

```
(a,b,c)=>{o="";for(s=++b;(s<(t=c.length)||s==b)&&s>=0&&b<a;)s-=b,o+=c.slice(s,s+=a<t?a:t).join`
`+`

`;return s>0?o:""}

```

Try it online!

Receives input in the format F, B, \[Array\]

# Answer
> 0 votes
## Python 2, 116

Finally beat javascript!

Now in case of endless loop outputs full array only if it fits in one step, otherwise ouputs nothing. Output all array in every case of endless loop was harder.

Uncomment different test cases in footer in Try it online

```
a,F,B=input()
l=len(a)-F;m=F+~B or-1;s=l/m;s+=1+(s*m<l)
for i in range(s):print"\n".join(map(str,a)[m*i:F+i*m]+[''])

```

Explanation:

```
  a,F,B=input()
  l=len(a)-F            # length of input array minu F stored to compact code
  m=F+~B or-1           # get the difference beetween blocks of output
                        # if F-B-1 == 0, which means endless loop, makes m = -1, which will make s < 0 and for loop won't execute
  s=l/m                 # get number of blocks (does not count first block)
  s+=1+(s*m<l)          # +1 for first block (brackets are still needed)
                        # s*m<l-F equals +1 for numbers at the end of array, that are not enough to make full block
                        # s becomes 2 in case of F-B-1==0, but it doesn't matter
  for i in range(s):
                        # print elements from slices, joined by line separator
                        # additional empty element added at the end of each block to divide blocks with newline
    print"\n".join(map(str,a)[m*i:F+i*m]+[''])

```

# Answer
> 0 votes
# 05AB1E, 41 bytes

```
gD²³+‹iq}©0U[XD²<+Ÿv¹yè,}¶,³X+U®X³2*+-0‹#

```

Try it online!

That output format, and inability to limit inputs for F/B made this less fun, will explain soon.

# Answer
> 0 votes
## Mathematica, ~~136~~ 123 bytes

Here's my answer:

```
""<>r[#~(r=Riffle)~"\n"&/@Quiet@Check[Partition[#,#2,n=#2-#3-1,1,{}]~Take~-Floor[(L=#2-Length@#)/n-1],If[L<0,{},{#}]],"\n\n"]&

```

(where `\n`s are replaced by newlines). It's a function that takes a list of strings (e.g. `{"1", "2", "3", ...}`) and two integers.

Mathematica has a function that almost solves this challenge on its own, namely `Partition[#, #2, #2-#3-1, 1, {}]`. However, the output format isn't what we want, it returns errors if **F** and **B** would put the program into a loop, and it doesn't stop when it reaches the end of a list (so if the inputs are `{"1", "2", "3"}`, `3`, `1`, for instance, it returns `{{"1", "2", "3"}, {"2", "3"}, {"3"}}` instead of just `{{"1", "2", "3"}}`). We deal with those technicalities as follows:

* `...~Take~-Floor[(L=#2-Length@#)/n-1]` gets rid of the extra bits after we hit the end of the list.
* `Quiet@Check[...,If[L<0,{},{#}]]` deals with the infinite loop cases by `Check`ing if the earlier code gives errors (but it does it `Quiet`ly, so it doesn't actually print them), and instead returns an empty list or the entire list as appropriate.
* `""<>r[#~(r=Riffle)~"\n"&/@...,"\n\n"]&` formats the output properly, by putting newlines between everything, including double newlines between the separate groups, and string-joins that all together.

# Answer
> 0 votes
# Ruby, ~~78 76~~ 72 bytes

```
->a,f,b{i=b-=f-1;puts a[i,f]+[""]while 0>b&&a[f+i-=b];b<i&&puts(a[i,f])}

```

### Explanation

* Initialize the index so that the first step brings it back to zero.
* Print `f` elements from the array starting with the current index, then a newline
* Move the index `f-b-1` elements forward, but only if `(b-f+1)` is negative
* If the increment is not negative, or we reached the end of the array, stop.
* If everything went Ok, the increment is negative, and the index is not (we took at least one step forward), in this case print the remaining elements.

# Answer
> 0 votes
# dc, 123 bytes

```
[[[dx]dx]sOzlF!>O]sO?1+sBsFlFlB-1>O_1sq[lq1+:Rlq1+sqz0<k]dskx0sd[[10PlqlB+sq]sWld0<W]sz[ldlF%0=zlq;Rplq1-dsqld1+sd0!>g]dsgx

```

Much longer than it should have been because of strict output regulations. Takes input on one line in the format

```
n_1 n_2 ... n_k F B

```

where `n_i` represents the `i`th element of the `k` length array. I hope this is an okay input format.

Try it online!

---
Tags: code-golf, array
---


title: Abbreviate an array

text:
# Question
Title: Abbreviate an array
# Goal:

Given an array of strings, create abbreviated versions of each string.

# Specification:

For this challenge, an abbreviation is the first N characters of a string. For the string `abc`: `a`, `ab`, and `abc` are all valid abbreviations, while `bc`, and `ac` are not.

Given an array of strings, we want to find the shortest set of abbreviations, such that given the input and any abbreviation, you could determine which item of the input that the abbreviation was referring to.

# Example:

Input: `["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]`

We work our way through the strings starting with the first one.

* Monday is only the item string with an `M`, so the shortest possible abbreviation is `M`.
* Tuesday starts with`T`, but so does Thursday. This means that we try the string `TU`. Since no other strings start with that, we use `TU`.
* Wednesday is `W`, Thursday is `Th`, and Friday is `F`.

# More Examples:

```
Input: "one,two,three,four,five,six,seven"
Output: "o,tw,th,fo,fi,si,se"

Input: "red,orange,yellow,green,blue,purple"
Output: "r,o,y,g,b,p"

Input: "a,ab,abc"
Output: Not valid! No abbreviation for `a` that doesn't apply to the other items.

```

# Notes:

* You make input and output in any reasonable way.
* You can assume that input will always be a valid array of strings.
* You can assume that there will always be a solution, unlike in the last test case.
* Strings will only consist of printable ASCII (or the printable characters in your encoding)
* This is code golf, so fewest bytes win!

# Answer
## Retina, 29 bytes

```
!ms`^(.+?)(?!.+^\1)(?<!^\1.+)

```

Input and output are linefeed-separated lists of strings.

Try it online! (Test suite with comma-separation for convenience.)

### Explanation

This simply matches all the prefixes with a single regex and prints them (`!`). `m` and `s` are the usual regex modifiers to make `^` match line beginnings and `.` match linefeeds.

```
^(.+?)      # Match the shortest possible prefix of a line and capture
            # it in group 1.
(?!.+^\1)   # Make sure that this prefix does not show up in a line after
            # the current one.
(?<!^\1.+)  # Make sure that this prefix does not show up in a line before
            # the current one.

```
> 10 votes

# Answer
# Python 2, ~~87~~ 86 bytes

```
lambda a:[b[:min(i for i in range(len(b))if sum(s[:i]==b[:i]for s in a)<2)]for b in a]

```

Try it online!
> 10 votes

# Answer
## JavaScript (ES6), ~~81~~ ~~78~~ ~~74~~ 70 bytes

Takes input as an array of strings.

```
a=>a.map(s=>[...s].reduce((y,c)=>a.some(x=>x!=s&!x.indexOf(y))?y+c:y))

```

### Formatted and commented

```
a =>                          // given an array of strings 'a'
  a.map(s =>                  // for each string 's' in 'a':
    [...s].reduce((y, c) =>   //   starting with 'y' = first character of 's',
                              //   for each subsequent character 'c' of 's':
      a.some(x =>             //     if we find a string 'x' in 'a' such that:
        x != s &              //       - 'x' is different from 's'
        !x.indexOf(y)         //       - and 'y' appears at the beginning of 'x'
      ) ?                     //     then:
        y + c                 //       append 'c' to 'y'
      :                       //     else:
        y                     //       keep 'y' unchanged
    )                         //   end of reduce(): returns the correct prefix
  )                           // end of map()

```

### Test cases

```
let f =

a=>a.map(s=>[...s].reduce((y,c)=>a.some(x=>x!=s&!x.indexOf(y))?y+c:y))

console.log(JSON.stringify(f(["Monday","Tuesday","Wednesday","Thursday","Friday"])))
console.log(JSON.stringify(f(["one","two","three","four","five","six","seven"])))
console.log(JSON.stringify(f(["red","orange","yellow","green","blue","purple"])))
```
> 8 votes

# Answer
# Jelly, 14 bytes

```
;\w@þ=1Si1⁸ḣð€

```

Try it online!

### How it works

```
;\w@þ=1Si1⁸ḣð€  Monadic link. Argument: A (string array)

            ð   Collect all links to the left into a chain (arity unknown) and
                begin a dyadic chain.
             €  Map the previous chain over A. The current chain is dyadic and the
                mapped one inherits its arity. Thus, the right will be A for all
                invocations, while the left argument will iterate over A.
                For each string s in A, the following happens.
;\                Cumulative reduce by concatenation; yield all prefixes of s.
  w@þ             Window index swapped table; for each string t in A and each
                  prefix p of s, find the index of the substring t in p.
                  The first index is 1; 0 means not found.
     =1           Compare the indices with 1, returning 1 iff t begins with p.
       S          Sum the Booleans across columns, counting the number of strings
                  in A that begin with a given prefix.
        i1        Find the first index of 1, the shortest prefix that is unique
                  across all strings in A.
          ⁸       Head; truncate s to the computed length.

```
> 6 votes

# Answer
# Haskell, 48 bytes

```
[_]#x=""
a#(c:y)=c:[z|d:z<-a,c==d]#y
f=map=<<(#)

```

Try it online!

* `f` is the main function, taking a list of `String`s and returning a `String`. Its definition is a monadic shortcut for `f a=map (a#) a`.
* `a#x` looks at the string `x` and the list `a` and tries to find the shortest prefix of `x` that is unique in `a`. If `a` has a single element, just use the empty string. If `a` isn't already a single element, chop off the first character of `x`, filter and chop the elements of `a` starting with the same character, then recurse.
> 6 votes

# Answer
## Mathematica, 64 bytes

```
#&@@@StringCases[#,Shortest@x__/;Tr@Boole@StringStartsQ[#,x]<2]&

```
> 4 votes

# Answer
# Jelly, ~~14~~ 12 bytes

```
ḣ€JṙLḶ$ḟ/€Ḣ€

```

Try it online!

### How it works

```
ḣ€JṙLḶ$ḟ/€Ḣ€  Main link. Argument: A (string array)

  J           Yield the 1-based indices of A, i.e., [1, ..., len(A)].
ḣ€            Head each; for each string s in A, take the first 1, ..., and len(A)
              characters. This builds the 2D array of prefixes of all strings in A.
    LḶ$       Length-unlength; yield [0, ..., len(A)-1].
   ṙ          Rotate the 2D array 0, ..., and len(A)-1 units to the left.
       ḟ/€    Reduce filterfalse each; for each rotation, remove all prefixes from
              the first set that also occur in later sets.
          Ḣ€  Head each; for each rotation, keep only the shortest unique prefix.

```
> 3 votes

# Answer
# Javascript ES6, 70 chars

```
s=>(s+'#'+s).replace(/(\w+?)(\w*)(?=(\W(?!\1(?!\2))\w+)+$)|#.+/g,"$1")

```

```
f=s=>(s+'#'+s).replace(/(\w+?)(\w*)(?=(\W(?!\1(?!\2))\w+)+$)|#.+/g,"$1")

console.log(f("one,two,three,four,five,six,seven")==="o,tw,th,fo,fi,si,se")
console.log(f("red,orange,yellow,green,blue,purple")==="r,o,y,g,b,p")
console.log(f("one,two,three,four,five,six,seven".split`,`)==="o,tw,th,fo,fi,si,se")
console.log(f("red,orange,yellow,green,blue,purple".split`,`)==="r,o,y,g,b,p")
```
> 3 votes

# Answer
# C++11 (MinGW), 198 bytes

```
#import<list>
#import<iostream>
f(std::list<std::string>l){int i,m;for(auto s:l){for(i=0,m=1;++i<s.length();)for(auto t:l)if(t!=s&&t.substr(0,i)==s.substr(0,i))m=i+1;std::cout<<s.substr(0,m)<<" ";}}

```

Call with:

```
int main()
{
    f({"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"});
}

```

Adding `void` identifier before the function should make it compile on other compilers too, thereby adding 5 bytes to the length.
> 2 votes

# Answer
# PHP, ~~131 120 119~~ 118 bytes

Thanks @Jörg for `preg_grep`.

```
for(;a&$s=$argv[++$k];$i=+$t=!print"$t
")for(;a&$s[$i]&&1<count(preg_grep("(^".preg_quote($t.=$s[$i++]).")",$argv)););

```

takes input from command line arguments; prints results one line each.
Run with `-nr` or try it online.

* may fail if input contains anything starting with `-`.
+15 bytes to fix: replace the second `$argv` with `array_slice($argv,1)`.
* yields warnings in PHP 7.1; replace `a&` with `""<` (+1 byte) to fix.
* -12 bytes if input contains no regex special chars:
Insert `&($t.=$c)` before `&&` and replace `". preg_quote($t.=$c)."` with `$t`.

**breakdown**

```
for(;a&$s=$argv[++$k];      # loop $s through arguments
    $i=+$t=!                # 3. reset $i and $t to empty
    print"$t\n")            # 2. print abbreviation
    for(;a&($c=$s[$i++])    # 1. loop $c through characters
        &&1<count(              # 3. if count==1, break loop
            preg_grep("(^"      # 2. find matching arguments
                . preg_quote(
                $t.=$c          # 1. append $c to abbreviation
            ).")",$argv)
        );
    );

```

**non-regex version, ~~131~~ 130 bytes**

```
for($a=$argv;a&$s=$a[++$k];$i=+$t=!print"$t
")for($n=1;$n&&a&$c=$s[$i++];)for($n=$m=1,$t.=$c;a&$u=$a[$m++];)$n-=0===strpos($u,$t);

```

Replace the first and the last `a&` with `""<` (+2 bytes) to fix for PHP 7.1.

**breakdown**

```
for($a=$argv;a&$s=$a[++$k];     # loop through arguments
    $i=+$t=!print"$t\n")            # 2. print abbreviation, reset $i and $t to empty
    for($n=1;$n&&a&$c=$s[$i++];)    # 1. loop through characters while $n<>0
        for($n=$m=1,                    # reset $n and $m to 1
            $t.=$c;                     # append current character to prefix
            a&$u=$a[$m++];              # loop through arguments:
        )$n-=0===strpos($u,$t);         # -$n = number of matching strings -1

```

completely uninteresting note:
`strstr($u,$t)==$u` and `0===strpos($u,$t)` have the same length and the same result.
> 2 votes

# Answer
# PHP, 127 Bytes

works not with invalid arrays

```
<?foreach($a=$_GET as$k=>$v)for($i=0,$c=2,$s="";$c>1;$r[$k]=$s)$c=count(preg_grep("_^".($s.=$v[$i++])._,$a));echo join(",",$r);

```

## PHP, 132 Bytes

```
<?foreach($a=$_GET as$v)for($i=0,$s="";a&$v[$i];)if(count(preg_grep("_^".($s.=$v[$i++])._,$a))==1){$r[]=$s;break;}echo join(",",$r);

```

Online Version

## 151 Bytes supports special characters

```
<?foreach($a=$_GET as$v)for($i=0,$s="";a&$v[$i];)if(count(preg_grep("_^".preg_quote($s=substr($v,0,++$i),_)._,$a))==1){$r[]=$s;break;}echo join(",",$r);

```

## PHP, 140 Bytes

```
<?foreach($a=$_GET as$k=>$v)for($i=0;a&$v[$i];)if(count(preg_grep("#^".($s=substr($v,0,++$i))."#",$a))==1){$r[]=$s;break;}echo join(",",$r);

```
> 1 votes

# Answer
# PowerShell, 151 139 bytes

```
$x,$w=@(),$args[0];$w|%{$k=$_;$a='';foreach($l in [char[]]$k){$a+=$l;if($a-notin$x-and!($w|?{$_-ne$k-and$_-like"$a*"})){$x+=$a;break;}}};$x

```

Interested if there's a better way to do this. Had to use a `foreach` (over a `|%`) to be able to perform a `break` in the nested loop without labeling it.

Edit: 2 golfs from AdmBorkBork
> 0 votes

# Answer
# APL (Dyalog), 27 bytes

```
{⍵↑¨⍨1⍳⍨¨↓+/(↑,\¨⍵)∘.(⊃⍷)⍵}

```

Try it online!

`{` an anonymous function, where ⍵ represents the argument...

`∘.(` a function table where the function is

the first element of

the Boolean list "left argument begins here in the right argument?"

`)` where the right arguments are

the arguemts

`(` and the left argument is

a table with rows consisting of

`,/` prefixes of

`¨` each of

the arguments

`+/` sum across (counts how many of the arguments befin with this prefix)

split table into list of rows

`⍳⍨¨` in each one, find the location of the first

`1` one (i.e. the first prefix that only heads one argument)

`↑¨⍨` for each location, takes that many characters from the corresponding element of

the argument

`}` end of anonymous function
> 0 votes

# Answer
## Clojure, 118 bytes

```
#(reduce(partial map(fn[a b](or a b)))(for[i(range 1e2)S[(for[c %](take i c))]](for[s S](if(=((frequencies S)s)1)s))))

```

This works on prefixes up-to length of `1e2` but the same byte count can support up-to `1e9`. `i` loops lengths of prefixes, `S` is the sequence of substrings of length `i`. The last `for` replaces those substrings with `nil` which occur more frequently than once. The reduction keeps the first non-nil value for each string, too bad `or` isn't a function so I had to wrap it.

This actually returns lists of lists of characters like `((\M) (\T \u) (\W) (\T \h) (\F))`, but I guess it is acceptable. Clojure is quite verbose with strings, and `subs` would throw `StringIndexOutOfBoundsException` unlike `take`.

Full examples:

```
(def f #(reduce(partial map(fn[a b](or a b)))(for[i(range 1e2)S[(for[c %](take i c))]](for[s S](if(=((frequencies S)s)1)s)))))

(f ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"])
(f (re-seq #"[^,]+" "one,two,three,four,five,six,seven"))
(f (re-seq #"[^,]+" "red,orange,yellow,green,blue,purple"))

```
> 0 votes

# Answer
# SQL (PostgreSQL 9.4 flavour), 219 bytes

Now for the longest answer:) I don't think this could even beat Java. I will try to shave a few more off this. Hoping to get rid of one of the nested queries, but don't like my chances.
This assumes that there is a table that contains the strings to be worked on. As this is SQL the order of the return is not guaranteed to be the same as the table order and in this case unlikely. If this is a problem I will delete.

```
SELECT R FROM(SELECT*,RANK()OVER(PARTITION BY A ORDER BY C,N)Z FROM(SELECT*,SUM(1)OVER(PARTITION BY R)C FROM(SELECT*FROM A JOIN LATERAL(select left(A,n)R,N FROM generate_series(1,length(A))S(n))L ON 1=1)X)Y)Z WHERE Z=1

```

SQL Fiddle
Explanation

```
  SELECT *
  FROM A
    JOIN LATERAL(SELECT LEFT(A,n)R,N
    FROM generate_series(1,length(A))S(n))L ON 1=1

```

The innermost query uses `generate_series` and a `LATERAL` join to create rows for the string split into increasing lengths, so 'one' becomes 'o','on','one'. The number of characters in the return is also kept.

```
SELECT
  *,
  SUM(1)OVER(PARTITION BY R)C
FROM ( ... )X

```

Then we add the number of records which have the same result. For example 'f' from four and five has 2, but 'fo' and 'fi' each have one. The `OVER` statement in SQL can be quite powerful. `COUNT(*)` would be the usual way, but `SUM(1)` gives the same result.

```
SELECT
  *,
  RANK()OVER(PARTITION BY A ORDER BY C,N)Z
FROM ( ... )Y

```

Then we rank the results for each input based on the least repetitions and characters. `ROW_NUMBER` would work here as well, but is longer.

```
SELECT R FROM ( ... )Z WHERE Z=1;

```

Finally we select the lowest rank number for each word.
> 0 votes

# Answer
# Pure Bash, 146 bytes

```
for i in $@;{ K=1;U=${i::1};((M++));L=;while [[ `for v in $@;{ ((L++));(($L!=$M))&&echo ${v::K}||:;}` =~ $U ]];do U=${i::K};((K++));done;echo $U;}

```

Try it online!
> 0 votes

# Answer
# APL, 26 bytes

```
{⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}

```

Explanation:

* `↓↑⍵`: pad each string in  to match the length of the longest string
* `∘.(`...`)⍨`: for each possible pair of strings, find the shared prefix:
    + : array inequality
    + : and
    + `=`: itemwise equality
    + `∧\`: and-scan (keep only the leading matches)
* `+/¨`: sum each vector in the table, giving the length of the shared prefixes
* `⌈/`: find the maximum value in each column
* `1+`: add one, giving the amounts of characters needed to keep each string unique
* `⍵↑¨⍨`: take that many characters from each string

Test:

```
      {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'Monday' 'Tuesday' 'Wednesday' 'Thursday' 'Friday'
┌─┬──┬─┬──┬─┐
│M│Tu│W│Th│F│
└─┴──┴─┴──┴─┘
      {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'one' 'two' 'three' 'four' 'five' 'six' 'seven'
┌─┬──┬──┬──┬──┬──┬──┐
│o│tw│th│fo│fi│si│se│
└─┴──┴──┴──┴──┴──┴──┘
      {⍵↑¨⍨1+⌈/+/¨∘.(∧\=∧≢)⍨↓↑⍵}'red' 'orange' 'yellow' 'green' 'blue' 'purple'
┌─┬─┬─┬─┬─┬─┐
│r│o│y│g│b│p│
└─┴─┴─┴─┴─┴─┘

```
> 0 votes

# Answer
## Q, 93 bytes

```
{n:1;{$[any e:(,/)1<{(+/)i like x}each i:z#'x;[z+:1;y:?[e;z#'x;i];.z.s[x;y;z]];y]}[x;n#'x;n]}

```

Solved recursively, takes string as input, gets first n elements of each string with every recursion. If any of those elements aren't unique it replaces them with first n+1 elements.
> 0 votes

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


title: Not so good roads in Rnccia

text:
# Question
Title: Not so good roads in Rnccia
Here in the absolutely made up country Rnccia we have a lot of good stuff, but the roads aren't good. There are lots of holes and only half of them get fixed. Even then, only half of the fixes are well done. Your task is to embrace the bad roads of this country and draw them for me.

## Input

You receive two positive integers as input. One represents the length of the road, and the second represents the number of lanes in each direction. The length of the road is guaranteed to be an even number.

## Output

Output or return an ASCII-art image of the road with as many holes as will fit. Read the next two sections to see how the road and holes should be generated.

## Road layout

1. Every road has a straight line of minuses(-) above and below it.
2. Every road has the same number of lanes in both directions.
3. Every road has a line of equal signs(=) down the middle.
4. Lanes have dashed lines between them (excep the special middle line from rule #3). One minus, one whitespace and so on. Starting with the minus.

Examples of roads:

```
Road with one lane in both sides:

--------------

==============

--------------

Road with two lanes in both sides:

--------------

- - - - - - -

==============

- - - - - - -

--------------

```

## Hole layout

1. Every road has 7**n** total holes. **n** is the ceiling of the number of holes that will fit on the road divided by seven.
2. Every road has 4**n** unfixed holes. An unfixed hole is represented as double O (OO).
3. Every road has 2**n** holes that are fixed and represented as double # (##).
4. Every road also has **n** holes that are fixed well and represented as double H (HH).
5. Holes (in any state) appear on every lane in diagonal pattern, starting at the top right and moving down-across. A new line of holes should start in every 4th lane and every 8 characters in the top lane. See the examples for clarification.
6. The order of holes is irrelevant.
7. If 7**n** holes can't fit in road of given length, you may use #6 to choose which of the holes will not be visible.

In this example we have 14 holes, 4 of which are fixed poorly, and 2 which are fixed well:

```
------------------
OO      HH      OO
- - - - - - - - -
  ##      OO
- - - - - - - - -
    ##      OO
==================
      OO      OO
- - - - - - - - -
OO      ##      HH
- - - - - - - - -
  ##      OO
------------------

```

In this example we hava 9 holes, which is not multiple of 7. So your pool of holes to use is size 14 with 8 (OO), 4(##), 2(HH). You may use any holes from it to fill road.

```
------------------
OO  OO  OO  OO  OO
==================
  OO  OO  OO  ##
------------------

```

Another corner example. Road can have only 3 holes. So pool is 7: 4(OO), 2(##), 1(HH). Again, any can be used:

```
------
##
- - -
  ##
======
    HH
- - -

------

```

## Other rules

1. You may change the appearance of holes to two of any other character, except -, = and whitespace. Just mention it in your answer.
2. It's , so make your code as compact as possible.

# Answer
## JavaScript (ES6), 158 bytes

```
f=
(w,l)=>[...Array(l*4+1)].map((_,i)=>[...Array(w)].map((_,j)=>i%2?(i>>1)-j&3?`  `:s[n%7]+s[n++%7]:i/2%l?`- `:i-l-l?`--`:`==`).join``,n=0,s=`O#OHO#O`).join`\n`
```

```
<div oninput=o.textContent=f(+w.value,+l.value)><input id=w type=number min=1 value=1><input id=l type=number min=1 value=1><pre id=o>--
OO
==

--
```
> 1 votes

# Answer
# Python 2, ~~229~~ ~~213~~ ~~204~~ ~~200~~ 188 bytes

```
lambda n,l:"\n".join(["-"*l]+[i%2and"".join(j-i/2&1+2*(n>1)and"  "or x.append(1)or"H0000##"[len(x)%7]*2for j in range(l/2))or((i-n*2and"- "or"=")*l)[:l]for i in range(1,n*4)]+["-"*l])
x=[]

```

Try it online!

---

My longest answer so far
> 5 votes

# Answer
# PHP, ~~160 186 178 173 170 168~~ 163 bytes

```
for(;$y<=2*$h=2*$argv[2];$y+=print"
")for($x=0;$x++<$w=$argv[1];)echo$y%2?($x+$y+$h*$y)%($h+2)>1|$x>($w&~1)?" ":UBUGUBU[$n++%14/2]:" -="[$y%(2*$h)?$y-$h?$x&1:2:1];

```

takes input from command line; Run with `-nr`. The holes are `G`ood, `B`ad and `U`gly.

**breakdown**

```
for(;$y<=2*$h=2*$argv[2];$y+=print"\n") # loop throug lines and lanes, post-print newline
    for($x=0;$x++<$w=$argv[1];)echo         # loop from left to right and print ...
        $y%2
        ?                                       # lanes:
            ($x+$y+$h*$y)%($h+2)>1                  # if not the position for a hole
            |$x>($w&~1)                             # or too close to the end
            ?" "                                    # then space
            :UBUGUBU[$n++%14/2]                     # else hole
    :" -="[                                     # or lines:
        $y%(2*$h)                               # if neither top nor bottom line
            ?   $y-$h                               # if not middle line
                ?   $x&1                                # then "- "
                :   2                                   # else "=="
            :   1                                   # else "--"
    ]
    ;

```
* `($x-$y)+$y*($h+2)` --\> `($x+$y+$h*$y)`
* `$w<$x+1&&$w&1` --\> `$x>$w-($w&1)` --\> `$x>($w&~1)`
* `($y%(2*$h)?$y-$h?" -"[$x&1]:"=":"-")` --\>
`($y%(2*$h)?" -="[$y-$h?$x&1:2]:"-")` (thanks @Christoph) --\>
`" -="[$y%(2*$h)?$y-$h?$x&1:2:1]`
> 2 votes

# Answer
## Batch, 380 bytes

```
@echo off
set h=O#OHO#O
set r=
for /l %%i in (1,1,%1)do call set r=--%%r%%
set/an=%2*2-1
for /l %%j in (0,1,%n%)do call:c %1 %2 %%j
echo %r%
exit/b
:c
if %3==0 (echo %r%)else if %3==%2 (echo %r:-==%)else echo %r:--=- %
set s=
for /l %%i in (1,1,%1)do set/an=%3-%%i^&3&call:l
echo(%s%
exit/b
:l
if %n%==3 (set s=%s%%h:~,1%%h:~,1%&set h=%h:~1%%h:~,1%)else set s=%s%

```
> 1 votes

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


title: Count the ASCII hamantaschen!

text:
# Question
Title: Count the ASCII hamantaschen!
Today is Purim on which one custom is to give out triangle-shaped cookies with filling called *hamantaschen* (singular: *hamantasch*). Another custom is to drink heavily.

I'm not the most perfect baker.... I have so many irregularly-sized hamantaschen to give out and so many friends to give them to! If I sent you a picture of my cookies, can you tell me how many I have of which size and filling? But because it's Purim and I'm too drunk to read much code, it needs to be as small code as you can make.

## Definitions

### Size

A hamantasch can be any **size**. The smallest hamantasch is size 1 and looks like these:

```
/\  --
--  \/

```

Sometimes, multiple hamantaschen can **overlap**. The shape below counts as two hamantaschen (one size 1, one size 2):

```
 /\
/\ \
----

```

Some hamantaschen have **filling**. This will be indicated by filling all whitespace inside with a character. Note that size 1 hamantaschen cannot have filling.

We will **name** hamantaschen based on filling and size. Let's use the format `<filling> <size>` and if unfilled, `- <size>` (you can use a space instead of a `-`, but markdown doesn't like that).

Here are a `. 2`, a `. 4`, and a `- 3`:

```
          /\
         /./\
 ----   /./  \
 \../  /./    \
  \/   --------

```

These are a `@ 3`, a `. 2` and a `- 4`:

```
          /\
         / /\
  /\    / /@@\
 /..\  / /@@@@\
 ----  --------

```

Here's something more difficult. See how the `& 2` has less filling than you've come to expect due to the slant from the overlapping `- 3`? It has a `- 1`, a `& 2` a `- 3` and a `& 4`:

```
--------
\   \/&/
 \  /\/
  \/&/
   \/

```

## Input

You will be given a text file or single string of hamantaschen (optional trailing newline and optionally padded trailing whitespace to be even).

### Limits

* You can expect the string to be **valid** \- that is, every non-whitespace character contributes to a deliciously sweet hamantasch (why waste dough?).
* You can also expect it to be **properly filled** or not - that is, each hamantasch it will be entirely filled with a consistent ASCII character - ASCII 32 for unfilled, or anything 32..127 for filled (excluding `/`, `\` and `-`).
* These hamantaschen are **not stacked** in 3-space. All `/` and `\` will be visible. All `-` that are not blocked by `/` and `\` will be visible. Filling comes very last.
* All hamantaschen will have at least **half of their horizontal line** (rounding up) visible.
* Any contiguous block of **filling only fills the smallest hamantasch** that surrounds it.

## Output

Return a list of "names" of all the hamantaschen that can be found meeting the above criteria. The output can be in whatever form you'd like (a string, a hash, stdout, etc).

## Test cases

### Test case #1

Input #1:

```
          /\
         / /\
  /\    / /@@\
 /..\  / /@@@@\
 ----  --------
    /\
   /**\
  /*/\*\
 /*/..\*\
 --------

```

Output #1:

```
. 2
. 2
- 4
@ 3
* 4

```

### Test Case #2

Input #2:

```
  /\----
 /\/\*\/
/ /\d\/
------

```

Output #2:

```
- 3
- 2
d 2
- 1
* 2
- 1

```

### Test #3

Input #3:

```
----
\/\/
/\/\  /\
---- /::\
     ----

```

Output #3:

```
- 1
- 1
- 2
- 1
- 1
- 2
: 2

```

### Test #4

Input #4:

```
 /\/\
/ /\$\
-/--/\\
 --/--\
  /xxx/\
 /xxx/##\
 ---/----\
   /      \
   --------

```

Output #4:

```
$ 2
x 4
- 3
- 2
- 4
- 1
- 1
# 2

```

### Invalid Test Case #5

Input:

```
/\
\/

```

Output:

You do not need to handle this.

# Answer
> 4 votes
# C#, ~~496~~ 452 bytes

***Edit:*** *found a bug with bounds checking... but also striped a load of bytes having been forced to understand my own code. Unrolling the local function helped a bit, and removed the C# 7 specific code. This question has been a lot of fun.*

```
using C=System.Console;class P{static void Main(){string D="",L;int W=0,H=0,z=0,d,q,c,j,b;for(;(L=C.ReadLine())!=null;H+=W=L.Length)D+=L;var B=new int[H];for(d=W;(d=-d)>0||++z<H*H;)for(c=1,q=z%H;c<=z/H&q%W+c<W&q>=d&q<H+d&&D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47);q-=d+1,c+=2){for(b=0;j>q;)b+=D[--j-d]==45?2:0;for(char h='-',e;c==z/H&b>c;C.WriteLine(h+" "+c/2))for(b=c++;b>1;j=q+=d+1,b-=2)for(;j<q+b;)B[j]=h=B[j]<1&h==45&(e=D[j++])!=47&e!=92&e>32?e:h;}}}

```

Try it Online

Complete program, expects space-padded input to standard in, outputs to standard out. The output is one entry per line, with trailing line feed. Cookies are outputted in increasing size order, upper-left most first. It took me a good while to understand the rules, but I think it passes all the examples provided.

It works by repeatedly searching the entire grid for valid Hamantaschen, incrementing the 'allowed' size. For each cell, it checks up and down, following the `\` and `/` on either side as far as it can. If it notices that the next row has lots of `-`, and the current size is the 'allowed' size, then it determines the filling and prints out the entry.

The filling is found by exploring the entire space of the cookie, looking for an 'unused' cell. When an unused cell is found, it is marked as used (since we increase the allowed size, we know we are the smallest cookie that contains it), and we record the filling.

Formatted and commented code:

```
using C=System.Console;

class P
{
    static void Main()
    {
        //   32
        // - 45
        // / 47
        // \ 92
        // range 32..127 (no mod for you)

        string D="", // the whole map
            L; // initally each line of the map, later each line of output

        int W=0, // width
            H=0, // length (width * height)
            z=0, // search tracker
            d, // check direction (this is backwards (1 byte saving!))
            q, // check tracker
            c, // counter (truely, this is the distance from the right to the left)
            //M, // c max (now inlined as z/H)
            j, // horiontal tracker
            b; // - count, and reverse counter

        // read map and width
        for(;(L=C.ReadLine())!=null; // read a line, while we can
                H+=W=L.Length) // record the width, and increment height
            D+=L; // add the line to the map

        var B=new int[H]; // whether this filling has been used already (0 -> false, >0 -> true)

        for(d=W; // init direction
            (d=-d)>0|| // swap direction, else increment z (this allows us to run the check for the same z twice with opposite direction)
            ++z<H*H; // for all M, for all q (z<H -> M=z/H=0 -> no valid cookies, so we can safetly skip them)
            )
            for(//M=z/H, // c allow (now inlined)
                c=1, // reset counter
                q=z%H; // note position
                c<=z/H& // counter check
                // no need for a left check: if we run off the left end, then the right check will necessarily fail
                q%W+c<W& // right check
                q>=d& // high check
                q<H+d&& // low check (short-circuit lookups)
                D[q]==(d>0?92:47)&D[j=q+c]==(d<0?92:47); // /\ or \/ check, and set j=q+c
                    q-=d+1, // move left tracker
                    c+=2) // increase counter (move right tracker)
            {
                // count the number of '-' into b
                for(b=0; // zero b
                    j>q; // for each element in the row below
                        ) // empty
                    b+=D[--j-d]==45?2:0; // add 2 to b if we tap a '-'

                // j = q

                // check valid before looking up cHaracter (so we don't mark unused stuff as taken)
                // if we are at the current max count, and we have enough -, then we are valid and should be commited
                for( // this runs either one or zero times, we only have a for here (rather than an if) so we can ditch a pair of braces
                    char h='-', // default filling
                         e; // filling we are considering
                    c==z/H&b>c;
                        C.WriteLine(h+" "+c/2)) // print filling and count
                    // continuously compute character
                    for(b=c++; // count b backwards, starting from c (add 1 to c so we can /2 in print)
                        b>1;j=q+=d+1,b-=2) // count q backwards toward z%H (where q came from), and b backwards toward 1 (for each row)
                        for(;j<q+b;) // for each cell in row
                            B[j]= // mark cell as taken (h,e > 0)
                            h= // record filling
                                B[j]<1& // check cell not already used
                                h==45& // '-'
                                (e=D[j++])!=47& // '/'
                                e!=92& // '\'
                                e>32 // ' '
                                ?e:h; // take first filling we can
                    // c runs out after this (exists both loops), so no need to action
            }
    }
}

```

Outputs for the 4 test cases:

```
testcase #1
. 2
. 2
@ 3
- 4
* 4

testcase #2
- 1
- 1
- 2
d 2
* 2
- 3

testcase #3
- 1
- 1
- 1
- 1
- 2
- 2
: 2

testcase #4
- 1
- 1
- 2
$ 2
# 2
- 3
x 4
- 4

```

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


title: How far from the exterior?

text:
# Question
Title: How far from the exterior?
Take a 2D region of space divided into axis aligned unit square elements with their centers aligned at integer intervals. An edge is said to be internal if it is shared by two elements, otherwise it is an external edge.

Your goal is to find the minimum number of neighboring elements which must be traversed to reach an exterior edge starting from the center of each element, known as the `traversal distance`, or `distance` for short. You may only traverse through an edge (i.e. no corner cutting/diagonal movement). Note that "exterior elements" (elements which have at least one external edge) are considered to need to traverse `0` neighboring elements to reach an exterior edge..

# Input

The input is a list of non-negative integer pair coordinates denoting the (x,y) of the center of all elements. It is assumed there are no overlapping elements (i.e. an x/y pair uniquely identifies an element). You may **not** assume anything about the element input order.

You are welcome to transform the origin of the input to any location (e.g. 0,0 or 1,1, etc.).

You may assume that all input elements are connected, or in other words it is possible to travel from any one element to any other element using the rules above. Note that this does not mean that the 2D region is simply connected; it may have holes inside of it.

Example: the following is an invalid input.

```
0,0
2,0

```

error checking is not required.

The input may be from any source (file, stdio, function parameter, etc.)

# Output

The output should be a list of coordinates identifying each element, and the corresponding integer distance traversed to get to an edge. The output may be in any element order desired (e.g. you need not output elements in the same order received as inputs).

The output may be to any source (file, stdio, function return value, etc.)

Any output which matches the coordinate of the element with it's exterior distance is fine, e.g. all of these are fine:

```
x,y: distance
...

[((x,y), distance), ...]

[(x,y,distance), ...]

```

# Examples

Text example inputs are in the form `x,y`, with one element per line; you are welcome to reshape this into a convenient input format (see input format rules).

Text example outputs are in the format `x,y: distance`, with one element per line; again, you are welcome to reshape this into a convenient ouput format (see output format rules).

Graphical figures have the lower-left bound as (0,0), and the numbers inside represent the expected minimum distance traveled to reach an exterior edge. Note that these figures are purely for demonstration purposes only; your program does not need to output these.

## Example 1

**input:**

```
1,0
3,0
0,1
1,2
1,1
2,1
4,3
3,1
2,2
2,3
3,2
3,3

```

**Output:**

```
1,0: 0
3,0: 0
0,1: 0
1,2: 0
1,1: 1
2,1: 0
4,3: 0
3,1: 0
2,2: 1
2,3: 0
3,2: 0
3,3: 0

```

**graphical representation:**

## Example 2

**input:**

```
4,0
1,1
3,1
4,1
5,1
6,1
0,2
1,2
2,2
3,2
4,2
5,2
6,2
7,2
1,3
2,3
3,3
4,3
5,3
6,3
7,3
8,3
2,4
3,4
4,4
5,4
6,4
3,5
4,5
5,5

```

**output:**

```
4,0: 0
1,1: 0
3,1: 0
4,1: 1
5,1: 0
6,1: 0
0,2: 0
1,2: 1
2,2: 0
3,2: 1
4,2: 2
5,2: 1
6,2: 1
7,2: 0
1,3: 0
2,3: 1
3,3: 2
4,3: 2
5,3: 2
6,3: 1
7,3: 0
8,3: 0
2,4: 0
3,4: 1
4,4: 1
5,4: 1
6,4: 0
3,5: 0
4,5: 0
5,5: 0

```

**graphical representation:**

## Example 3

**input:**

```
4,0
4,1
1,2
3,2
4,2
5,2
6,2
8,2
0,3
1,3
2,3
3,3
4,3
5,3
6,3
7,3
8,3
9,3
1,4
2,4
3,4
4,4
5,4
6,4
7,4
8,4
9,4
2,5
3,5
4,5
5,5
6,5
9,5
10,5
11,5
3,6
4,6
5,6
9,6
10,6
11,6
6,7
7,7
8,7
9,7
10,7
11,7

```

**output:**

```
4,0: 0
4,1: 0
1,2: 0
3,2: 0
4,2: 1
5,2: 0
6,2: 0
8,2: 0
0,3: 0
1,3: 1
2,3: 0
3,3: 1
4,3: 2
5,3: 1
6,3: 1
7,3: 0
8,3: 1
9,3: 0
1,4: 0
2,4: 1
3,4: 2
4,4: 2
5,4: 2
6,4: 1
7,4: 0
8,4: 0
9,4: 0
2,5: 0
3,5: 1
4,5: 1
5,5: 1
6,5: 0
9,5: 0
10,5: 0
11,5: 0
3,6: 0
4,6: 0
5,6: 0
9,6: 0
10,6: 1
11,6: 0
6,7: 0
7,7: 0
8,7: 0
9,7: 0
10,7: 0
11,7: 0

```

**graphical representation:**

# Scoring

This is code golf. Shortest code in bytes wins. Standard loopholes apply. Any built-ins other than those specifically designed to solve this problem are allowed.

# Answer
> 2 votes
# MATLAB/Octave, 143 bytes

```
function [v,x,y]=d(x,y)R=S=zeros(max(y+3),max(x+3));i=sub2ind(size(S),y+2,x+2);S(i)=1;while nnz(S=imerode(S,strel('disk',1,0)))R+=S;end;v=R(i);

```

## Ungolfed

```
function [v,x,y]=d(x,y)
  R=S=zeros(max(y+3),max(x+3));
  i=sub2ind(size(S),y+2,x+2);
  S(i)=1;
  while nnz(S=imerode(S,strel('disk',1,0)))
    R+=S;
  end;
  v=R(i);

```

## Explanation

Create **S**ource and **R**esult matrices of appropriate size, filled with zeros.

```
R=S=zeros(max(y+3),max(x+3));

```

Calculate the linear indices that correspond to the `xy`-pairs, with one element padding at the borders.

```
i=sub2ind(size(S),y+2,x+2);

```

Draw the structure.

```
S(i)=1;

```

`S` is shown here for **Example 2**:

```
0   0   0   0   0   0   0   0   0   0   0
0   0   0   0   0   1   0   0   0   0   0
0   0   1   0   1   1   1   1   0   0   0
0   1   1   1   1   1   1   1   1   0   0
0   0   1   1   1   1   1   1   1   1   0
0   0   0   1   1   1   1   1   0   0   0
0   0   0   0   1   1   1   0   0   0   0
0   0   0   0   0   0   0   0   0   0   0

```

Remove all border elements by image erosion

```
S=imerode(S,strel('disk',1,0))

```

using the structuring element *disk with radius 1*:

```
0   1   0
1   1   1
0   1   0

```

If diagonal movement was allowed, we would instead use the rectangle:

```
1   1   1
1   1   1
1   1   1

```

Then, increment the result for all non-border elements

```
R+=S;

```

and loop until the image is completely eroded.

```
while nnz(S)

```

Return the result for each `xy`-pair.

```
v=R(i);

```

# Answer
> 2 votes
# MATL, ~~38~~ ~~37~~ ~~36~~ 33 bytes

```
1Z?t"tX@<~5Bt!Z~2X53$Y+4=+]3#fqhh

```

This uses current version (15.0.0) of the language/compiler.

Input format is: one array with *x* values and one array with *y* values. Input and output are 1-based. So the test cases have the following inputs:

```
[2 4 1 2 2 3 5 4 3 3 4 4]
[1 1 2 3 2 2 4 2 3 4 3 4]

[5 2 4 5 6 7 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 9 3 4 5 6 7 4 5 6]
[1 2 2 2 2 2 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 5 5 5 5 5 6 6 6]

[5 5 2 4 5 6 7 9 1 2 3 4 5 6 7 8 9 10 2 3 4 5 6 7 8 9 10 3 4 5 6 7 10 11 12 4 5 6 10 11 12 7 8 9 10 11 12]
[1 2 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 7 7 7 7 7 7 8 8 8 8 8 8]

```

**Try it online!**

### Explanation

A matrix is initially built with 1 at the input positions and 0 otherwise. Then a convolution is applied with a "North, East, South, West" mask (`[0 1 0; 1 0 1; 0 1 0]`), and the result at each position is compared with 4. A result of 4 means that that position is surrounded by other points, and so has distance-to-exterior at least 1. The result (0 or 1 for each point) is added to the original matrix. Those positions now contain 2 (at the end of the process the matrix will be decremented by 1).

The convolution process is iterated. For the next iteration, the input of the convolution is the accumulated matrix thresholded with 2; that is, values lower than 2 are set to 0. The result of the convolution indicates which points have distance at least 2 (all their neighbours have distance 1).

The number of iterations is chosen, for convenience, as the number of columns of the input matrix. This is sufficient (in fact, the maximum required number of iterations is half the minimum matrix dimension). The last iterations may be useless, but do no harm (they do simply add 0 to all points).

At the end of the process, 1 is subtracted from the result, because positions with value *k* have distance *k*-1 to the exterior. The coordinates and values of all positions is extracted and displayed.

```
           % take x and y implicitly
1          % push 1
Z?         % build sparse matrix from that x, y indices with 1 as value
t          % duplicate
"          % for each column of that matrix
  t        %   duplicate
  X@       %   push iteration index
  <~       %   true for matrix entries that are >= iteration index
  5B       %   5 in binary: row vector [1 0 1]
  t!       %   duplicate and transpose into a column vector
  Z~       %   element-wise XOR with broadcast: gives desired mask,
           %   [0 1 0; 1 0 1; 0 1 0]
  2X53$Y+  %   2D convolution. Output has same size as input
  4=       %   compare with 4: are all neighbouring positions occupied?
  +        %   add to accumulated matrix from previous iteration
]          % end for each
3#f        % extract row index, column index and value for nonzero
           % entries. In this case all entries are nonzero
q          % subtract 1 to value to yield distance to exterior
hh         % concatenate vertically twice
           % display implicitly

```

# Answer
> 2 votes
# Pyth, 26 bytes

```
V]MQNf>*4Nl=Nsmfq1.a,dYQN0

```

Example 2

The output format I used is:

```
[[4, 3]]
2

```

That is, a list containing the point, followed by the distance from the exterior.

The code works by using a currently reached set, for each point filtering the input for all points exactly distance 1 away from that point, and checking whether the resultant number of points is 4 times as many as the starting number, and repeating until it's not. When started at a given point, this gives how far that point is from the exterior.

# Answer
> 1 votes
# Python 3, ~~180~~ ~~166~~ 160 bytes

```
def f(l,d=0):
 l=set(l);
 if l:i={(a,b)for a,b in l if all([x in l for x in[(a+1,b),(a-1,b),(a,b+1),(a,b-1)]])};return{(c,d)for c in l-i}|f(i,d+1)
 return set()

```

We know that if a coordinate has less than four neighbours, it must be on the "exterior". Therefore, we can repeatedly strip the exterior cells and assign to them a distance equal the the number of iterations/depth of recursion in this case.

Definitely think there's room for improvement - What's the best way of checking of adjacent neighbours?

edit: I should be allowed to accept a list of pairs as tuples.

# Answer
> 0 votes
# PHP, 316 Bytes

```
<?preg_match_all("#^(\d+),(\d+)#m",$_GET[i],$t);foreach($t[1]as$k=>$v)$a[$v][$t[2][$k]]=0;function w($x,$y){global$a;return isset($a[$x][$y])?$a[$x][$y]:-1;};for(;$z++<max($t[2]);$o=$s,$s="")foreach($a as$x=>$b)foreach($b as$y=>$c)$s.="\n$x,$y: ".$a[$x][$y]=1+min(w($x+1,$y),w($x-1,$y),w($x,$y-1),w($x,$y+1));echo$o;

```

Online Version

## Breakdown

```
preg_match_all("#^(\d+),(\d+)#m",$_GET[i],$t);
foreach($t[1]as$k=>$v)
$a[$v][$t[2][$k]]=0;  # make a 2 D array
function w($x,$y){global$a;return isset($a[$x][$y])?$a[$x][$y]:-1;};# check the neighbours
for(;$z++<max($t[2]);$o=$s,$s="") # stored the last loop string first run make possible to 1 and so on
foreach($a as$x=>$b) # x values
foreach($b as$y=>$c) # y values
$s.="\n$x,$y: ".$a[$x][$y]=1+min(w($x+1,$y),w($x-1,$y),w($x,$y-1),w($x,$y+1)); # concanate array item x+y+value
echo$o; #Output

```

## Visualize as Ascii chars

```
ksort($a);
foreach($a as$x=>$b){
for($y=0;$y<=max($t[2]);$y++)
echo isset($a[$x][$y])?$a[$x][$y]:" ";
#The better way would be make a SVG and use the text element and use a factor
#echo '<text x="'.($x*$factor).'" y="'.($y*$factor).'">'.$a[$x][$y].'</text>';
echo"\n";}

```

---
Tags: code-golf, math, geometry, grid, graph-theory
---