O enésimo número de Motzkin é o número de caminhos de (0, 0) a (n, 0) em que cada etapa tem a forma (1, -1), (1, 0) ou (1, 1) e o caminho nunca fica abaixo de y = 0.
Aqui está uma ilustração desses caminhos para n = 1, 2, 3, 4, no link acima:
A sequência desejada é OEIS A001006 . OEIS tem algumas outras caracterizações da sequência.
Você receberá um número inteiro positivo n como entrada. Você deve emitir o enésimo número Motzkin.
Aqui estão os números 1 a 10 de Motzkin:
1, 2, 4, 9, 21, 51, 127, 323, 835, 2188
Todos os métodos padrão de entrada e saída são permitidos. Aplicam-se brechas padrão .
Isso é código de golfe. Menos bytes ganha.
Respostas:
MATL , 13
14bytesExemplo:
EDIT (16 de junho de 2017): você pode experimentá-lo online! Observe também que nas versões modernas do idioma (que pós esse desafio)
i
foram removidas.Explicação
Bem simples, usando a equivalência (veja a equação (10)) com o método função hipergeométrica :
A partir da definição da função hipergeométrica
é claro que a ordem dos dois primeiros argumentos pode ser trocada, o que economiza um byte.
fonte
Retina,
5958 bytesTakes input in unary. Input 7 (i.e.
1111111
) takes quite a while but still completes in less than a minute. I wouldn't go much further than that.Try it online.
Explanation
A different characterisation of the Motzkin numbers is the number of strings of three different characters, where two of them are correctly balanced (hence the close relation to Catalan numbers, which are the same without the third character which is independent of the balancing).
.NET's balancing groups are pretty good at detecting correctly matched strings, so we simply generate all strings of length
N
(using_
,<
and>
as the three characters) and then we count how many of those are correctly balanced. E.g. forN = 4
the valid strings are:Compared with the definition in the challenge,
_
corresponds to a(1,0)
step,<
to(1,1)
and>
to(1,-1)
.As for the actual code, the
:
is used as a separator between the different strings. The second regex is just a golfed form of the standard .NET regex for balanced strings.Something to note is that there is only a single
:
inserted between strings in each step, but the second regex matches a leading and a trailing:
(and since matches cannot overlap, this means that adjacent strings generated from one template in the last step cannot both match). However, this is not a problem, because at most one of those three can ever match:_
matches, the prefix without that_
is already balanced correctly, and<
or>
would throw off that balance.>
matches, the string is balanced with that>
, so_
or<
would throw off that balance.<
can never be balanced.fonte
Python 2, 51 bytes
Uses the formula from Mathworld
Saves chars by putting the
M[n-1]
term into the summation ask=n-1
, which givesM[-1]*M[n-1]
, withM[-1]=1
as part of the initial condition.Edit: One char shorter writing the sum recursively:
Other approaches that turned out longer:
fonte
Pyth, 15 bytes
This defines a function
y
. Try it online: DemonstrationExplanation:
Let
y[n]
be then
-th Motzkin Number. I calculatey[n]
with the formulaNotice that the first vector is larger than the second one (except when calculating
y[0]
). When this is the case, than Pyth automatically ignores the 1 at the end of the first vector, so that both vectors are of equal length.This formula is a variation of one of the formulas listed on OEIS. It may be a little bit stupid. Because of the 1 at the end of the first vector (which make the lengths unequal), I don't actually have to give the recursion a base case. And I had hopes, that the two
+...1
s can be golfed somehow. Turns out I can't.You can define a similar recursion with a dot product of equal length vectors and define the base case
y[0] = 1
with with the same byte count.fonte
CJam (20 bytes)
Online demo
As Mego noted in the comments on the question, this is very closely related to the Catalan numbers: change the
.5
to1
and offset the index by one (or simply remove the.5
entirely and leave the index unchanged) to get Catalan numbers.The recurrence used is
from the OEIS page. The corresponding recurrence for the Catalan numbers is listed as
fonte
Seriously, 21 bytes
Borrows some code from quintopia's Catalan Numbers solution, specifically the improvement I made in the comments.
I use the following formula:
Since
nCk
is 0 fork > n
, I sum all the way ton-1
, since those values will all be 0 and thus do not affect the sum.Try it online
Explanation:
fonte
C(n, 2*k)
does what now?C(n,k) = nCk
, or the number of combinations ofk
items from a pool ofn
items.R, 64 bytes
Uses also the Mathworld formula of @xnor's python answer. Thanks to rules of precedence,
2:n-2
is equivalent to0:(n-2)
.Test cases:
fonte
Mathematica,
3130 bytesFor fun, here's a 37 byte version
and 52 byte version
fonte
Jelly,
171413 bytesThis uses the recurrence relation from @PeterTaylor's answer. Try it online!
How it works
fonte
Mathematica,
444234 bytesA 35 bytes version:
fonte
Pari/GP,
383626 bytesTry it online!
Using equation (11) from MathWorld:
where(nk)2 is a trinomial coefficient. By definition, (nk)2 is the coefficient of xn+k in the expansion of (1+x+x2)n .
fonte
);;7 2D$ⁿ$)╡$÷
. I won't post it as an answer because the language is newer than the question.05AB1E,
1312 bytesTry it online!
While most answers use a formula or recurrence relation, this is a simple counting approach.
Each possible path through the grid is represented by the list of its y coordinates. For n segments, there are a total of (n+1) points, but the first and last one are necessarily 0, so that leaves (n-1) points to specify.
We now have a list of paths (not yet including the initial and final 0). By construction, none of them ever go below 0. However, some of them have illegal slopes (e.g. jump from 0 to 2), so we need to filter them out.
Ÿ
is the fluctuating range built-in. If there's any pair of non-adjacent numbers, it will fill in the missing numbers (e.g. [0, 2] becomes [0, 1, 2]). Only legal paths will be left unchanged.A perhaps more intuitive way to check for illegal slopes would be
üαà
(assert the maximum of pairwise absolute differences equals 1). However, this misses the flat [0, 0, ... 0] path, which costs one extra byte to fix.Finally, note that the actual code uses
.ø
where this explanation uses0.ø
. Instead of surrounding the path with 0s, this surrounds the implicit input with two copies of the path. This turns the coordinate system upside-down and inside-out, but is otherwise equivalent.fonte
Stax, 12 bytes
Run and debug it
I don't know how to do fancy math typesetting, but this essentially relies on a dynamic programming construction
fonte
Ruby, 50
straightforward implementation of the recurrence relation.
fonte
Brain-Flak, 90 bytes
Try it online!
Computes(n0)2−(n2)2 , where (nk)2 is a trinomial coefficient. I couldn't find this formula anywhere, so I can't reference it, but it can be proved in the same way as the analogous formula Cn=(2nn)−(2nn+1) .
fonte
ES6, 44 bytes
Straightforward port of @xnor's recursive Python solution. Needs
n<1?1:
becausen<1||
would makef(0)
returntrue
.fonte
Haskell, 55 bytes
Straightforward implementation of the recursion.
Try it online!
fonte