title: Numbers on a Chain

text:
# Question
Title: Numbers on a Chain
Some positive integers can be shown to have a property called *Chain divisibility.* For a number to be chain-divisible by *n*, it must fulfil three requirements:

1. > Each digit divides the number formed by the *n* digits that follow it.

For example, the number 7143 is chain-divisible by 2 because 7 divides 14 and 1 divides 43. It is *not* chain-divisible by 3 because 7 does not divide 143.
2. > Each subsequence taken into account for divisibility must not have leading zeros.

For instance, the number 14208 is not chain-divisible by 2 because 08 has a leading zero. It is, however, chain-divisible by 3, because 208 does not have a leading zero.
3. > All digits in the number must be unique.

For instance, the number 14280 is chain-divisible by 2, 3 and 4. If my explanation of chain divisibility is unclear please ask questions in the comments.

**Input**

The input to the program consists of a single integer `n`, followed by a space, then a number that has had certain digits replaced by underscores. For example, the following is a possible input:

```
3 6__2__4508

```

*n* will be greater than 1. The number will never be entirely underscores. You are not guaranteed that the first digit is not an underscore. The first digit will never be 0. *n* will never be greater or equal to the number of digits in the number.

**Output**

Output the number, with the digits replaced by integers such that the resulting number is chain-divisible by *n*. If more than one way of completing the chain-divisible number exists, any may be used as output. If there is no numbers that can complete it, output `no answer`. For instance, the output of the example input could be:

```
6132794508

```

This is code golf, so the shortest code wins.

# Answer
# Bash+coreutils, 197 bytes

```
for i in $(eval printf '%s\\n' ${2//_/{0..9\}}|grep -vP '(\d).*\1');{
for((f=d=0;d<${#i}-$1;d++));{
((${i:d+1:1}==0||10#${i:d+1:$1}%${i:d:1}))&&f=
}
[ $f ]&&echo $i&&((c++))
}
((c))||echo no answer

```

### Output:

```
$ ./chain.sh 3 714_
7140
$ ./chain.sh 2 7141
no answer
$ ./chain.sh 2 14208
no answer
$ ./chain.sh 3 14208
14208
$ ./chain.sh 2 1_208
no answer
$ ./chain.sh 3 1_208
14208
$ ./chain.sh 2 6__2__4508
no answer
$ ./chain.sh 3 6__2__4508
6132794508
$

```

### Explanation

* The parameter expansion `${2//_/{0..9\}}` replaces all underscores with `{0..9}`.
* The resulting string is `eval`ed to expand all these brace expressions.
* The `grep` weeds out all possibilities where there are any repeated digits.
* Then each remaining number is checked, digit-by-digit for conditions 1 and 2.
> 5 votes

# Answer
## ~~Mathematica~~ Ruby, ~~349~~ ~~224~~ 229 bytes

```
n=$*[0].to_i
r='no answer'
(?0..?9).to_a.permutation($*[1].count'_'){|q|s=$*[1]
q.map{|d|s=s.sub'_',d}
c=s.chars
(t=1
c.each_cons(n+1){|c|e=c.shift.to_i
(t=!t
break)if e<1||c[0]==?0||c.join.to_i%e>0}
(r=s)if t)if c==c.uniq}
$><<r

```

This is a very naive implementation. I count the number of underscores, and then simply create a list of all digit-permutations of that length, to brute force every possible combination. This will perform horribly for larger numbers of underscores, but this is code golf and not fastest-code. :)

**Edit:** Ported this from Mathematica. See the edit history for the original version.

**Edit:** Fixed leading underscore cases.
> 2 votes

# Answer
# Python - ~~239~~ 267

```
from itertools import*
T=raw_input()
n=int(T[0])
N=len(T)-2
J=''.join
for i in permutations('0123456789',N):
 if all([S in[I,'_']for S,I in zip(T[2:],i)])*all([i[j]>'0'<i[j+1]and int(J(i[j+1:j+n+1]))%int(i[j])<1for j in range(N-n)]):print J(i);exit()
print'no answer'

```

Slow, but short. Simply compare every possible N-digit permutation with the given pattern and check all requirements. I've tested it only with 7 or 8 digits. Should work for 9 or 10 as well, but will take quite a while.

**Edit:** I added the missing default output "no answer".
> 2 votes

# Answer
## Java, 421

```
class C{static int n;public static void main(String[]a){n=new Short(a[0]);f(a[1]);System.out.print("no answer");}static void f(String s){if(s.contains("_"))for(int i=0;i<=9;i++)f(s.replaceFirst("_",i+""));else{for(int i=1;i<s.length()-n+1;){String t=s.substring(i,i+n);if(t.charAt(0)<49||new Long(t)%new Long(s.substring(i-1,i++))>0||s.chars().distinct().count()<s.length())return;}System.out.print(s);System.exit(0);}}}

```

Less golfed, with explanation:

