n=>(F=_=>f>n?((G=(n,z=0,x=f,y=l,b=[...a])=>y?G(n%(x/=y),+b.splice(n/x,1)+z*10,x,y-1,b):z)(n--)-G(n))/9:F(a.push(++l),f*=l))(a=[l=f=1])
オンラインでお試しください!
1インデックス付き。
@ guest271314の意見は正しい。直接置換計算はより短いです...
説明
n=>( // Function -
F=_=> // Helper func to calculate length needed
f>n? // If f > n (meaning the length is enough) -
(
(
G=( // Helper func to calculate permutation value -
n,
z=0, // Initial values
x=f, // Made as copies because we need to alter
y=l, // these values and the function will be
b=[...a] // called twice
)=>
y? // If still elements remaining -
G(
n%(x/=y), // Get next element
+b.splice(n/x,1)+z*10, // And add to the temporary result
x,
y-1, // Reduce length
b // Remaining elements
)
:z // Otherwise return the permutation value
)(n--)-G(n) // Calculate G(n) - G(n - 1)
)/9 // ... the whole divided by 9
:F(
a.push(++l), // Otherwise l = l + 1, push l into the array
f*=l // ... and calculate l!
)
)(
a=[l=f=1] // Initial values
)
元のソリューション(159バイト)
n=>(x=l=t=0n,P=(a,b=[])=>n?""+a?a.map(z=>P(a.filter(y=>y-z),[...b,z])):(v=b.reduce((u,y)=>u=u*10n+y),x?--n?0:t=v-x:0,x=v):0)([...Array(n+1))].map(_=>++l))&&t/9n
オンラインでお試しください!
リンクはパフォーマンスのために作られた長いバージョンへのリンクです。デモを動作させるためにArray(n+1)なりArray(Math.min(n+1,15))ます。理論的には、無限まで(実際にはスタック制限まで)機能します。
説明
説明しきれないほどたくさんあります。
n=>( // Function
x=l=t=0n, // Initialization
P=( // Function to determine the permutation -
a, // remaining items
b=[] // storage
)=>
n? // if we haven't reached the required permutation yet -
""+a? // if we haven't the last layer of loop -
a.map( // loop over the entries -
z=>
P( // recurse -
a.filter(y=>y-z), // pick out the selected number
[...b,z] // append to next
)
)
:( // if we are at the last layer -
v=b.reduce((u,y)=>u=u*10n+y), // calculate the value of the permutation
x? // if not the first number -
--n? // if not the last -
0 // do nothing
:t=v-x // else calculate difference
:0, // else do nothing
x=v // record ot anyway
)
:0 // else do nothing
)
(
[...Array(n+1)].map(_=>++l) // the list of numbers to permute
)&&t/9n // last difference divided by 9