「組合わせ」を返す関数
function mathematics (ary = [ ], n = ary.length) { if (1 === n) { return ary.map (a=> [a]); } else { return ary.flatMap ((a, i)=> mathematics (ary.slice (i), n -1).map (b=> [a,...b])) } } console.log (mathematics ([1,2,3],3)); /* [1,1,1], [1,1,2], [1,1,3], [1,2,2], [1,2,3], [1,3,3], [2,2,2], [2,2,3], [3,3,3] */
やっぱり1行で済ます
const mathematics=((f=(a=[],b=a.length)=>b==1?a.map(c=>[c]):a.flatMap((c,d)=>f(a.slice(d),b-1).map(d=>[c,...d])))=>f)();
で目的は
Javascript で、0000 から 9999 までの表を作りたい。 -HTML の <table- JavaScript | 教えて!goo
<!DOCTYPE html> <title></title> <meta charset="utf-8"> <style> td { text-align: right; width: 6em;} </style> <body> <table border="1" id="T"></table> <script> const ary2tbody=(a,b=document.createElement('tbody'))=>a.reduce((b,a)=>(a.reduce((c,d)=>(c.insertCell().append(d||''),c),b.insertRow()),b),b), transpose=a=>a[0].map((_,i)=>a.map(b=>b[i])), mathematics=((f=(a=[],b=a.length)=>b==1?a.map(c=>[c]):a.flatMap((c,d)=>f(a.slice(d),b-1).map(d=>[c,...d])))=>f)(), sum=(a,b)=>a+b; const A = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const B = [[0], ...mathematics (A,1), ...mathematics (A,2), ...mathematics (A,3), ...mathematics (A,4)]; const C = [...Array(10)].map (()=>[]); B.forEach (a=> C[a.reduce (sum, 0) % 10].push (a ? a.join``.padStart (4,0) : '')); ary2tbody (transpose(C), T); </script>