```
class C {

    static int n;

    public static void main(String[] a) {
        n = new Short(a[0]);
        f(a[1]);
        System.out.print("no answer");
    }

    /**
     * This method is called recursively, each time with
     * another underscore replaced by a digit, for all possible digits.
     * If there is a solution, the method prints it and exits the program.
     * Otherwise, it returns.
     */
    static void f(String s) {
        if (s.contains("_")) {
            for (int i = 0; i <= 9; i++) {
                f(s.replaceFirst("_", i + ""));
            }
        } else {
            for (int i = 1; i < s.length() - n + 1;) {
                String t = s.substring(i, i + n);       // on each substring...
                if (                                    // test for the three rules
                    t.charAt(0) < 49 ||
                    new Long(t) % new Long(s.substring(i - 1, i++)) > 0 ||
                    s.chars().distinct().count() < s.length()
                ) {
                    return;            // a rule was broken
                }
            }
            System.out.print(s);       // if we made it this far, it's a success!
            System.exit(0);
        }
    }
}

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 179 bytes

```
d←≠⊆⊢
p←≢¨'|'d'\d'⎕R'|'⊢n←2⊃a←' 'd⍞
⊃(t/⍨t≡¨∪¨t←r/⍨(⍎⊃a)∘{(∧/'0'≠⊃¨x)>1∊×(⊖⍺↓⊖⍎¨⍵)|⍎¨x←1↓⍺,/⍵}¨r←{×≢p:{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨(⊂p/⍕0),⍕¨{⍵~⍳⌊⊃⌽⍵÷10}⍳1-⍨10*+/p⋄⊂n}0),⊂'no answer'

```

Try it online!

-4 bytes from dzaima.

-9 bytes from ngn.

-4 bytes from Adam.

Golfed by a lot at The APL Orchard.

## Explanation

`d←≠⊆⊢` splitting function: takes character on left, string on right.

`p←≢¨'|'d'\d'⎕R'|'⊢n←2⊃a←' 'd⍞` a multiple assignment:

`a←' 'd⍞` a - holds input split on spaces.

`n←2⊃` n - holds the number string.

`p←≢¨'|'d'\d'⎕R'|'⊢` p - holds the length of each blank space.

### Part 1: generating the required number partitions

`r←{×≢p:{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨(⊂p/⍕0),⍕¨{⍵~⍳⌊⊃⌽⍵÷10}⍳1-⍨10*+/p⋄⊂n}0`

`×≢p: ... ⋄⊂n` If there are no underscores, return the number, wrapped.

Otherwise:

`⍳1-⍨10*+/p` generate range 1..(9 repeated sum(p) times)

`{⍵~⍳⌊⊃⌽⍵÷10}` remove 1..10^(sum(p)-1), getting all sum(p) digit numbers.

`⍕¨` convert each to string

`(⊂p/⍕0),` prepend 0 repeated sum(p) times to it

`{⍕⍎∊⍉↑('_'d n)(⍵⊆⍨p/⍳≢p)}¨` execute the following for each no. string:

`(⍵⊆⍨p/⍳≢p)` split into pieces of sizes in p

`↑('_'d n)` add the input to it and make a 2xn matrix

`⍕⍎∊⍉` transpose the fillers and enlist them, then remove all spaces using `⍕⍎`

`r/⍨` filter this list by:

### Part 2: checking chain divisibility

`(⍎⊃a)∘{(∧/'0'≠⊃¨x)>1∊×(⊖⍺↓⊖⍎¨⍵)|⍎¨x←1↓⍺,/⍵}¨`

`(⍎⊃a)∘{...}` execute the following, using the first number as constant left argument:

`⍎¨x←1↓⍺,/⍵` store overlapping groups of 3 in x, convert to int

`|` modulo:

`(⊖⍺↓⊖⍎¨⍵)` list of numbers they should be divisible by

`1∊×` are any of them truthy?

`>` check if the result is lesser than:

`(∧/'0'≠⊃¨x)` whether any of the groups have a leading zero

filter complete!

### Part 3: checking uniqueness

`t≡¨∪¨t←` boolean mask for whether each number matches itself uniquified.

`t/⍨` filter to get the final array

`⊃(...),⊂'no answer'` pick the first item of the result with 'no answer' appended.

if there are no results, it will default to that.
> 1 votes

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


# Question
Title: Generating versions of an array with elements changed in ruby
I'm new to code golf challenges. My problem came up in Advent of Code 2020 Day 8

The input is an array of arrays. In part two of the problem one needs to run several trials to produce a result by changing an element in the input array. My current code is this (comments added to explain what's going on):

```
p input.each_with_index { |val, i|
  next if val[0] != :acc # not all elements need to be experimented with
  changed = input.dup # clone input to make a change
  # change the first element of the value at input position i (but keep the rest)
  changed[i] = val.dup.tap { |v| v[0] = v[0] == :nop ? :jmp : :nop }
  result = try_with(changed) # run the experiment
  break result if result[1] == :terminate # success condition
end

```

So, that's quite a lot of code for something relatively simple. Can I make it shorter? Can I have a simple generator that produces different versions of the same array?

My complete code for day 8 is here

**Edit:**

As suggested in the comments, I'll try to put the problem my snippet is solving as a code golf challenge (note that this is just my snippet):

In ruby you have `input`: an array of instructions. Each element of `input` is another array of two elements, where the first is a symbol (the instruction name) which is one three: `:acc`, `:jmp`, or `:nop`, and the second is an integer (the instruction argument).

You also have a function `try_with` which works with such an array, executes the instructions and returns `[n, :terminate]` if the program terminates or `[n, :loop]` if the program is an endless loop. `n` is the value of the accumulator after the execution.

The original input is a loop. If you change *one* of the instructions in the input array from `:nop` to `:jmp` **or** from `:jmp` to `:nop`, and keep the argument, it will result in a terminating program. What is the value of the accumulator after you find and execute the terminating program?

**The original AOC2008D8 problem**

You have a file with valid assembly. Each line is a three character instruction and a (possibly negative) integer argument separated by a single space. Example

```
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6

```

Instructions are `acc` add arg to accumulator and increment ip, `jmp` add arg to ip, `nop` ignore arg and just increment ip.

Then... what I said above about the snippet-only problem

Changing the next-to-last line in the example from `jmp` to `nop` results in a termination with acc value: 8

# Answer
# Ruby, <sup>~~102~~ ~~99~~ ~~98~~</sup> 95 bytes

```
(k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp]until(r=try_with k||$:)[1]>:t;p r

```

Try it online!

I assume that `input` and `try_with` are mandatory names for the Advent of Code challenge. If not, the code can obviously be even shorter. Here, I also assume that the `try_with` method will accept invalid input, that is, an array whose elements are not of the form `[:instruction, integer]`. See below for a slightly longer version in case `try_with` strictly requires valid input.

See commented code below for a complete list of ideas used. Apart from generic code-golf tips such as 'use short variable names', or common Ruby tips such as 'omit parentheses in method calls', here are some specific tips for the problem posed:

* Instead of `each_with_index`, use a counter variable ~~together with an anonymous lambda and `redo`~~ together with `until` (or `while`) in modifier form. For the counter, a good choice in this case is the predefined global variable `$.`, which is initialised to `0`. Processing the `input` array in reverse (by decrementing `$.` in place) is the best approach. Incrementing `$.` in place doesn't work (because `input[0]` would be skipped); incrementing `$.` at the end of the loop would cost bytes.
* Only call `dup` at the lowest level, that is, on the elements of `input`, not on `input` itself.
* Lexicographical comparisons work with symbols, so `>:t` is better than `== :terminate`, for example.
* It turns out to be slightly shorter to use the spaceship operator `<=>` instead of a ternary conditional to choose between instructions. In the code, `k[$.][0]<=>:jmp` returns `-1` if the current instruction is `:acc`, `0` if it is `:jmp`, and `1` if it is `:nop`. Use these values to index into an array of the three symbols, ordered such that the correct replacement is chosen.

```
(k=                # use parentheses to define variables inline
   input.map &:dup # only duplicate the lowest-level arrays, and do all at once
)[$.-=1][0]        # use $. as a counter and decrement in place
=%i[nop jmp acc][k[$.][0]<=>:jmp] # use the spaceship operator to choose between instructions
until              # loop with until
(r=try_with k      # omit parentheses in the call to try_with
||$:)[1]           # on the first iteration (only), k is nil so pass the predefined array $: to try_with as dummy input
>:t;               # test for >:t instead of ==:terminate
p r                # print the result

```

---

# Ruby, 98 bytes

```
p->{(k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp];(r=try_with k)[1]>:t||redo;r}[]

```

Try it online!

Use this version if `try_with` rejects `$:` as valid input. Here, we iterate using an anonymous lambda and `redo`.
> 6 votes

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


title: The Holy Numbers

text:
# Question
Title: The Holy Numbers
In many fonts (specifically in the Consolas font), 5 out of the 10 decimal digits have "holes" in them. We will call these holy digits:

```
46890

```

The 5 unholy digits are thus:

```
12357

```

An integer may thus be classified as "holy" if it only contains holy digits, and "unholy" otherwise. Because `-` is unholy, no negative integers can be holy.

Holy integers may be further classified based on how many holes they have. For example, the following digits have a holiness of 1:

```
469

```

And these digits have a holiness of 2:

```
80

```

We say that the overall holiness of an integer is the sum of the holiness of its digits. Therefore, `80` would have a holiness of 4, and `99` would have a holiness of 2.

## The Challenge

Given two integers `n > 0` and `h > 0`, output the `n`th holy integer whose holiness is at least `h`. You may assume that the inputs and outputs will be no greater than the maximum representable integer in your language or `2^64 - 1`, whichever is less.

Here is a list of the first 25 holy integers with holiness `h >= 1`, for reference:

```
0, 4, 6, 8, 9, 40, 44, 46, 48, 49, 60, 64, 66, 68, 69, 80, 84, 86, 88, 89, 90, 94, 96, 98, 99

```

The first 25 holy integers with holiness `h >= 2` are:

```
0, 8, 40, 44, 46, 48, 49, 60, 64, 66, 68, 69, 80, 84, 86, 88, 89, 90, 94, 96, 98, 99, 400, 404, 406

```

# Answer
## Pyth, 32 bytes

```
e.fg*g.{`46890J`Z++lJ/J`8/J`0QE0

```

Explanation

```
                                 - autoassign Q = eval(input())
 .f                           E0 -  first eval(input()) terms of func V starting Z=0

     g.{`46890J`Z                -    Are all the digits in Z in "46890"?
               `Z                -      str(Z)
              J                  -     autoassign J = ^
     g                           -    is_subset(V,^)
      .{`46890                   -     set("46890")

    *                            -   ^*V (Only return non-zero if only contains holy numbers)

                 ++lJ/J`8/J`0    -    Get the holiness of the number
                   lJ            -      len(J)
                  +              -     ^+V
                     /J`8        -      J.count("8")
                 +               -    ^+V
                         /J`0    -     J.count("0")
   g                         Q   -  ^>=Q (Is the holiness great enough)
e                                - ^[-1]

```

Try it here

Takes input in the form `h \n n`
> 5 votes

# Answer
## Ruby, ~~109~~ ~~105~~ ~~95~~ 82 bytes

```
->n,h{(?0..?9*99).select{|x|x.count('469')+2*x.count('80')>=h&&/[12357]/!~x}[n-1]}

```

This is the terrible "calculate from 0 to 99999999999..." approach that happens to be 13 bytes shorter than its lazy counterpart. However, this version is unlikely to finish before the heat death of the universe. Worth 13 bytes, anyway ¯\\\_(ツ)\_/¯

You can test it for smaller values by changing `?9*99` to, say, `'99999'`.

Here's the old version (95 bytes, with lazy evaluation, which runs near-instantly rather than near-never):

```
->n,h{(?0..?9*99).lazy.select{|x|x.count('469')+2*x.count('80')>=h&&/[12357]/!~x}.first(n)[-1]}

```

```
->n,h{
(?0..?9*99)  # range '0' (string) to '9' repeated 99 times, way more than 2**64
.lazy        # make the range lazy, so we can call `select' on it
.select{|x|  # choose only elements such that...
 x.count('469')+2*x.count('80')  # naive holiness calculation
 >=h         # is at least h
 &&/[12357]/!~x                  # naive "is holy" calculation
}
.first(n)    # take the first n elements that satisfy the condition
[-1]         # choose the last one from this array
}

```
> 11 votes

# Answer
# Python 3, 103

```
lambda n,h,l='4698080':[y for y in range(2**64-1)if(sum(l.count(x)-(x not in l)for x in str(y))>=h)][n]

```

Here's a solution that uses a more memory efficient approach, but otherwise uses the same algorithm if you want to test it.

```
l='4689080'
def f(n,h):
 c=i=0
 while i<n:
  if sum(l.count(x)-(x not in l)for x in str(c))>=h:u=c;i+=1
  c+=1
 return u

```

Test cases:

```
assert f(3, 1) == 6
assert f(4, 2) == 44

```
> 6 votes

# Answer
## PowerShell, ~~163~~ ~~150~~ ~~141~~ ~~101~~ ~~98~~ 96 bytes

```
param($n,$h)for(--$i;$n){if(++$i-notmatch"[12357]"-and($i-replace"8|0",11).Length-ge$h){$n--}}$i

```

Takes input, then loops until `$n` is zero. We initially setting `$i=-1` by using a pre-processing trick, which works because `$i`, having not previously been declared, is `$null`. Then we `--` it, which causes PowerShell to evaluate it as `$i = $null - 1`, which is `$i=-1`.

Each loop we increment `$i` and then execute a lengthy `if` statement. The first part of the conditional verifies that `$i` doesn't have any of `12357` in it by using the `-notmatch` operator, to filter out the unholy numbers.

The second part of the conditional checks the quantity of holes in `$i`. It uses the `-replace` operator to replace each `8` or `0` with `11`, and then compares whether the length is \>= `$h`. We don't need to worry about stripping out the unholy numbers, since that's in the first part of the conditional, and the single-holed numbers are the same length as `1` anyway, so we don't need to replace them, either.

If that is still truthy, we decrement `$n` (as that means we've found another number that satisfies input requirements). Thus when the `for` condition is recalculated to check if `$n` is zero, that means we've found the *nth* one, so we exit the `for` loop, output `$i` and terminate.

Edit -- saved 13 bytes by using an array instead of string for `$l` and changing how `$n` is decremented/checked
Edit 2 -- saved an additional 9 bytes by checking for `$n` in the `for` conditional and moving the output outside the loop
Edit 3 -- saved a whopping 40 more bytes by radically changing how we calculate the holes
Edit 4 -- saved an additional 3 bytes by moving the `++` to be a pre-increment on the first part of the conditional
Edit 5 -- saved another 2 bytes thanks to TessellatingHeckler
> 5 votes

# Answer
## CJam, ~~36~~ 34 bytes

*Thanks to aditsu for saving 2 bytes.*

```
Wq~:X;{{)_Ab39643Zbf=_:*g*1bX<}g}*

```

Test it here.
> 4 votes

# Answer
# R, ~~109~~ 107 bytes

```
f=function(n,h){m=-1;while(n){m=m+1;if(!grepl("[12357]",m))if(nchar(gsub("([08])","\\1\\1",m))>=h)n=n-1};m}

```

With new lines and indentations:

```
f=function(n,h){
    m=-1
    while(n){
        m=m+1
        if(!grepl("[12357]",m))
            if(nchar(gsub("([08])","\\1\\1",m))>=h)
                n=n-1
    }
    m
}

```

Usage:

```
> f(4,3)
[1] 68
> f(4,2)
[1] 44
> f(6,2)
[1] 48
> f(10,2)
[1] 66

```
> 4 votes

# Answer
# Bash + GNU utilities, 67

* 20 bytes saved thanks to @TobySpeight!

```
seq 0 NaN|sed -r "h;/[12357]/d;s/8|0/&&/g;/^.{$1}/!d;x"|sed $2!d\;q

```
* `seq` simply generates integers starting from `0` upwards
* `sed -r`:
    + `h` copy the input line to the hold space
    + `/12357/d` delete unholy numbers
    + `s/8|0/&&/g` replace doubly holy digits with twice themselves. Thus singly holy digits are counted once and doubly holy digits are counted twice.
    + `/^.{$1}/!d` If not matching at least `$1` holes, delete and continue to the next line
    + `x` bring original number back to the pattern space
    + implicit print
* `sed`
    + `$2!d` on any lines before line `$2`, delete and continue to the next line
    + `q` must be at line `$2` \- quit (and implicit print)

Ideone.
> 3 votes

# Answer
# MATL, 39 ~~40~~ bytes

```
x~q`QtV4688900V!=stA*s2G<?T}N1G=?F1$}tT

```

Inputs are `n` and `h` in that order.

**Try it online!**

We need to keep track of two numbers: current candidate number (to check its holiness) and amount of numbers found that are holy enough. The first is the top od the stack, and the latter is kept as the number of elements in the stack. When the program finishes, only the top needs to displayed.

```
x~q          % implicitly take two inputs. Delete one and transform the other into -1
`            % do...while loop
  Q          %   add 1 to current candidate number
  tV         %   duplicate and convert to string
  4688900V!  %   column char array of '4', '6' etc. Note '8' and '0' are repeated
  =          %   compare all combinations. Gives 2D array
  s          %   sum of each column: holiness of each digit of candidate number
  tA*        %   are all digits holy? Multiply by that
  s          %   sum of holiness of all digits, provided they are all holy
  2G<        %   is that less than second input (h)?
  ?          %   if so: current candidate not valid. We'll try the next
    T        %     push true to be used as loop condition: next iteration
  }          %   else: current candidate valid
    N1G=     %     does stack size equal first input (n)?
    ?        %     if so: we're done
      F1$    %       push false to exit loop. Spec 1 input, to display only top
    }        %     else: make a copy of this number
      tT     %       duplicate number. Push true to continue with next iteration
             %     implicit end if
             %   implicit end if
             % implicit end do...while. If top of stack is truthy: next iteration
             % implicit display

```
> 3 votes

# Answer
## JavaScript (ES6), 110 bytes

```
f=(n,h,r=[],i=0)=>r.length<n?f(n,h,/[12357]/.test(i)|[...''+i].reduce((t,c)=>t+1+!(c%8),0)<h?r:[...r,i],i+1):r

```

Tail recursive solution that accumulates holy numbers in an array.

Out of interest, not requiring the number to be wholly(!) holy makes the holiness count more awkward, but it still saves 10% overall:

```
f=(n,h,r=[],i=0)=>r.length<n?f(n,h,[...''+i].reduce((t,c)=>+"2000101021"[c]+t,0)<h?r:[...r,i],i+1):r

```
> 3 votes

# Answer
# JavaScript ES6, 191 bytes

Sure, this isn't the most efficient way. But you know me, I love generators \<3

```
H=(x,o=x+"")=>(F=/^[46890]+$/).test(o)&&[...o].map(y=>d+=(F.test(y)+/8|0/.test(y)),d=0)&&d;(n,h)=>(a=(function*(h){q=0;while(1){if(H(q)>=h)yield q;q++}})(h),eval("a.next().value;".repeat(n)))

```

Slightly ungolfed:

```
H = (x, o = x + "") => (F = /^[46890]+$/).test(o) && [...o].map(y => d += (F.test(y) + /8|0/.test(y)), d = 0) && d;
Q = (n, h) => (a = (function*(h) {
    q = 0;
    while (1) {
        if (H(q) >= h) yield q;
        q++
    }
})(h), eval("a.next().value;".repeat(n)))

```
> 1 votes

# Answer
## Lua, ~~155~~ ~~141~~ 140 Bytes

Takes both inputs by command-line argument(first argument is n, then h)

**Edit: Thanks to @DavisDude, who helped me shaving 14 bytes off and reminded me I didn't have to print all the holy numbers up to n, but only the nth.**

```
a={}x=0while(#a<arg[1])do b,c=(x..""):gsub("[08]","")e,d=b:gsub("[469]","")a[#a+1],x=c*2+d>=arg[2]and #e<1 and x or nil,x+1 end print(a[#a])

```

### Ungolfed and explanations

```
x,a=0,{}                      -- initialise a counter, and the array which
                              -- contains the holy numbers found
while(#a<arg[1])              -- iterate while we found less holy numbers than n
do
  b,c=(x..""):gsub("[08]","") -- replace [08] by "", b=the new string
                              -- c=the number of subsitution
  e,d=b:gsub("[469]","")      -- same thing for [469]
  a[#a+1]=c*2+d>=arg[2]       -- insert the number into a if:nb[08]*2+nb[469]>h
             and #e<1         -- and e is empty (no unholy numbers)
             and x or nil
      x=x+1                   -- increment x
end
print(a[#a])                  -- print the last element of a

```
> 1 votes

# Answer
**C# 6, 168 bytes**

```
(n,h)=>{for(int i=0;i<=int.MaxValue;i++){string d=$"{i}";if(d.Any(y=>"12357".Contains(y)))continue;n-=d.Sum(y=>y=='0'||y=='8'?2:1)>=h?1:0;if(n==0)return i;}return -1;}

```

This is a Lambda Expression of type Func\< int, int, int\>. This code is otimized for min size (not performatic).

Below, the beautified code in method declaration (with more performance):

```
    int GetHolyNumber(int n, int h)
    {
        for (int i = 0; i <= int.MaxValue; i++)
        {
            string d = $"{i}";
            char[] cs = "12357".ToArray();
            if (d.Any(y => cs.Contains(y))) continue;

            n -= d.Sum(y => y == '0' || y == '8' ? 2 : 1) >= h ? 1 : 0;

            if (n == 0)
                return i;
        }
        return -1;
    }

```
> 1 votes

# Answer
# JavaScript (ES6), 87

```
(n,h)=>eval("for(i=0;[...i+''].map(d=>r-=~!(d%8),r=0),/[12357]/.test(i)|r<h||--n;)++i")

```

**Less golfed**

```
f=(n,h)=>{
  for (i=0;
    // this is the loop condition
    /[12357]/.test(i) // go on if not holy
    ||([...i+''].map(d=>r-=~!(d%8),r=0),r<h) // go on if not holy enough
    ||--n; // ok, found one! go on if we need to find more
  )
    ++i; // loop body - using eval this is the returned value
  return i; // not using eval, an explicit return is needed
}

```

**Test**

```
f=(n,h)=>eval("for(i=0;[...i+''].map(d=>r-=~!(d%8),r=0),/[12357]/.test(i)|r<h||--n;)++i")

function test() {
  var a,b
  [a,b]=I.value.match(/\d+/g)
  R.textContent = f(a,b)
}

test()
```

```
N, H: <input id=I value="25 2" oninput="test()"> >>
<span id=R></span>
```
> 1 votes

# Answer
# Jelly, ~~23~~ 22 bytes

```
“J,1’D=þD§S×ẠƊ
0Ç<Cɗ#Ṫ

```

Try it online!

## How it works

```
0Ç<Cɗ#Ṫ - Main link. Takes h on the left and n on the right
    ɗ   - Group the previous 3 links into a dyad f(k, h):
 Ç      -   Call the helper link on k
  <     -   Less than h?
   C    -   Complement; 0 -> 1, 1 -> 0
0    #  - Count up k = 0, 1, 2, ... until n k's return true under f(k, h)
      Ṫ - Take the last k

“J,1’D=þD§S×ẠƊ - Helper link. Takes an integer k on the left
        D      - Digits of k
“J,1’          - Compressed integer 4698800
     D         - Converted to digits
       þ       - Outer product with:
      =        -   Equality
         §     - Sum of each row
             Ɗ - Group the previous 3 links into a monad g(s) over the sums:
          S    -   Sum
            Ạ  -   All are non-zero?
           ×   -   Product
                 This calculates the holiness of k, which is 0 if k isn't holy

```
> 1 votes

# Answer
# Oracle SQL 11.2, 229 bytes

```
WITH v(c,p,i,j,n)AS(SELECT 0,-1,0,0,0 FROM DUAL UNION ALL SELECT c+1,c,REGEXP_COUNT(c||'','[4,6,9]'),REGEXP_COUNT(c,'[8,0]'),n+DECODE(LENGTH(p),i+j,DECODE(SIGN(i+j*2-:h),-1,0,1),0)FROM v WHERE p<c AND n<:n)SELECT MAX(p)-1 FROM v;

```

Un-golfed

```
:h -> required min holy value
:n -> nth number

curv   -> current number
precv  -> previous number
prech1 -> number of holy 1 letters in previous number
prech2 -> number of holy 2 letters in previous number
n      -> how many numbers with at least the required holy value

WITH v(curv,precv,prech1,prech2,n)AS
(
  SELECT 0 curv, -1 precv, 0 prech1, 0 prech2, 0 n FROM DUAL     -- Start with 0
  UNION ALL
  SELECT curv+1,   -- Next number
         curv,     -- Current Number
         REGEXP_COUNT(curv||'','[4,6,9]'),  -- number of holy 1 letters
         REGEXP_COUNT(curv,'[8,0]'),        -- number of holy 2 letters
         n+DECODE(LENGTH(precv),prech1+prech2,DECODE(SIGN(prech1+prech2*2-:h),-1,0,1),0) -- Is the previous number holy enough ?
  FROM   v
  WHERE  precv<curv   -- Needed to trick oracle cycle detection
         AND n<:n     -- Until clause
)
SELECT MAX(precv)-1 FROM v

```
> 0 votes

# Answer
# Haskell, 94 bytes

`c` is the holiness of a digit, `v` the holiness of a number, `n!h` does the rest.

```
c=([2,0,0,0,1,0,1,0,2,1]!!)
v n|n>9=c(mod n 10)+v(div n 10)|1<2=c n
n!h=[i|i<-[0..],v i<=h]!!n

```

Note: I think this is the only answer without the characters `4,6,8`.
> 0 votes

# Answer
## Python 2, 96 bytes

```
f=lambda n,h,k=0,s="0046889":-0**n or-~f(n-(sum(map(s.count,`k`))>=h<set(str(k))<=set(s)),h,k+1)

```

The holyness condition on `k` is checked by

* `sum(map(s.count,`k`))>=h`, which counts the number of holes by summing the counts for each character in `s="0046889"`, where `0` and `8` appear twice.
* `set(str(k))<=set(s))`, which checks that the numbers are all holy. `str` is used rather than backticks to avoid the suffix `L` for longs.

These are chained into a single equality using the Python 2 fact that numbers are smaller than sets.

The function is defined recursively to count up numbers `k`, decreasing the counter `n` each time a holy number of hit unless it hits `0`. It could then return the `k` that triggered this, but it's shorter to keep the count recursively by adding `1` each time, though an off-by-one requires a base count of `-1` to fix.
> 0 votes

# Answer
# Lua, 169 bytes

```
function a(n,h)H=0N=0I=-1while N<n do I=I+'1'H=0 if not I:find('[12357]') then _,b=I:gsub('[469]',1)_,c=I:gsub('[08]',1)H=b+2*c end N=H>=h and N+1 or N end print(I) end

```

Ungolfed:

```
function a(n,h) -- nth term, holiness
    H=0N=0I=-1 -- Really ugly, but hey, it works. Set up 3 vars
    while N<n do -- While nth term is lower than desired term
        I=''..I+1 -- Convert number to string (can't coerce since it will become a float)
        if not I:find('[12357]') then -- If the number doesn't have those numbers
            _,b=I:gsub('[469]',1) -- _ is the new string, b is the number of changes
            _,c=I:gsub('[08]',1) -- Same as above. Use 1 to replace to save chars
            H=b+2*c -- Increase holiness appropriately
        end
        N=H>=h and N+1 or N -- If current holiness >= desired holiness, increment N
    end
    print(I) -- Once the loop ends, print the current term
end

```
> 0 votes

# Answer
**Swift**

```
func f(n: Int, h: Int) {
    var m = 0
    let a = [1,2,3,5,7]
    for j in 0..<Int.max {
        var c = 0
        for i in (j.description.characters.map{(String($0) as NSString).integerValue}) {
            c += (a.contains(i)) ? 0 : (i == 8 || i == 0) ? 2 :1
        }
        if c >= h { m += 1; if m >= n {print(j); break}}
    }
}

```
> 0 votes

# Answer
# Perl 5 `-ap`, 58 bytes

```
$_=0;$n=<>;$_++while/[12357]/||y/64980//+y/80//<"@F"||--$n

```

Try it online!

Input is on two lines with `h` on the first and `n` on the second.
> 0 votes

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


title: Recreate the classic snake Game

text:
# Question
Title: Recreate the classic snake Game
The challenge is to create the classic Snake game using as few bytes as possible.

Here are the requirements:

* The game must be implemented in a typical 2-dimensional layout. The snake should be able to grow significantly within the bounds of the map (this really means, don't make your map too small, use your discretion here).
* A user may move the snake using keys of your choosing, however, the snake cannot double back on itself (e.g. if it is going West it cannot go East without first going North or South). A snake ought to be able to travel in all 4 directions: up, down, left, right (North, South, West, East).
* Snake starts off as length 1, each time it eats a "food" object it grows +1 in length
* Food objects are randomly placed in locations other than those occupied by the snake
* If the Snake hits itself or a wall the game is ended
* When the game has been ended the literal "Score: \[score\]" is displayed where \[score\] is the number of food items eaten during the game. So, for example, if the snake has eaten 4 "foods" (and therefore has a length of 5) when the game ends, "Score: 4" will be printed.
* No compression algorithms unless they are explicitly defined in your code.

Here's my solution, 908 Bytes, Python 2.7

```
import random as r
import curses as c
def g(s,w,l):
 while 1:
  p=[r.randrange(0,w),r.randrange(0,l)]
  for l in s:
   if l==p:continue
  return p
s=[]
d=[0,1]
p=k=n=0
e=100
v={65:[-1,0],66:[1,0],68:[0,-1],67:[0,1]}
z=c.initscr()
w,l=z.getmaxyx()[0],z.getmaxyx()[1]
c.noecho()
z.clear()
x=g(s,w,l)
s.append([w/2,l/2])
z.nodelay(1)
q=lambda h,i:range(h,len(i))
while k!=101:
 k=z.getch()
 if k in v and not (d[0]==(v[k][0]*-1) and d[1]==(v[k][1]*-1)):d=v[k]
 f=[0,0]
 for i in q(0,s):
  if i == 0:
   f=[s[i][0],s[i][1]]
   s[i][0]+=d[0]
   s[i][1]+=d[1]
  else:s[i],f=f,s[i]
 if s[0]==x:
  n+=1
  s.append(f)
  x=g(s,w,l)
 z.clear()
 if s[0][0]>=w or s[0][1]>=l or s[0][0]<0 or s[0][1]<0:break
 for i in q(1,s):
  if s[0] == s[i]: k = 101
 for i in q(0,s):z.addch(s[i][0],s[i][1],"X")
 z.addch(x[0],x[1],"O")
 z.move(0,0)
 z.refresh()
 if d[1]!=0:c.napms(e/2)
 else:c.napms(e)
c.endwin()
print 'Score: %s'%n

```

# Answer
## Ruby 1.9 + SDL (~~341~~ ~~324~~ 316)

Here's a first attempt at a Ruby version using the SDL library. I can save 6 characters if I'm allowed to load the SDL library using `-rsdl` on the command line instead of the require statement.

```
require'sdl'
f=o=d=3
s=SDL::Screen.open l=32,l,0,0
r=*0..l*l
loop{f==o ?f=(r-$*).sample: $*.shift
/yU/=~"#{e=SDL::Event.poll}"&&(v=e.sym%4)&&d+v!=3&&d=v
$><<"Score #{$*.size}"&&exit if$*.index(n=o+[-1,-l,l,1][d])||n<0||n>=l*l||d%3<1&&n/l!=o/l
$*<<o=n
r.map{|i|s[i%l,i/l]=[[f,*$*].index(i)?0:255]*3}
s.flip
sleep 0.1}

```

The snake segments and food pieces are represented using black pixels, the grid size is currently 32\*32. You can control with the arrow keys (or any keys really, the keycode mod 4 indexes the direction array \[LEFT, UP, DOWN, RIGHT\]). I think there's definitely room for improvement here, especially in the death-checking IF statement.

I've vastly improved this over the previous version, hopefully it more closely matches the spirit of the question now. ~~There's one thing I need to fix to comply with the spec, which is that food can currently spawn inside the tail.~~ Fixed!

Prints the score to stdout after the game is completed.
> 3 votes

# Answer
# APL (dzaima/APL), <sup>~~244~~</sup> 233 bytes

```
s←2⌿⊂2⌿25
d←?x←2⌿50
o←⍳2
G←P5.G
P5.draw←{G.bg¯1
G.fill←0
s⊢←(1↓s),⊂o+f←⊃⌽s
((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:P5.exit 0⊣⍞←'Score: ',⍕2-⍨≢s
d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x
(t←'center'G.rect,∘2 2)¨2×s
G.fill←'f00'
t+⍨d}
P5.kp←{o≢-n←('sdwa'⍳⍵)⊃1-↓⍬2⍴3⊤2320:o⊢←n}

```

Golfed from 294 → 244 bytes with the help of dzaima.

Uses `WASD` controls.

Uses `⎕IO←0` (0-indexing).

The grid is `50x50`, on the default `100x100` canvas Processing uses.

Displays score to the console.

Explanation done!

## Explanation

`s←2⌿⊂2⌿25` snake starts at \\$(25,25)\\$

`d←?x←2⌿50` first food position: 2 random ints in (0,50)

`x←2⌿50` save (50,50) in x

`o←⍳2` initial snake direction: (0,1)

`G←P5.G` save namespace as `G`

`P5.draw←{` execute the following each frame:

`G.bg¯1` display white background

`G.fill←0` set fill to black

`s⊢←(1↓s),⊂o+f←⊃⌽s` calculate next snake position:

`(1↓s)` remove the last tail segment

`,⊂o+f←⊃⌽s` add direction to the front, and append that

`f←⊃⌽s` assign head coordinates to f

`((⊢≢∪)s)∨~f⊂⍛∊a←⍳x:(...)` check if the player has lost:

`((⊢≢∪)s)∨` if snake does not match itself uniquified, or

`~f⊂⍛∊a←⍳x:` head is not within 50x50 grid:

`⍞←'Score: ',⍕2-⍨≢s` display the score in console, and

`P5.exit 0⊣` exit, displaying nothing

`d≡f:s⊢←s,⊂f+2×o⊣d⊢←?x` if head matches food, then change food position and increase snake length.

`(t←'center'G.rect,∘2 2)¨2×s` draw each position of the snake

`t←'center'G.rect,∘2 2` create function `t` for drawing the blocks

`G.fill←'f00'` set fill to red\`

`t+⍨d` draw the food

`}` close draw loop

`P5.kp←{...}` execute the following each time a key is pressed (⍵ is key name):

`1-↓⍬2⍴3⊤2320` array of directions `│0 1│1 0│0 ¯1│¯1 0│`

`('sdwa'⍳⍵)⊃` get key number, index into directions

`n←` store direction in n

`o≢-` if snake direction is not the opposite of n,(prevents moving backward)

`o⊢←n` then change snake direction

## Gameplay

(recorded at low fps)
> 4 votes

# Answer
# JavaScript, 609 bytes

```
document.write`<canvas id=C width=40 height=40 style='width:180px;height:180px;border:4px solid'`
s=[l={x:9,y:9}]
h=t=0,v=1
r=(x,y,w,h,f)=>{c.fillStyle=f,c.fillRect(x,y,w,h)}
m=n=>{g=4,i=0|38*(R=Math.random)()+1,j=0|38*R()+1,s.map(b=>b.x^i|b.y^j?0:m())},m()
onkeydown=k=>{f={d:[0,1],a:[0,-1],w:[-1,0],s:[1,0]}[k.key],f?(v=f[0],h=f[1]):0}
z=setInterval(w=>z?(focus(),c=C.getContext`2d`,r(0,0,80,80,'#fff'),s.push(l={x:l.x+h,y:l.y+v}),s.splice(0,0>g--),l.x^i|l.y^j?0:t+=!m(),s.map(b=>z&&(0>l.x||0>l.y||39<l.x||39<l.y||b!=l&&b.x==l.x&&b.y==l.y)?z=alert('Score:'+t):r(b.x,b.y,1,1,'#000')),r(i,j,1,1,'#f0f')):0,75)
```

Use WASD for controls.

JSFiddle
> 4 votes

# Answer
# Bash: ~~537~~ ~~533~~ 507 characters

```
C=$COLUMNS;L=$LINES;D=-1;c=9;r=9;z=(9\ 9);l=;h=1;v=;s=1;d=1
t(){ echo -en "\e[$2;$1H$3";}
b(){ ((f=RANDOM%C+1));((g=RANDOM%L+1));for i in "${z[@]}";do [[ $f\ $g = $i ]]&&b;done;t $f $g F;}
echo $'\e[2J';b
while :;do
read -sn1 -t.1 k
case $k in
w|s)((h))&&h=&&v=${D:$k};;
a|d)((v))&&v=&&h=${D:$k};;
esac
((c+=h));((r+=v))
((c==f&&r==g&&++l))&&b
((c<1||r<1||c>C||r>L))&&break
for i in "${z[@]}";do [[ $c\ $r = $i ]]&&break 2;done
t ${z[-1]} \ ;t $c $r X
z=($c\ $r "${z[@]::l}")
done
echo $'\e[2J\e[H'Score: $l

```

As it uses the `$COLUMNS` and `$LINES` shell variables, it must be run sourced: `. snake.sh`. The snake can be controlled with the `w`/`a`/`s`/`d` keys.

I know, it can be easily reduced to 493 characters by using `clear` to clear the screen, but I prefer to keep it pure `bash`, without using any external tool.
> 3 votes

# Answer
## Python 2.7: 869 816 818 817 816 Characters

I hacked this together in the last few hours. It should meet the requirements and is a few characters shorter than mjgpy3's solution (Tried hard, but couldn't get it much shorter. Now I'm tired). Surprisingly, using a game development library like pygame didn't get the python-snake much shorter. Suggestions and tips how to make it shorter are highly appreciated. I hope it's not too cryptic.

This is the result:

```
import pygame as p
from random import randint as r
p.init();l=20
c=p.time.Clock()
dp=p.display;w=p.display.set_mode((500,)*2)
C=p.Color;b=C(0,0,0);g=C(0,99,0)
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)
S=[R];d=R;n=[]
O=lambda t:{U:D,R:L,D:U,L:R}[t]
def Q(e):print "Score: %i"%(len(S)-1);p.quit()
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]
def M():n=(r(0,24),r(0,24));return n not in S and n or M()
A=lambda s,o:tuple(x+y for x,y in zip(s,o))
n=[M()]
while True:
 w.fill(b);[{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]
 if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)
 if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]
 else: S.append(A(S[-1],d));S.pop(0)
 N(S);dp.update();c.tick(6)

```

EDIT: I could reduce it to 816 Bytes, yay! :) Fixed the score

EDIT2: Pasted the wrong version accidentally

Here is a commented version:

```
import pygame as p
from random import randint as r

# initialize pygame
p.init()

# the game consists of 25*25 blocks,with each block 20*20 pixels
l=20

# initialize the main loop clock
c=p.time.Clock()

# open the window
dp=p.display;w=p.display.set_mode((500,)*2)

# define black and green colors
C=p.Color;b=C(0,0,0);g=C(0,99,0)

# Directions of the snake: down, up, left, right
D=(0,1);U=(0,-1);L=(-1,0);R=(1,0)

# S is the snake, d is the current direction and n is the array of foods
S=[R];d=R;n=[]

# get the opposite direction of a direction to forbid double backing
O=lambda t:{U:D,R:L,D:U,L:R}[t]

# print the score and quit
def Q(e):print "Score: %i"%(len(S)-1);p.quit()

# update the direction (this is a key press handler)
def K(e):global d;_={276:L,273:U,274:D,275:R}.get(e.key,(0,0));d=not _==O(d) and _ or d

# draw the snake and food boxes
def N(S):[p.draw.rect(w,g,[x[0]*l,x[1]*l,l,l]) for x in S+n]

# place new food on the map not colliding with the snake
def M():n=(r(0,24),r(0,24));return n not in S and n or M()

# A((1,1), (-2, 1)) -> (-1,2)
A=lambda s,o:tuple(x+y for x,y in zip(s,o))

# initialize food array
n=[M()]

while True:
 # fill the screen black
 w.fill(b)
 # get quit or key press events and execute the event handlers
 [{12:Q,2:K}.get(e.type,lambda e:e)(e) for e in p.event.get()]

 # check if snake hits map boundaries or itself
 if not (0<=S[-1][0]<25 and 0<=S[-1][1]<25) or A(S[-1],d) in S: Q(e)

 # check if snake is eating food at the moment and append one to the snake's length
 if A(S[-1],d) in n: S.append(A(S[-1],d));n=[M()]

 # move the snake in the current direction
 else: S.append(A(S[-1],d));S.pop(0)

 # draw the map and limit the main loop to 6 frames per second
 N(S);dp.update();c.tick(6)

```
> 3 votes

# Answer
# Java, ~~2343~~ 2239

Not exactly concise, but I believe it follows all the requirements.

### Snake class

```
import javax.swing.*;
public class S extends JFrame{
S(){add(new B());setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setSize(320,340);setVisible(true);}
public static void main(String[]a){new S();}}

```

---

### Board class

```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class B extends JPanel implements ActionListener{
int W=300;int H=300;int DS=10;int AD=900;int RP=29;int D=140;int x[]=new int[AD];int y[]=new int[AD];int d;int ax;int ay;boolean l=false;boolean r=true;boolean u=false;boolean dn=false;boolean ig=true;Timer t;Image b;Image a;Image h;
B(){addKeyListener(new T());setBackground(Color.black);ImageIcon id=new ImageIcon(this.getClass().getResource("d.png"));b=id.getImage();ImageIcon ia=new ImageIcon(this.getClass().getResource("a.png"));a=ia.getImage();ImageIcon ih=new ImageIcon(this.getClass().getResource("h.png"));h=ih.getImage();setFocusable(true);i();}
void i(){d=3;for(int z=0;z<d;z++){x[z]=50-z*10;y[z]=50;}l();t=new Timer(D,this);t.start();}
public void p(Graphics g){super.paint(g);if(i){g.drawImage(a,ax,ay,this);for(int z=0;z<d;z++){if(z==0)g.drawImage(h,x[z],y[z],this);else g.drawImage(b,x[z],y[z],this);}Toolkit.getDefaultToolkit().sync();g.dispose();}else{g(g);}}
void g(Graphics g){String ms="Score:";Font sm=new Font("Courier",Font.PLAIN,12);FontMetrics me=this.getFontMetrics(sm);g.setColor(Color.white);g.setFont(sm);g.drawString(ms+d,(W-me.stringWidth(ms)),H);}
void c(){if((x[0]==ax)&&(y[0]==ay)){d++;l();}}
void m(){for(int z=d;z>0;z--){x[z]=x[(z-1)]; y[z]=y[(z-1)];}if(l){x[0]-=DS;}if (r){x[0]+=DS;}if(u){y[0]-=DS;}if(dn){y[0]+=DS;}}
void cc(){for(int z=d;z>0;z--){if((z>4)&&(x[0]==x[z])&&(y[0]==y[z])){ig=false;}}if(y[0]>H){ig=false;}if(y[0]<0){ig=false;}if(x[0]> W){ig=false;}if(x[0]<0){ig=false;}}
void l(){int r=(int)(Math.random()*RP);ax=((r*DS));r=(int)(Math.random()*RP);ay=((r*DS));}
public void actionPerformed(ActionEvent e){if(ig){c();cc();m();}repaint();}
class T extends KeyAdapter{public void keyPressed(KeyEvent e){int k=e.getKeyCode();if((k==KeyEvent.VK_LEFT)&&(!r)){l=true;u=false;dn=false;}if((k==KeyEvent.VK_RIGHT)&&(!l)){r=true;u=false;dn=false;}if((k==KeyEvent.VK_UP)&&(!dn)){u=true;r=false;l=false;}if((k==KeyEvent.VK_DOWN)&&(!u)){dn=true;r=false;l=false;}}}}

```

---

### Screenshot

---

### Commentary

A while back I visited a website called zetcode which provided some tutorials for creating classic 2D games in Java. The code provided is strongly influenced by the tutorial that was provided for the Snake game... I think at this time I just started coding classic games and followed the tutorial to a 'T'.

I'll make an edit later and add a link to an executable so people can play the game.

---

### EDITS

* 9/9/12: I am unable to properly load the images from the resource folder. I'll continue to work through this issue in an attempt to prove that my code works and meets all criteria of the question.
* 9/11/12: I am going to continue working on getting the pictures to load from the resource file. I added a picture provided from the ZetCode tutorial.
> 2 votes

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


title: Leaping Kangaroos

text:
# Question
Title: Leaping Kangaroos
### Backstory

Disclaimer: May contain made up information about kangaroos.

Kangaroos traverse several stages of development. As they grow older and stronger, they can jump higher and longer, and they can jump more times before they get hungry.

In stage **1**, the kangaroo is very little and cannot jump at all. Despite this, is constantly requires nourishment. We can represent a stage **1** kangaroo's activity pattern like this.

```
o

```

In stage **2**, the kangaroo can make small jumps, but not more than **2** before it gets hungry. We can represent a stage **2** kangaroo's activity pattern like this.

```
 o o
o o o

```

After stage **2** the kangaroo improves quickly. In each subsequent stage, the kangaroo can jump a bit higher (1 unit in the graphical representation) and twice as many times. For example, a stage **3** kangaroo's activity pattern looks like this.

```
  o   o   o   o
 o o o o o o o o
o   o   o   o   o

```

For stage **n**, the activity pattern consists of **2n-1** V-shaped jumps of height **n**.

For example, for stage **4**, there are **8** jumps of height **4**.

```
   o     o     o     o     o     o     o     o
  o o   o o   o o   o o   o o   o o   o o   o o
 o   o o   o o   o o   o o   o o   o o   o o   o
o     o     o     o     o     o     o     o     o

```

### Task

Write a full program or a function that takes a positive integer **n** as input and prints or returns the ASCII art representation of a stage **n** kangaroo's activity pattern.

Surrounding whitespace and ANSI escape codes are allowed, as long as the pattern looks exactly as depicted above.

If you choose a function that returns the output, it must return a single string or character array that displays the proper output when printed. Returning an array of strings is not allowed.

You can use any printable, non-whitespace character instead of `o`, as long as it is consistent within the activity pattern and across all patterns in your answer.

This is ; may the shortest answer in bytes win!

# Answer
> 8 votes
# 05AB1E, ~~12~~ 10 bytes

```
Îj¹FÐvû},À

```

Explanation:

```
Î              # Push zero and input
 j             # Prepend input - 1 spaces
  ¹F           # Input times do..
    Ð          #   Triplicate the string
     v }       #   Length times do..
      û        #     Palindromize
        ,      #   Pop and print with a newline
         À     #   Rotate the string on to the right

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 14 votes
# MATLAB, ~~92 90 86~~ 84 bytes

```
n=input('');p=eye(n)+32;A=repmat([fliplr(p),p,''],1,2^n/2);A(:,n+1:n:end)=[];disp(A)

```

Try it online!

`eye` creates an identity matrix. If we flip it and concatenate the original i.e. `[fliplr(p),p]` we get (for `n=3`):

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

```

With `repmat(...,1,2^n/2)` we repeat this `2^(n-1)` times and get

```
0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0
0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 ...
1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1

```

From this we just delete the unnecessary columns, with `A(:,n+1:n:end)=[];`

# Answer
> 9 votes
# Charcoal, 14 bytes

```
ＮλＰ^×λoＦ⁻λ¹‖Ｏ→

```

Try it online!

### Explanation

`Ｎλ` inputs an integer into `λ`. `Ｐ^` is a multidirectional print (SE and SW) of `×λo` (string multiplication of `λ` with `o`). Then `Ｆ⁻λ¹` runs a for loop `λ - 1` times, in which `‖Ｏ→` reflects the whole thing to the right with overlap.

# Answer
> 7 votes
# Python 2, 87 bytes

```
n=input()
for i in range(n):print''.join(' o'[abs(j%(2*n)-n)==i]for j in range(1,n<<n))

```

Try it online!

Uses a formula for the coordinates `(i,j)` that contain a circle, then joins and prints the grid. There's a lot of golf smell here -- `''.join`, two nested ranges, `for` over `exec`, so there's likely to be improvements.

# Answer
> 7 votes
# Python 2, ~~83~~ 81 bytes

```
n=input()
i=0
exec"s=' '*n+'o'+' '*i;i+=1;print(s[i:-1]+s[:i:-1])*2**~-n+s[i];"*n

```

Try it online!

# Answer
> 5 votes
# Befunge, ~~98~~ 91 bytes

This uses a `,` in place of the `o`, since that enables us to save a couple of bytes.

```
&::1>\1-:v
+\:v^*2\<_$\1-2*::!+00p*1
:-1_@v0\-g01:%g00:-1<:\p01
 ,:^ >0g10g--*!3g,:#^_$\55+

```

Try it online!

**Explanation**

Given the stage number, *n*, we start by calculating the following three parameters of the pattern:

```
jump_count = 2 ^ (n - 1)
jump_len   = (n - 1) * 2
width      = (jump_len * jump_count) + 1

```

The *jump\_len* is normalised to avoid it being zero for a stage 1 kangaroo with:

```
jump_len += !jumplen

```

We can then output the jump pattern by iterating over the *x* and *y* coordinates of the output area, and calculating the appropriate charater to output for each location. The *y* coordinate counts down from *n* \- 1 to 0, and the *x* coordinate counts down from *width* \- 1 to 0. We determine whether a dot needs to be shown with the following formula:

```
jump_off = x % jump_len
show_dot = (jump_off == y) or (jump_off == (jump_len-y))

```

The *show\_dot* boolean is used as a table index to determine actual character to output at each location. To save on space, we use the start of the last line of source as that table, which is why our `o` character ends up being a `,`.

# Answer
> 5 votes
# , ~~28~~ 25 bytes

```
' o'{~]_&(](|.,}.)"1)=@i.

```

Saved 3 bytes thanks to @Conor O'Brien.

This is based on the palindrome trick from @muddyfish's solution.

Try it online!

## Explanation

```
' o'{~]_&(](|.,}.)"1)=@i.  Input: integer n
                       i.  Form the range [0, 1, ..., n-1]
                     =@    Equality table with itself.
                           Creates an identity matrix of order n
      ]                    Get n
       _&(          )      Repeat n times on x = identity matrix
           (     )"1         For each row
            |.                 Make a reversed copy
               }.              Get a copy with the head removed
              ,                Append them
          ]                  Use that as the new value of x
