There are p, q and r balls. arrange balls in a straight line such that no two balls of the same type are adjacent.
Building upon understanding of Arrange balls (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def arrange(p, q, r): cache = [[[{'p': 0, 'q': 0, 'r': 0} for _ in range(r + 1)] for _ in range(q + 1)] for _ in range(p + 1)] cache[1][0][0]['p'] = 1 cache[0][1][0]['q'] = 1 cache[0][0][1]['r'] = 1 for i in range(p + 1): for j in range(q + 1): for k in range(r + 1): for l in cache[i][j][k]: if i == 0 and j == 0 and k == 0: continue if l == 'p': if i > 0: cache[i][j][k]['p'] += cache[i - 1][j][k]['q'] + cache[i - 1][j][k]['r'] elif l == "q": if j > 0: cache[i][j][k]['q'] += cache[i][j - 1][k]['p'] + cache[i][j - 1][k]['r'] else: if k > 0: cache[i][j][k]['r'] += cache[i][j][k - 1]['q'] + cache[i][j][k - 1]['q'] return cache[p][q][r]['p'] + cache[p][q][r]['q'] + cache[p][q][r]['r'] p = 1 q = 1 r = 1 print(arrange(p, q, r))
function arrange(p, q, r) { const cache = []; for (let i = 0; i <= p; i++) { cache[i] = []; for (let j = 0; j <= q; j++) { cache[i][j] = [] for (let k = 0; k <= r; k++) { cache[i][j][k] = { p: 0, q: 0, r: 0 } } } } cache[1][0][0]['p'] = 1; cache[0][1][0]['q'] = 1; cache[0][0][1]['r'] = 1; for (let i = 0; i <= p; i++) { for (let j = 0; j <= q; j++) { for (let k = 0; k <= r; k++) { for (let l in cache[i][j][k]) { if (i == 0 && j == 0 && k == 0) { continue; } switch(l) { case 'p': if (i > 0) { cache[i][j][k]['p'] += cache[i - 1][j][k]['q'] + cache[i - 1][j][k]['r']; } break; case 'q': if (j > 0) { cache[i][j][k]['q'] += cache[i][j - 1][k]['p'] + cache[i][j - 1][k]['r']; } break; default: if (k > 0) { cache[i][j][k]['r'] += cache[i][j][k - 1]['q'] + cache[i][j][k - 1]['q']; } break; } } } } } return cache[p][q][r]['p'] + cache[p][q][r]['q'] + cache[p][q][r]['r']; } const p = 1; const q = 1; const r = 1; console.log(arrange(p, q, r))