[Question]
  [
### Snaking Number Challenge
I wonder how many snaking numbers there are between 1 and 50,000?
[![Snake on a Nokia](https://i.stack.imgur.com/oOche.gif)](https://i.stack.imgur.com/oOche.gif)
Snaking Numbers, in this game, are numbers which can be typed out on a traditional numberpad (format below) by moving one key up, down, left, or right.
```
7 8 9
4 5 6
1 2 3
 0
```
For example, if you start with the number 5, you could select 4, 6, 8, or 2 as your next valid move - however 7, 3, 9, and 1 are off-limits as they are positioned diagonally to the current key.
So, if you have 5, then 2, your next viable key choices are 0, 1, 3, or 5 again. 
In this Code Golf exercise, you are to output a list of all the positive snaking numbers between 1 and 50k, along with a final count of all the numbers that meet the criterion.
### Rules
1. Numbers cannot start with a Zero.
2. Numbers must be whole positive integers.
3. Each consecutive number, read from left to right, must "snake" around the numberpad.
4. The snake cannot travel diagonally across keys
5. The number 0 can be accessed from both numbers 1 and 2
6. Numbers cannot be paired (eg: 22)
### Examples of valid Snaking Numbers:
```
12369
45201
1254
10102
1
12
987
```
### Examples of invalid numbers
```
1238 - 8 is not connected
0001 - multiple leading 0s
0101 - leading 0
159  - snake cannot travel diagonally
4556 - duplicate 5
```
As per normal Code Golfs, the aim is fewest bytes!
According to my maths and rules, you should have 670 valid snaking numbers in your list, plus 670 itself printed as the last number.
  
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~60 57~~ 60 bytes
```
(x;#x:({*/1=3!5&+/x*x:+1_-':(+0 1,'2*!3 3)@10\x}')#1+!50000)
```
[Try it online!](https://ngn.bitbucket.io/k#eJzTqLBWrrDSqNbSN7Q1VjRV09av0Kqw0jaM11W30tA2UDDUUTfSUjRWMNZ0MDSIqahV11Q21FY0NQACTQCiOg0U)
`!50000` list of `0` .. `49999`
`1+` add 1 to all
`({` `}')#` filter with the function in `{` `}`
`10\x` decimal digits of the argument
`(` `)@` use as indices in ...
* `!3 3` a pair of lists: `(0 0 0 1 1 1 2 2 2;0 1 2 0 1 2 0 1 2)`
* `2*` multiply all by 2
* `0 1,'` prepend `0` to the first list and `1` to the second
* `+` transpose (pair of lists -> list of pairs). this gives us the approx button coords.
`-':` subtract from each pair the previous pair. use `0 0` as an imaginary element before the first.
`1_` drop the first
`+` transpose
`x*x:` square (assign to `x` and multiply by `x`). here `x` is a pair of lists - ∆x-s and ∆y-s
`+/` sum the two lists (element by element)
`5&` min with 5
`3!` mod 3
`1=` boolean list of where it's equal to 1
`*/` product (boolean "and")
`(x;#x:` `)` make a pair of the result and the length (`#`) of the result
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~24~~ 23 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
5ȷ4µDo1.’d3ZIASĊ’ẸµÐḟṄL
```
A full program which prints a list of all the results and then the number of results.
**[Try it online!](https://tio.run/##ASsA1P9qZWxsef//Nci3NMK1RG8xLuKAmWQzWklBU28y4buK4bqgwrXGhyxMJP// "Jelly – Try It Online")**
### How?
```
5ȷ4µDo1.’d3ZIASĊ’ẸµÐḟṄL - Main Link: no arguments
5ȷ4                     - 5*10^4 = 50000
   µ              µÐḟ   - filter discard those for which this is truthy:
                        -                  e.g.: 8520        ... or           4559 
    D                   -   decimal digits       [8,5,2,0]                    [4,5,5,9]
      1.                -   literal 1.5
     o                  -   logical OR           [8,5,2,1.5]                  [4,5,5,9]
        ’               -   decrement            [7,4,1,0.5]                  [3,4,4,8]
         d3             -   div-mod by 3         [[2,1],[1,1],[0,1],[0,0.5]]  [[1,0],[1,1],[1,1],[2,2]]
           Z            -   transpose            [[2,1,0,0],[1,1,1,0.5]]      [[1,1,1,2],[0,1,1,2]]
            I           -   deltas               [[-1,-1,0],[0,0,-0.5]]       [[0,0,1],[1,0,1]]
             A          -   absolute value       [[1,1,0],[0,0,0.5]]          [[0,0,1],[1,0,1]]
              S         -   sum (vectorises)     [1,1,0.5]                    [1,0,2]
               Ċ        -   ceiling              [1,1,1]                      [1,0,2]
                ’       -   decrement            [0,0,0]                      [0,-1,1]
                 Ẹ      -   any?                 0 (i.e. keep)                1 (i.e. discard)
                     Ṅ  - print and yield
                      L - length
                        - implicit print
```
[Answer]
# [Python 3](https://docs.python.org/3/), 140 bytes
```
f=lambda s:''==s[1:]or s[1]in'10021234562216565878 43 749 9   5  8'[int(s[0])::10]and f(s[1:])
print(*filter(f,map(str,range(1,50000))),670)
```
[Try it online!](https://tio.run/##HYy9DoMgGAD3PsW3AQ0DoPxI4pMQBhqlNVEkwOLTU9tbbrjk8tU@Zxp6j/MejtcSoFqE5rk6bv1Z4LbfEuKMCS6GUSohuJJKGm1gHECPE0wAIAEMcltquDrmibWc@ZAWiPg/Io9cfvEZt72tBUd6hIxrK7SE9F4xp5LdEEKo0oz0/gU "Python 3 – Try It Online")
I'm positive someone will be able to do this with an expression instead of a lookup string.
[Answer]
# [Python 2](https://docs.python.org/2/), 101 bytes
```
print[n for n in range(1,50000)if all(`n`[i:i+2]in`0x20b33ec8bc49a10589e76b15`for i in range(4))],670
```
[Try it online!](https://tio.run/##RcxLCoAgEADQq8wyycVo2u8qEahhNRBTSIs6vdWqd4B33Oe6s875SMTnwDDvCRiIIXleYqGkxZegGfy2FY7dQD2VeiR2eGkMVRWnNkym8wpt28WmDsq6b6F/MUKMsm4w5wc "Python 2 – Try It Online")
The hex number is decimal `10120214525632365878969854741`, which encodes every ordered pair of digits that can appear adjacent to one another.
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~112 106~~ 104 bytes
*Saved 2 bytes thanks to @NahuelFouilleul*
A full program.
```
for(n=0;++n<5e4;)[...n+''].every(x=>'6589632145201478'.match(x+p+'|'+p+(p=x)),p='')&&print(n)
print(670)
```
[Try it online!](https://tio.run/##JcbRCsIgFADQ9z5k914scUudY9mPRA8yjBZk4kQM@ncLejmchytuW9Ia86GY1m6vhMGKmbFwUl7OdOGcBwZw5b749MZqz6CVmfRx6KUaRC9HA/zp8nLHyiKDD/zEaCvRPloA6rqY1pAx0O4fPQpq7Qs "JavaScript (V8) – Try It Online")
Or **96 bytes** if we can output the numbers in reverse order:
```
for(n=5e4;n--;)[...n+''].every(x=>'6589632145201478'.match(x+p+'|'+p+(p=x)),p='')&&print(n||670)
```
[Try it online!](https://tio.run/##DcTRCsIgFADQv9m9Ysq21BnDfiR6kGG0oDsxEQP/3ToP5@WL/2xpj1kU2/vjSEhOB7WSECu7SSmJA9xlKCF9sborGG0v5jxPSs/jpBYL8u3z9sTKI4cG/zG6ytgpOgA2DDHtlJFaM8vIev8B "JavaScript (V8) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~37~~ 35 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü╞╡~▄ⁿ♪eµïê◙ü╔ï▼ΔJr¥æ≤PH╟♀I♣Δz8─¶Γ╞Ç▓
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=8ce15d53873821b51db83a5b66ecdf904d1a54eb4d9948a4bc6d431f27cfcdfb10ffa9&i=)
It was so nice and short, until it wasn't.
### Unpacked (42 bytes) and explanation
```
49999{E2B{{om"#qYY>!(AFI"%A|E2B{{om-C_Qf%p
49999{                                 f      Filter range [1..49999]:
      E2B                                       All adjacent pairs of digits
         {{om                                   Each sorted
             "#qYY>!(AFI"%A|                    Literal 2012365478963258741
                            E2B{{om             Pairs of digits, each sorted
                                   -            Set difference
                                    C           Cancel block execution if any remain
                                     _Q         Print current value
                                        %p    Print length
```
2012365478963258741 encodes the keypad. Look at pairs of adjacent digits. Perhaps if I could get a decently short alternative that goes in both directions for each pair, I could cut the eight bytes of `{{om`.
Without that trailing 670, a simple filter would suffice: `f..!` instead of `{..C_Qf%p`. There might be a better way to go about handling this irregularity. In either case, this filter-range behavior is undocumented.
[Answer]
# [PHP](https://php.net/), 145 bytes
```
for(;$i++<5e4;$f&&print$i._)for($f=1,$l=b;''<$d=("$i")[$$i++];$l=$d)$f&=$l>a||strstr([12,240,1053,26,157,2468,359,48,579,68][$l],$d)>'';echo 670;
```
[Try it online!](https://tio.run/##FYvhCoMgFEZfZcQljS5DLc0w24NEjG0VCbHE9bN3dwYfBz4Ox68@dg@fuOyBGnBl2cm5NrDkuQ/ue4C7P4vLwWI5wmbfhpAOJkszcFkxwJWMJgmYilRZ2PrXef6OkEYHLlDUDDmTFQqFXDbpK42VbLHWKJsWlR4H2EZMfU@ImT/rflMNMzH@AQ "PHP – Try It Online")
For every number from 1 to 50,000, checks every digit of that number from left to right. If all digits are in the list of valid digits of the previous digit, that number is printed. At the end prints a hard coded 670 since it takes less bytes than actually counting it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 23 bytes
```
ŽÅKLʒSÌYX;:3‰üαï€OP}=g=
```
[Try it online!](https://tio.run/##ATYAyf9vc2FiaWX//8W9w4VLTMqSU8OMWVg7OjPigLDDvM6xw6/igqxPUH09Zz3///8tLW5vLWxhenk "05AB1E – Try It Online")
Port of [Jonathan Allan's Jelly answer](https://codegolf.stackexchange.com/a/191022/6484).
[Answer]
# Perl 5 (`-M5.01`), ~~96~~, 92 bytes
-4 bytes thanks to @Xcali
```
$r=join"|",map$t++."[^$_]",12,240,1350,26,157,2648,359,48,579,68;map/$r/||say,1..5e4;say 670
```
[TIO](https://tio.run/##K0gtyjH9/1@lyDYrPzNPqUZJJzexQKVEW1tPScPeNjpOJT5WU0nH0EjHyMRAx9DY1EDHyEzH0NQcSJlY6BibWuoAKVNzSx0zC2ugTn2VIv2amuLESh1DPT3TVBNrIFPBzNzg//9/@QUlmfl5xf91fU31DAwB)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~179~~ ~~173~~ ~~151~~ 129 bytes
```
[12,240,1350,26,157,2468,359,48,579,68].map((_,i,l)=>i&&(f=(v,t)=>print(v)|v<5e3&&[...l[t]+''].map(k=>f(v+k,k)))(i,i)),print(670)
```
[Try it online!](https://tio.run/##JctLCoMwEADQ28QZnAZ/iQrVi4gUaRWmURtiCBR691Rw@RbvPYXpeDq2/nZYfs1u@@xm/sY45AUVVUZ5qTIqNOWqPq0bKlVLVUOqbkk3o9wmC/AgphW7noWApYNA/oR1vHsI@At3NZdCDFLKdfBjmiRXM12/QEgNGUQEJkakK@k6wxjjHw "JavaScript (SpiderMonkey) – Try It Online")
-22 bytes thank to Arnauld
-22 bytes thank to dana
# explanation:
```
[12,240,1350,26,157,2468,359,48,579,68] 
// an array where keys are current position and values, the possible destinations
.map((_,i,l)=>                    // loop over it
    i&&(                          // if key is not 0
        f=(v,t)=>                 // create a function
                 print(v)|        // which print the value
                          v<5e3&& // and if the limit is not attained
                                 [...l[t]+''].map(k=>f(v+k,k)) 
                    // recurcively call itself with for each destinations
                                                              )(i,i)),
                    // make the first call with each digit
print(670) // finally print 670
```
---
@dana also gave a 123 bytes solution if we can print 670 first
```
[21,420,5310,62,751,8642,953,84,975,86].map((_,i,a)=>(f=(v,t)=>print(i?v:640)|i&v<5e3&&[...a[t]+''].map(k=>f(v+k,k)))(i,i))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 99 bytes
```
1.upto(5e4){|n|w,*x=n.digits;x.all?{|d|[6,21,43,68,162,340,552,272,672,320][w][w=d]>0}&&p(n)}
p 670
```
[Try it online!](https://tio.run/##KypNqvz/31CvtKAkX8M01USzuiavplxHq8I2Ty8lMz2zpNi6Qi8xJ8e@uialJtpMx8hQx8RYx8xCx9DMSMfYxEDH1NRIx8jcSMcMiI2NDGKjy4HINiXWzqBWTa1AI0@zlqtAwczc4P9/AA "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~28~~ 26 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Δh┤♣É╦&·é╝n$K»à¶▲v═NÆ;↨m≥8
```
[Run and debug it](https://staxlang.xyz/#p=ff68b40590cb26fa82bc6e244baf85141e76cd4e923b176df238&i=&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
G               Call to unbalanced trailing '}', then resume here
670P            Print 670
}               Call target
219J            219 squared (47961)
f               Filter 1-based range by the rest of the program; implicitly output
  $2B           Convert to string and get adjacent pairs; e.g. 213 -> ["21", "13"]
  O             Push 1 under list of pairs
  F             Iterate over pairs, using the rest of the program
    o           Order each pair; e.g. "21" -> "12"
    "{<f:[/T8Z" string literal with code points [123 60 102 58 91 47 84 56 90]
    $           concate as string i.e. "12360102589147845690"
    s#          How many times does the current pair appear in the constant string?
    *           Multiply this by running total.  Any zero will cause the result to be zero.
```
[Run this one](https://staxlang.xyz/#c=G++++++++++++++%09Call+to+unbalanced+trailing+%27%7D%27,+then+resume+here%0A670P+++++++++++%09Print+670%0A%7D++++++++++++++%09Call+target%0A219J+++++++++++%09219+squared+%2847961%29%0Af++++++++++++++%09Filter+1-based+range+by+the+rest+of+the+program%3B+implicitly+output%0A++%242B++++++++++%09Convert+to+string+and+get+adjacent+pairs%3B+e.g.+213+-%3E+[%2221%22,+%2213%22]%0A++O++++++++++++%09Push+1+under+list+of+pairs%0A++F++++++++++++%09Iterate+over+pairs,+using+the+rest+of+the+program%0A++++o++++++++++%09Order+each+pair%3B+e.g.+%2221%22+-%3E+%2212%22%0A++++%22%7B%3Cf%3A[%2FT8Z%22%09string+literal+with+code+points+[123+60+102+58+91+47+84+56+90]%0A++++%24++++++++++%09concate+as+string+i.e.+%2212360102589147845690%22%0A++++s%23+++++++++%09How+many+times+does+the+current+pair+appear+in+the+constant+string%3F%0A++++*++++++++++%09Multiply+this+by+running+total.++Any+zero+will+cause+the+result+to+be+zero.&i=)
The secret sauce is in the string literal `"{<f:[/T8Z"`. After jamming all the codepoints together, you get `12360102589147845690`. The ascending pairs in this string are the valid snake moves.
[Answer]
# [Haskell](https://www.haskell.org/), 118 bytes
```
(filter(and.(zipWith elem.tail<*>map f).show)[1..50000],670)
f c=words"12 024 0135 26 157 2468 359 48 579 68"!!read[c]
```
[Try it online!](https://tio.run/##DcHdCoMgAAbQ@z3FV1c1hqilFay9xi6iCylFmf2gQrCXdzvHqvjR3uccx8o4n3So1L6S6uvOt0sW2uuNJOX88/7a1AlTk2iPq54YIYL@zQ/Z0fpmsIzXEdZYMg7KW1DWCHAJJjrwVvZoxIC2h@gGyL4siqDVOi1z3pTbMeIMbk@I@Qc "Haskell – Try It Online")
A first pass; I'm not good at compression.
The `s=` doesn't count, since we don't actually need to bind the result.
[Ungolfed code](https://tio.run/##TZA/b8IwEMV3f4oTQgIGUP45AaR0aLt0aYcOHVAGixhi4ThRbJWqXz49@0IVL/bvvTv7nhthb1LrcTTyx72qq3IWjkd4acQA2yc4@UPFZuYZSjgLK/HQXRjAKlr5wkWcLDzFRFGSBUwmjFMeOCVO8kDZ1MqLgHwys3wfOCdO@SFgQZiRuSfiBZkHQt/JlP004iZ9jjfjvP7cdfpfNphAmBqW8Kv6L@UakFq2sHZCabBueN/At9CqpsB4@b2Rg8QdgovdtunuYIIyq0SjFT3M/sqXM2b9q@FXTzhO9eASLko7OcBjrlO82/EIV8VYK5QJ83/AekNUQt3hk/2gMNMS6JaZoKW5YhbSx/EP).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 42 bytes
```
≔ΦＩ…·¹×⁵⁰φ⬤ι№”)¶∧XRτ_ΠＧêＲ⁵m⎇λ”✂ιμ⁺²μ¹θθＩＬθ
```
[Try it online!](https://tio.run/##Rc7dCoMgHAXw@z2FdPUXHKhlH3QVwWCwi9j2AiKuBDNK6/Wd62Z3h8Phx1GT3NQibYyd92Z0cDM26A166QPcnbK7N4d@SjdqYAS9zaw9CErQB2NMUGctGIL6ZXcBMsqKqm7KnFPOuChELUrB87Kpq4LRjKCXNUr/9jNBQ5KBp5gUhk9sxe1l2EyS/un88dBuDFNqcRtjvB72Cw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ΦＩ…·¹×⁵⁰φ
```
Process the inclusive range from `1` to `50,000` cast to string.
```
⬤ι№”)¶∧XRτ_ΠＧêＲ⁵m⎇λ”✂ιμ⁺²μ¹θ
```
Filter out those that have pairs of digits not contained in the compressed string `01478963202125458565236987410`.
```
θＩＬθ
```
Output the remaining array and its length.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 34 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
5e4õs f_ä@"-Pì[/Z8"mc øZñÃe
pUl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NWU09XMgZl/kQCItUAHsWy8IWgI4Im1jIPha8cNlCnBVbA&input=Ii1QAexbLwhaAjgi)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 64 bytes
```
{670,grep {[+&](:36<12HGX91H8VCL3MG0FDVQ>X+>m:ov/../)%2},1..5e4}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2szcQCe9KLVAoTpaWy1Ww8rYzMbQyMM9wtLQwyLM2cfY193AzSUs0C5C2y7XKr9MX09PX1PVqFbHUE/PNNWk9n9BaYlCmobmfwA "Perl 6 – Try It Online")
### Explanation
```
{670,grep {...},1..5e4}  # Meet questionable output requirements
# Actual decision problem
     :36<12HGX91H8VCL3MG0FDVQ>  # Bit field of allowed transitions
                                # encoded in base 36
                                 m:ov/../  # All 2-digit substrings
                              X+>  # Right shift by each substring
                                   # (implicitly converted to an integer)
[+&](                                    )  # Binary and
                                          %2  # Modulo 2
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~68~~ ~~65~~ 45 bytes
```
l
f.Am}dCtB+J`65874589632012541_PJCtB`TS50000
```
[Try it online!](https://tio.run/##K6gsyfj/P4crTc8xtzbFucRJ2yvBzNTC3MTUwtLM2MjA0MjUxDA@wAsokxASbGoABP//AwA "Pyth – Try It Online")
Inspiration for the revised lookup process came from [Khuldraeseth na'Barya's Stax answer](https://codegolf.stackexchange.com/a/191029/41020), go give them an upvote!
---
Edit 2: Rewrote to save a bunch of bytes, previous version: 
```
l
f.Am}ed@c"12 024 0135 26 157 2468 359 48 579 68";shdCtB`TS50000
```
---
Edit: Golfed 3 bytes by using string lookups, previous version:
```
l
f.Am}ed@sMMc"12 024 0135 26 157 2468 359 48 579 68";hdCtBjT;S50000
```
]