' o'{~                     Index into the char array

```

# Answer
> 4 votes
## C#, 180, 173 171 bytes

Wont win this, posting for other C# contestants as something they can beat.

```
n=>{var s=new string[n];for(int a=-1,j=0,i,m=n-1,x=m;j<=m*(Math.Pow(2,n)*n+1);){i=j++%n;s[i]+=x==i?"o":"_";if(i==m&n>1){x+=a;a*=x%m==0?-1:1;}}return string.Join("\n",s);};

```

complete program:

```
using System;
public class P
{
    public static void Main()
    {
        Func<int, string> _ = n =>
        {
            var s = new string[n];
            for (int a = -1, j = 0, i, m = n - 1, x = m; j <= m * (Math.Pow(2, n) * n + 1);)
            {
                i = j++ % n;
                s[i] += x == i ? "o" : "_";
                if (i == m & n > 1)
                {
                    x += a;
                    a *= x % m == 0 ? -1 : 1;
                }
            }
            return string.Join("\n", s);
        };

        Console.Write(_(4));
        Console.ReadKey();
    }
}

```

---

**edit:** -7 bytes thanks to @KevinCruijssen

**edit:** -2 bytes, simplified if

# Answer
> 4 votes
## Pyke, 11 bytes

```
XFd*\o+Q^Vs

```

Try it here!

```
 F          -  for i in range(input)
  d*\o+     -     " "*i+"o"
       Q^   -    ^.lpad(input)
         Vs -   repeat len(^): palindromise()
X           - print(reversed(^))

```

# Answer
> 4 votes
# Haskell, 100 bytes

```
k 1="o"
k n|n<-n-1,m<-n*2=unlines[[last$' ':['o'|mod c m`elem`[m-r,r]]|c<-[0..m*2^n]]|r<-[n,n-1..0]]

```

Try it online! Usage: `k 3`.

Explanation:

Given a row `r`, a column `c` and `m = 2(n-1)` an `o` is set if `c mod m` equals `r` or `m-r`. The outermost list comprehension sets the range of `r` from `n-1` to `0`, the next one sets the range of `c` from `0` to `m*2^(n-1)` and the innermost acts as conditional returning `'o'` if the above formula is fulfilled and `' '` otherwise. This yields a list of strings which is turned into a single newline separated string by `unlines`. For `n=1` the function produces a division-by-zero error, so this case is handled explicitly in the first line.

# Answer
> 3 votes
# , ~~58~~ 47 bytes

```
' o'{&:>~[:(,.}."1)&.>/(2^<:)#<@(|.,.}."1)@=@i.

```

Saved 11 bytes using the identity matrix idea from @flawr's solution.

Try it online!

A straightforward application of the definition.

## Explanation

For `n = 3`, creates the identity matrix of order *n*.

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

```

Then mirror it to make

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

```

Repeat that 2*n*-1 times and drop the head of each row on the duplicates

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

```

Use those values as indices into the char array `[' ', 'o']` to output a 2d char array

```
  o   o   o   o
 o o o o o o o o
o   o   o   o   o

```

# Answer
> 3 votes
# Python 2, ~~115~~ ~~113~~ ~~108~~ 98 bytes

```
lambda n:'\n'.join(map(''.join,zip(*[' '*abs(i)+'o'+~-n*' 'for i in range(-n+1,n-1)*2**~-n])))+'o'

```

Try it online!

Using `range(-n+1,n-1)` to create the absolute number of spaces between the bottom and the `o` to generate

```
  o
 o
o
 o

```

and then appending more copies, rotating 90º everything and appending the last `o` at bottom right

# Answer
> 3 votes
# Pyth, 30 bytes

```
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^

```

A program that takes input of an integer and prints the result. Uses a quote mark `"` instead of `o`.

Try it online!

**How it works**

```
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^    Program. Input: Q
jC.<V*]+*dtQNh*tQ^2Q*+JUQtP_J^QQ  Implicit input fill
      ]                           Yield a one-element list, A
        *dtQ                      cotaining Q-1 spaces
       +    N                     appended with a quote mark.
             h*tQ^2Q              Yield 1+(Q-1)*2^Q
     *                            Repeat A that many times, giving B
                       UQ         Yield [0, 1, 2, ..., Q-1]
                      J           (Store that in J)
                     +   tP_J     Append the reverse of J, discarding the first and last
                                  elements
                    *        ^QQ  Repeat the above Q^Q times, giving C
    V                             Vectorised map. For each pair [a,b] from B and C:
  .<                               Cyclically rotate a left by b characters
 C                                Transpose
j                                 Join on newlines
                                  Implicitly print

```

# Answer
> 3 votes
## JavaScript (ES6), 83 bytes

```
f=
n=>` `.repeat(n).replace(/ /g,"$'o$`-$`o$'-".repeat(1<<n-1)+`
`).replace(/-.?/g,``)
```

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

# Answer
> 3 votes
# Jelly, 11 bytes

```
ŒḄ¡ḶUz1Ṛa⁶Y

```

**TryItOnline!**

### How?

The printable character used is `0`.

Builds upon the method of Dennis's answer to his previous question on the subject of kangaroos.

```
ŒḄ¡ḶUz1Ṛa⁶Y - Main link: n                      e.g. 3
ŒḄ          - bounce, initial implicit range(n) e.g. [1,2,3,2,1]
  ¡         - repeat n times                    e.g. [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1]
                  i.e. [1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1] bounced to [1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1]
   Ḷ        - lowered range (vectorises)        e.g. [[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0],[0,1],[0,1,2],[0,1],[0]]
    U       - upend (vectorises)                e.g. [[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0],[1,0],[2,1,0],[1,0],[0]]
     z1     - transpose with filler 1
       Ṛ    - ...and reverse                    e.g. [[1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1],
                                                      [1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1],
                                                      [0,1,2,1,0,1,2,1,0,1,2,1,0,1,2,1,0]]
        a⁶  - logical and with space character (all non-zeros become spaces)
          Y - join with line feeds              e.g.    0   0   0   0
                                                       0 0 0 0 0 0 0 0
                                                      0   0   0   0   0

```

# Answer
> 3 votes
# MATL, 27 bytes

```
XyPt3LZ)2&Pht4LZ)lGqX"h48*c

```

Try it out at **MATL Online**

# Answer
> 2 votes
# Perl 6, ~~104~~ ~~93~~ 88 bytes

```
->\n{my @a;@a[$_;$++]="o" for [...] |(n-1,0,n-1)xx 2**n/2;say .join for @a».&{$_//" "}}

```

Inserts `o`'s into a 2D array, and then prints it.

# Answer
> 2 votes
# Python 3, 177 bytes

```
n=5;f=n-1;w=''
for i in range(n):
 s='';a=0;d='\n'
 if i==f:w='';a=-1;d=''
 for _ in range(2**f):
  s+=' '*(f-i)+'o'+' '*(2*i-1)+w+' '*(n-i-2+a)
 print(s,end=d);w='o'
print('o')

```

Try it online!

# Answer
> 2 votes
# 05AB1E, 16 bytes

```
L<¹Fû}ð×'o«.BøR»

```

Try it online!

Why and how?

```
                 # Example input of n=2.
L<               # [0,1] (Push [1..a], decrement).
  ¹Fû}           # [0,1,0,1,0] (Palindromize n times).
      ð×'o«      # ['o',' o','o',' o','o'] (Push n spaces, append o's).
           .Bø   # ['o ',' o','o ',' o','o '] (Pad with spaces into 2D array, transpose).
              R» # Reverse, join and print.

```

# Answer
> 1 votes
# Java 8, 254 bytes

Golfed:

```
n->{if(n==1)return"o";int k,x,y,m=n+n-2;char[][]p=new char[n][m];for(y=0;y<n;++y)for(x=0;x<m;)p[y][x++]=' ';for(k=0;k<m;++k)p[k<n?n-k-1:k-n+1][k]='o';String s="";for(y=0;y<n;++y){for(k=0;k<1<<(n-1);++k)for(x=0;x<m;)s+=p[y][x++];if(y==n-1)s+='o';s+='\n';}

```

Ungolfed:

```
import java.util.function.*;

public class LeapingKangaroos {

  public static void main(final String[] args) {
    for (int i = 1; i <= 4; ++i) {
      System.out.println(toString(n -> {
        if (n == 1) {
          return "o";
        }
        int k, x, y, m = (n + n) - 2;
        char[][] p = new char[n][m];
        for (y = 0; y < n; ++y) {
          for (x = 0; x < m;) {
            p[y][x++] = ' ';
          }
        }
        for (k = 0; k < m; ++k) {
          p[k < n ? n - k - 1 : (k - n) + 1][k] = 'o';
        }
        String s = "";
        for (y = 0; y < n; ++y) {
          for (k = 0; k < (1 << (n - 1)); ++k) {
            for (x = 0; x < m;) {
              s += p[y][x++];
            }
          }
          if (y == (n - 1)) {
            s += 'o';
          }
          s += '\n';
        }
        return s;
      } , i));
      System.out.println();
      System.out.println();
    }
  }

  private static String toString(final IntFunction<String> func, final int level) {
    return func.apply(level);
  }

}

```

Program output:

```
o

 o o
o o o

  o   o   o   o
 o o o o o o o o
o   o   o   o   o

   o     o     o     o     o     o     o     o
  o o   o o   o o   o o   o o   o o   o o   o o
 o   o o   o o   o o   o o   o o   o o   o o   o
o     o     o     o     o     o     o     o     o

```

# Answer
> 0 votes
## PHP, 157 bytes

```
for($i=$n=$argv[1],$r=str_repeat;$i>0;)echo$r($r(' ',$i-1).'o'.$r(' ',2*$n-2*$i-1).($i==$n|$i==1?'':'o').$r(' ',$i-2),2**($n-1)).($i--==1&$n!=1?'o':'')."\n";

```

Ungolfed:

```
for($i=$n=$argv[1];$i>0;) {

    // Spacing from beginning of pattern to first 'o'
    $o  = str_repeat(' ',$i-1);

    // First 'o' for the ascent
    $o .= 'o';

    // Spacing between ascent and descent
    $o .= str_repeat(' ',2*$n-2*$i-1);

    // Second 'o' for the descent, unless we are at the apex or the bottom
    $o .= ($i==$n|$i==1?'':'o');

    // Spacing to the end of the pattern
    $o .= str_repeat(' ',$i-2);

    // Repeat the pattern 2^(n-1) times
    echo str_repeat($o, 2**($n-1));

    // Output final 'o' if we are at the bottom in the last pattern
    echo $i--==1&$n!=1?'o':'';

    // End of line
    echo "\n";

}

```

# Answer
> 0 votes
# Canvas, 6 bytes

```
o×／Ｌ［│

```

Try it here!

## Explanation

```
o×/L[|
o×     repeat o input times
  /    make an antidiagonal using it
   L   get width without popping
    [| palindromize width times

```

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


# Question
Title: Parity of Nth Term in Fibonacci Integer Sequences
If you look at the Fibonacci Numbers, you will notice a pattern in their parity: `0, 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144`. Every third number is even, and all the others are odd. This makes sense because an even plus an odd is odd, but an odd plus an odd is even and the sum for a term will always include at least one even number unless the last two terms were odd, which happens every three terms.

In this challenge you will have to look at a generalization of this problem.

# Specs

* You will be given as input two positive integers describing the Fibonacci integer sequence you will have to look at.
* For example, `0, 1` describes the original Fibonacci numbers, and `2, 1` would be the Lucas numbers. The sequence is calculated with the recurrence relation: `x(n+2)=x(n+1)+x(n)`.
* You will also take a positive integer `n`.
* Your code has to output the parity of the nth term of the described Fibonacci integer sequence (0 indexed).
* The output format can be any two sane, consistent outputs (e.g. `0` for even and `1` for odd).

# Test Cases

```
(Fibonacci numbers) [0, 1], 4  ->  odd
(Lucas numbers) [2, 1], 9  ->  even
[14, 17], 24  ->  even
[3, 9], 15  ->  odd
[2, 4], 10  ->  even

```

# Answer
## Python, 29 bytes

```
lambda a,b,n:[a,b,a+b][n%3]%2

```

The generalized Fibonacci sequence modulo 2 has cycle length of 3. So, we reduce `n` mod 3 and take that element of the first three.

---

**31 bytes:**

```
lambda a,b,n:0<a%2*2+b%2!=n%3+1

```

`True` for odd, `False` for even
> 10 votes

# Answer
# Jelly, 4 bytes

```
^¡^Ḃ

```

Prints **0** for even, **1** for odd. Try it online!

### How it works

The quick `¡` takes a link it applies repeated to the previous output, and optionally a second link that specifies the number of iterations. If that second link is absent (which is the case here), the number of iterations is taken from the last command-line argument.

When the first link is dyadic (which is the case with `^`), `¡` applies that link to the previous return value (which is initialized as the left argument) and the right argument, then updates the return value with the result and the right argument with the previous return value. After doing so as many times as specified in the number of iterations, it returns the last return value.

The quicklink  is called with the left argument (first command-line argument) and the result of `^` (bitwise XOR of the left and right argument, i.e., the first and second command-line argument). XORing is necessary since the right argument is not among the return values, meaning that the right argument has to be the **x(-1)** in order to return **x(n)** with **x(0) `^` n `¡` x(1)**.

To actually calculate **x(n)**, we'd use the code `+¡_@` ( instead of  and `_@` – left argument subtracted from right argument – instead of `^`), but since we're only interested in the parities, any combination of `+`, `_` and `^` will do.

Finally,  (bit) computes and returns the parity of **x(n)**.
> 5 votes

# Answer
# Factor, 27 bytes

```
[ [ tuck + ] times . odd? ]

```

Try it online!

Well, executing the Fibonacci recurrence directly is way shorter than any other "smart" methods. Takes three items `a0 a1 n` on the stack, and outputs `t` for odd and `f` for even. Prints an unused value as a side effect.

For golfing, `.` is shorter than `drop`, and `odd?` is shorter than `2 mod` or `even?`.

```
[                   ! ( a0 a1 n )
  [ tuck + ] times  ! ( an an+1 ) Execute Fibonacci recurrence n times
  . odd?            ! drop an+1 by printing and test if an is odd
]

```
> 3 votes

# Answer
# Python, 38 bytes

```
lambda a,b,n:(b*(n%3>0)+a*(~-n%3>0))%2

```
> 2 votes

# Answer
# Jelly, 3 bytes

```
+¡Ḃ

```

Try it online!

Outputs `0` for even and `1` for odd

## How it works

```
+¡Ḃ - Main link. Takes a on the left and b on the right and n on the command line
 ¡  - Run the following dyad f(x,y) n times, starting with l = a and r = b.
      After each step, update l and r to l = r, r = f(l, r):
+   - f(x,y): x+y
      This is a generalised n'th Fibonacci "builtin"
  Ḃ - Bit; Return 1 for odd, 0 for even

```
> 2 votes

# Answer
# J, 15 bytes

```
2|0{(]{:,+/)^:[

```

Simple method. Computes the *n*th term, and takes it modulo 2 to find its parity. Even parity is represented by `0` and odd parity by `1`.

## Usage

```
   f =: 2|0{(]{:,+/)^:[
   4 f 0 1
1
   9 f 2 1
0
   24 f 14 17
0
   15 f 3 9
1

```

## Explanation

```
2|0{(]{:,+/)^:[  Input: n on LHS, and initial values [a, b] on RHS
    ( .... )^:[  Repeat the function n times
         +/      Find the sum of a+b
      {:         Get the value b from the tail of [a, b]
        ,        Join the values to get [b, a+b]
     ]           Return those values as the new [a, b]
  0{             Select the first value at index 0 from the list (after n applications)
2|               Take that value modulo 2 and return

```
> 1 votes

# Answer
# MATL, ~~10~~ 7 bytes

```
tshwQ)o

```

Try it online!

Explanation:

```
t            #Duplicate the array of numbers
 s           #Sum them
  h          #and add that to the end of the array
   w         #Swap inputs so that the *N* is on top
    Q        #Increment *N* (Since MATL uses 1-based indexing)
     )       #Get that element of the array. MATL uses modular indexing.
      o      #Return it's parity

```
> 1 votes

# Answer
# Perl 6,  ~~24~~  23 bytes

```
~~{(|@^a,sum @a)[$^n%3]%2}
{(|@^a,&[+]...*)[$^n]%2}~~
{(|@^a,*+*...*)[$^n]%2}
```

### Test:

```
use v6.c;
use Test;

constant even = 0;
constant odd = 1;
my @test = (
  ([0, 1], 4)    => odd,
  ([2, 1], 9)    => even,
  ([14, 17], 24) => even,
  ([3, 9], 15)   => odd,
  ([2, 4], 10)   => even,
);

my &seq-parity = {(|@^a,*+*...*)[$^n]%2}

for @test -> ( :key($input), :value($expected) ) {
  is seq-parity(|$input), $expected, ($input => <even odd>[$expected]).gist
}

```

```
ok 1 - ([0 1] 4) => odd
ok 2 - ([2 1] 9) => even
ok 3 - ([14 17] 24) => even
ok 4 - ([3 9] 15) => odd
ok 5 - ([2 4] 10) => even

```

### Explanation:

```
{
  (
    # generate the Fibonacci integer sequence
    # ( @^a is the first two values )
    |@^a, *+* ... *
  )[ $^n ] # get the one at the appropriate index
  % 2 # modulo 2
}

```
> 1 votes

# Answer
# Julia, 23 bytes

```
x\n=[x;sum(x)][n%3+1]%2

```

Try it online!
> 1 votes

# Answer
# Mathematica, ~~38~~ 36 bytes

```
OddQ@({#,#2,+##}&@@#)[[#2~Mod~3+1]]&

```

Anonymous function, based off of @xnor's Python approach. Takes a list and an integer, and outputs either `True` for odd or `False` for even. Not much beyond that.
> 1 votes

# Answer
# \+ pryr, 30 bytes

```
pryr::f(c(x,y,x+y)[n%%3+1]%%2)

```

Try it online!

Calculates parity of modular index of `(x,y,x+y)`; returns `0` for even and `1` for odd. Function with arguments `n`,`x` and `y`, where `x` and `y` represent the initial two fibonacci numbers.

The `f()` function from the `pryr` library is a short way to define a function. In code-golf, it's sometimes used simply because `pryr::f` has one less character than `function`. However, it also tries to 'guess' the function arguments from the body of the function if they are not declared (using a mysterious and not well-documented algorithm). This is particularly useful here, where declaring `x,y,n` in a conventional function definition would cost an extra 5 bytes.
Luckily, in this case `f` somehow manages to guess the arguments perfectly.
> 1 votes

# Answer
# Rust, 23 bytes

Port of xnor's answer, which you should upvote!

```
|a,b,n|[a,b,a+b][n%3]%2

```

Try it online!

Rust is Language of the month for December, but it doesn't have a ton of answers, so I'm posting a trivial one to remind y'all that Rust can sometimes beat Python too.
> 1 votes

# Answer
## Pyke, 9 bytes

```
3%QDs+@2%

```

Try it here!

```
    s+    -   input+sum(input)
      @   -  ^[V]
3%        -   line_2 % 3
       2% - ^ % 2

```
> 0 votes

# Answer
## Actually, 12 bytes

```
╗│+k3╜%@E2@%

```

This uses the same strategy as xnor's Python answer. Input is `a b n`, with the spaces replaced by newlines. Output is `0` for even parity and `1` for odd parity.

Try it online!

Explanation:

```
╗│+k3╜%@E2@%
              implicit input ([a, b, n])
╗             save n in reg0 ([a, b])
 │            duplicate stack ([a, b, a, b])
  +k          add, push stack as list ([[a, b, a+b]])
    3╜%       n mod 3 ([[a, b, a+b], n%3])
       @E     element in list ([[a, b, a+b][n%3])
         2@%  mod 2 ([[a, b, a+b][n%3]%2)

```
> 0 votes

# Answer
# CJam, 9 bytes

```
q~_:++=2%

```

Even is zero, odd is one.

Try it online!

# Explanation

```
q~        e# Read input and evaluate
  _       e# Duplicate initial tuple
   :+     e# Sum initial values
     +    e# Append sum to initial tuple
      =   e# Take the n-th element (modular indexing)
       2% e# Modulo 2

```
> 0 votes

# Answer
# Perl 5 `-MList::Util=sum -pla`, 21 bytes

A port of @xnor's python answer as a Perl program.

```
$_=(@F,sum@F)[<>%3]%2

```

Try it online!

Inputs the two starting sequence numbers on the first line and the element to find on the second. Outputs `1` for odd parity and `0` for even.
> 0 votes

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


title: Crown hundred crownty crown

text:
# Question
Title: Crown hundred crownty crown
I noticed a certain game had a peculiar life counter, which instead of stopping at `999`, gained a new digit – the next number was *crown* hundred or `00`. After `99` came *crown hundred crownty* (`0`) and the last number, after `9`, was *crown hundred crownty crown* or , which would be 1110 in decimal.

Your task is to write a program or a function that outputs this counter.

Given an integer from the range `[0,1110]` (inclusive on both ends), output a three character string where

* every character is from the list `0123456789`
* the crown () can only appear as the leftmost character or when there's a crown to the left of it
* when this number is read as a decimal number but with the crown counting as `10`, you get back the original number

## Test cases

```
   0 → "000"
  15 → "015"
 179 → "179"
 999 → "999"
1000 → "00"
1097 → "97"
1100 → "0"
1108 → "8"
1110 → ""

```

You may use any non-decimal character instead of the crown. To encourage pretty printing, the crown character (UTF8 byte sequence "\240\159\145\145") counts as one byte instead of four. Your program doesn't have to work for numbers outside the valid range.

This is , so the shortest answer, measured in bytes, wins!

# Answer
# 05AB1E, ~~20~~ 18 bytes

```
₄‹i₄+¦ëTð.;„1 „  :

```

Uses spaces for crowns.

Try it online or verify all test cases.

**Explanation:**

```
₄‹i               # If the (implicit) input is smaller than 1000:
   ₄+             #  Add 1000 to the (implicit) input
     ¦            #  And remove the leading 1 (so the leading zeros are added)
                  #   i.e. 17 → 1017 → "017"
  ë               # Else:
   Tð.;           #  Replace the first "10" with a space " "
                  #   i.e. 1010 → " 10"
                  #   i.e. 1101 → "1 1"
                  #   i.e. 1110 → "11 "
       „1 „  :    #  Replace every "1 " with "  " (until it no longer changes)
                  #   i.e. " 10" → " 10"
                  #   i.e. "1 1" → "  1"
                  #   i.e. "11 " → "   "

```
> 2 votes

# Answer
# JavaScript (Node.js), 50 bytes

```
f=(n,p=1e3)=>n<p?(n+p+'').slice(1):'#'+f(n-p,p/10)

```

Try it online!

TIO was based on Arnauld's answer. Show as `#`.
> 12 votes

# Answer
# JavaScript (ES6),  ~~62 46~~  44 bytes

*Saved 2 bytes thanks to @nwellnhof*

Outputs crowns as `x` characters.

```
n=>(n+1e4+'').replace(/1+0/,'xxx').slice(-3)

```

Try it online!

### How?

We add \\$10000\\$ to the input, coerce it to a string, look for the `/1+0/` pattern and replace it with `xxx`. Finally, we return the 3 trailing characters.

*Examples:*

$$\begin{align}&0 &\rightarrow &\text{ "}\color{red}{\text{10}}\text{000"} &\rightarrow &\text{ "xxx000"} &\rightarrow &\text{ "000"}\\ &123 &\rightarrow &\text{ "}\color{red}{\text{10}}\text{123"} &\rightarrow &\text{ "xxx123"} &\rightarrow &\text{ "123"}\\ &1023 &\rightarrow &\text{ "}\color{red}{\text{110}}\text{23"} &\rightarrow &\text{ "xxx23"} &\rightarrow &\text{ "x23"}\\ &1103 &\rightarrow &\text{ "}\color{red}{\text{1110}}\text{3"} &\rightarrow &\text{ "xxx3"} &\rightarrow &\text{ "xx3"}\\ &1110 &\rightarrow &\text{ "}\color{red}{\text{11110}}\text{"} &\rightarrow &\text{ "xxx"} &\rightarrow &\text{ "xxx"} \end{align} $$
> 9 votes

# Answer
# Shakespeare Programming Language, ~~763~~ ~~692~~ ~~690~~ ~~689~~ 683 bytes

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]Ford:Listen tothy!Ajax:You big big cat.Scene V:.Ajax:Remember the remainder of the quotient betweenI twice the sum ofa cat a big big cat.Ford:You be the quotient betweenyou twice the sum ofa cat a big big cat.Ajax:You be the sum ofyou a pig.Be you nicer zero?If solet usScene V.Ford:You big big cat.[Exit Ajax][Enter Page]Page:Recall.Ford:You be I.Scene X:.Page:Recall.Am I nicer zero?If notopen heart.If notlet usScene L.Ford:You big big big big big cat.Speak thy.Am I worse a cat?If soyou zero.Scene L:.[Exit Page][Enter Ajax]Ford:You be the sum ofyou a pig.Is you nicer a cat?[Exit Ajax][Enter Page]Ford:If solet usScene X.

```

Try it online!

Uses `" "` instead of crowns. At the cost of 4 more bytes, this could be modified to show a "visible" character instead.

## Explanation:

```
,.Ajax,.Ford,.Page,.Act I:.Scene I:.[Enter Ajax and Ford]

    Boilerplate, introducing the characters.

Ford:Listen tothy!

    Input a value to Ajax.

Ajax:You big big cat.

    Set Ford's value to 4 (we will be pushing 4 digits from Ajax onto Ford's personal stack).

