Last active
September 22, 2018 15:45
-
-
Save ShenTengTu/cdaf8cb43c8e7e6c69f7ef000ad4af2d to your computer and use it in GitHub Desktop.
Get binomial coefficients of Pascal's triangle.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pascal(n) { | |
if (n === 0) | |
return [1]; | |
let prev = n - 1; | |
let times = prev; | |
let leftLength = Math.floor(n / 2) + 1; | |
let lead = Array(prev).fill(1); | |
let temp = [1]; | |
let result_l = [1]; | |
let result_r = [1]; | |
for (let t = leftLength; t > 1; t--) { | |
times--; | |
for (let i = 0; i <= times; i++) { | |
temp.push(temp[i] + lead[i]); | |
} | |
lead = temp.slice(1, t + 3); | |
result_l.push(lead[lead.length - 1]); | |
if (result_r.length < leftLength - (prev) % 2) | |
result_r.unshift(lead[lead.length - 1]); | |
temp = [1]; | |
} | |
return result_l.concat(result_r); | |
} | |
for (let i = 0; i <= 8; i++) | |
console.log(pascal(i)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def pascal(n) : | |
if n == 0 : | |
return [1] | |
prev = n - 1 | |
times = prev | |
leftLength = int( n / 2 ) + 1 # Math.foor | |
lead = [1] * prev # Array(prev).fill(1) | |
temp = [1] | |
result_l = [1] | |
result_r = [1] | |
for t in range(leftLength, 1, -1) : # 1 < t <= leftLength | |
times = times - 1 | |
for i in range(0, times + 1) : # 0 <= i < times + 1 | |
temp.append(temp[i] + lead[i]) # Array.push | |
lead = temp[1:t+3] # Array.slice | |
result_l.append(lead[len(lead)-1]) # Arrray.push | |
if len(result_r) < (leftLength - prev % 2) : | |
result_r = [ lead[len(lead)-1] ] + result_r # Array.unshift | |
temp = [1] | |
return result_l + result_r # Array.cocat | |
for i in range(8) : | |
print(pascal(i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment