Generate Keyboard Friendly Numbers
Pyth, 27 24 bytes
uf!f/h-FY3.:metsd`T2hGQ0
Demonstration.
Improvements to the original:
Using
metd
, instead of.r ... _UJ
: 2 less bytes. 1 direct, 1 for not having to use J.Using
s
and`T
instead ofJT10
: 1 less byte.
We start with the string representation of a number: `T
.
Then, we convert the string to a list of digits, and rotate the digits digits backwards by one, (9876543210) with metsd
. Then, we take the 2 element subsequences with .: ... 2
. These subsequences are filtered on /h-FY3
. This expression corresponds to ((a-b)+1)/3
, which is zero if and only if the difference between a
and b
is at most 1. Thus, the filtered list will be empty if and only if the number is keyboard friendly. With !
, the result is true only if the number is keyboard friendly.
f ... hG
filters upwards from G+1
until the result is true, giving the first keyboard friendly number at G+1
or above. u ... Q0
applies this function to its own output Q
times, starting from 0, where Q
is the input. This gives the Q
th Keyboard Friendly Number, as desired.
Python 3, 112 102 bytes
f=lambda n,k=0:n+1and f(n-all(-2<~-int(a)%10-~-int(b)%10<2for a,b in zip(str(k),str(k)[1:])),k+1)or~-k
We keep track of the count of friendly numbers still needed to find in n
and the last checked number in k
.
5 and 5 bytes saved thanks to @isaacg and @Sp3000.
CJam, 29 28 bytes
ri_4#{AbAfe|_1>.-W<3,:(-!},=
Try it online in the CJam interpreter.