Scene V:.Ajax:Remember the remainder of the quotient betweenI twice the sum ofa cat a big big cat.Ford:You be the quotient betweenyou twice the sum ofa cat a big big cat.

    DIGIT-PUSHING LOOP: Push Ajax's last digit onto Ford's stack; divide Ajax by 10.

Ajax:You be the sum ofyou a pig.Be you nicer zero?If solet usScene V.

    Decrement Ford; loop until Ford is 0.

Ford:You big big cat.

    Set Ajax's value to 4 (we will pop 3 digits from Ford's stack in the next loop).

[Exit Ajax][Enter Page]Page:Recall.Ford:You be I.

    Pop the top value off Ford's stack, and store that into Page.
    Here, Page will contain 0 if there are no crowns to be drawn,
    and 1 if there are crowns to be drawn.

Scene X:.Page:Recall.Am I nicer zero?If notopen heart.If notlet usScene L.

    DIGIT-DRAWING LOOP: Pop the top value off of Ford's stack and set Ford equal to that value.
    If there are no crowns to be drawn, output Ford's literal value here, and skip the crown-drawing section.

Ford:You big big big big big cat.Speak thy.Am I worse a cat?If soyou zero.

    Draw crown.
    If we are drawing crowns, and Ford contains 0 here, then we are now done drawing crowns, and thus we store 0 into Page.
    (Put in one more "big" for the crown to look like an @ symbol.)

Scene L:.[Exit Page][Enter Ajax]Ford:You be the sum ofyou a pig.Is you nicer a cat?[Exit Ajax][Enter Page]Ford:If solet usScene X.

    Decrement Ajax; loop until Ajax is 1 (i.e. 3 times).

```
> 9 votes

# Answer
# Python 2, 53 bytes

Hats off to Arnauld for **-22 bytes**. Recursion still wins, though.

```
lambda k:re.sub("1+0","CCC",`k+10000`)[-3:]
import re

```

Try it online!

# Python 2, 51 bytes

This instead implements tsh's recursive method. Saved 2 bytes thanks to ovs.

```
f=lambda n,p=1000:n/p and'C'+f(n-p,p/10)or`n+p`[1:]

```

Try it online!
> 5 votes

# Answer
# Python 2, 52 bytes

```
lambda n:['%03d'%n,'%3s'%`n`.lstrip('1')[1:]][n>999]

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 41 bytes

```
\b((.)|..)\b
$#2$*00$&
T`d`_#`(?=....)1+0

```

Try it online! Uses `#`s instead of s. Link includes test cases. Explanation:

```
\b((.)|..)\b
$#2$*00$&

```

Pad 1- and 2-digit numbers to three digits.

```
T`d`_#`(?=....)1+0

```

Change leading `1`s of 4-digit numbers to `#`s and delete the next `0`.
> 3 votes

# Answer
# Jelly, 19 bytes \- 0 = 19

```
<ȷ¬ȧDi0ɓ⁶ẋ⁹Ḋ;+ȷDḊṫʋ

```

A full program printing the result using a space character as the crown.
(As a monadic Link a mixed list of integer digits and space characters is yielded)

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

...maybe a recursive implementation will be shorter.

### How?

```
<ȷ¬ȧDi0ɓ⁶ẋ⁹Ḋ;+ȷDḊṫʋ - Main Link: integer, N    e.g. 1010       or   10
 ȷ                  - literal 1000                  1000            1000
<                   - less than?                    0               1
  ¬                 - logical not                   1               0
    D               - to decimal list               [1,0,1,0]       [1,0]
   ȧ                - logical and                   [1,0,1,0]       0
      0             - literal zero                  0               0
     i              - first index - call this I     2               1  (0 treated as [0] by i)
       ɓ            - new dyadic chain with swapped arguments - i.e. f(N, I)
        ⁶           - literal space character       ' '             ' '
          ⁹         - chain's right argument        2               1
         ẋ          - repeat                        [' ',' ']       [' ']
           Ḋ        - dequeue                       [' ']           []
                  ʋ - last four links as a dyad - i.e. f(N, I)
             +ȷ     -   add 1000                    2010            1010
               D    -   to decimal list             [2,0,1,0]       [1,0,1,0]
                Ḋ   -   dequeue                     [0,1,0]         [0,1,0]
                 ṫ  -   tail from index (I)         [1,0]           [0,1,0]
            ;       - concatenate                   [' ',1,0]       [0,1,0]
                    - implicit print                " 10"           "010"

```
> 3 votes

# Answer
# Python 2, 40 bytes

```
lambda n:'%3s'%`10000+n`.lstrip('1')[1:]

```

Try it online!

Implements an idea similar to Mr. Xcoder's regex-based answer but without a regex. We remove leading 1's in `10000+n` as well as the next character, then pad with spaces to length 3. The result is similar to ovs's solution using `lstrip` but without needing two cases.
> 3 votes

# Answer
# Clean, 87 bytes

Doesn't output crowns (uses `c`).

```
import StdEnv,Text
$n#i=3-n/1000-n/1100-n/1110
=("ccc"+lpad(""<+n rem(10^i))i'0')%(i,9)

```

Try it online!

```
$ n                   // function $ of `n`
 # i =                // define `i` as (the number of digits that aren't crowns)
  3 -                 // three minus
  n / 1000 -          // 1 if first digit is crown
  n / 1100 -          // 1 if second digit is crown
  n / 1110            // 1 if third digit is crown
 = (                  // the string formed by
  "ccc" +             // prefixing three crowns to
  lpad (              // the padding of
   "" <+ n rem (10^i) // non-crown digits of `n`
  ) i '0'             // with zeroes
 ) % (i, 9)           // and removing the extra crowns

```

# Clean, 99 - 3 = 96 bytes

This one has crowns.

```
import StdEnv,Text
$n#i=3-n/1000-n/1100-n/1110
=(""+lpad(""<+n rem(10^i))i'0')%(i*4,99)

```

Try it online!
> 2 votes

# Answer
# C,  ~~84~~  58 bytes

*Thanks to @tsh for saving 25 bytes and thanks to @ceilingcat for saving a byte!*

```
f(n,p){for(p=1e3;p/=10;)n-=putchar(n/p>9?46:48+n/p)%12*p;}

```

Try it online!
> 1 votes

# Answer
# Japt, 20 bytes

A naïve (and slightly drunk!) port of Arnauld's solution. Uses `"` for crown.

```
U+A³ s r"^21*0"_çQÃÅ

```

Try it
> 1 votes

# Answer
# Java 10, ~~84~~ 83 bytes

```
n->{for(int p=100,t;p>0;n-=t%12*p,p/=10)System.out.printf("%c",t=n/p>9?46:48+n/p);}

```

Port of *@tsh*' C comment.
Uses `.` instead of crowns.

Try it online.

**Alternative approach (84 (87-3) bytes):**

```
n->f(n,1000)String f(int n,int p){return n<p?(n+p+"").substring(1):""+f(n-p,p/10);}

```

Port of *@tsh*' JavaScript's answer.

Try it online.
> 1 votes

# Answer
# APL (Dyalog Unicode), 32 bytes

```
1e3∘{⍵<⍺:1↓⍕⍵+⍺⋄'C',(⍵-⍺)∇⍨⍺÷10}

```

Try it online!

Prefix direct function.

Port of @tsh's JS Answer.

### How:

```
1e3∘{⍵<⍺:1↓⍕⍵+⍺⋄'C',(⍵-⍺)∇⍨⍺÷10} ⍝ Main function, arguments ⍵ and ⍺ (⍵ → input, ⍺ → 1000).
     ⍵<⍺:                          ⍝ If ⍵<⍺
         1↓                        ⍝ Drop (↓) the first element (1) of
           ⍕                       ⍝ Format (⍕); 'stringify'
            ⍵+⍺                    ⍝ ⍵+⍺
               ⋄                   ⍝ else
                'C',               ⍝ Concatenate (,) the literal 'C' with
                         ∇⍨        ⍝ Recursive call (∇) with swapped arguments (⍨)
                    (⍵-⍺)  ⍺÷10    ⍝ New arguments; ⍵ → ⍵-⍺; ⍺ → ⍺÷10

```
> 1 votes

# Answer
# PHP, 71 bytes

```
for($n=$argn,$x=1e4;1<$x/=10;$n%=$n<$x?$x/10:$x)echo$n<$x?$n/$x*10|0:C;

```

prints `C` for the crown. Run as pipe with `-nR` or try it online.
> 1 votes

# Answer
# Haskell, 48 bytes

```
('2'#).show.(+1000)
n#(a:x)|n==a='c':'1'#x|1>0=x

```

Try it online!
> 1 votes

# Answer
# Perl 6, 38 - 9 = 29 bytes

*-2 bytes thanks to Jo King*

```
{~m/...$/}o{S/1+0//}o*+1e4

```

Try it online!

Inspired by Arnauld's JavaScript solution.
> 1 votes

# Answer
# sed, 39

48 bytes, but score is 39, since each counts as 1.

```
/..../s/^1+0//
s/^/00/
s/.*(...)/\1/

```

Try it online!
> 1 votes

# Answer
# Pip, 21 bytes

```
(a+t*mR`1+0`'xX3)@>-3

```

Try it online!
> 1 votes

# Answer
# Stax, 15 bytes

```
çi╖@u;╟w☼7ø4σcH

```

Run and debug it

Same idea as Arnauld's answer.
> 1 votes

---
Tags: code-golf, number, integer, conversion
---