Skip to content

Instantly share code, notes, and snippets.

@Shou
Created June 6, 2018 11:16
Show Gist options
  • Save Shou/2691575680093def22c8561c0e354fe9 to your computer and use it in GitHub Desktop.
Save Shou/2691575680093def22c8561c0e354fe9 to your computer and use it in GitHub Desktop.
Pascal exercises
pascal :: Int -> [[Int]]
pascal n = take n $ snd (foldl go ([], []) [0 .. n])
where
go :: ([Int], [[Int]]) -> Int -> ([Int], [[Int]])
go ([], []) _ = ([1,1], [[1], [1,1]])
go (lst, xs) _ = let newLst = sub lst False in (newLst, xs ++ [newLst])
sub :: [Int] -> Bool -> [Int]
sub (first : second : rest) False = 1 : first + second : sub (second : rest) True
sub (first : second : rest) True = first + second : sub (second : rest) True
sub [x] t = [1]
sub [] t = []
function makeRow(oldRow) {
let oldN = null
let newRow = []
for (const n of oldRow) {
if (oldN == null) {
newRow.push(1)
oldN = 1
} else {
newRow.push(oldN + n)
oldN = n
}
}
newRow.push(1)
return newRow
}
function pascal(n) {
let oldRow = null
let rows = []
for (let i = 0; i < n; i++) {
console.log(oldRow, 'oldRow')
if (oldRow == null) {
rows = [[1]]
} else {
const newRow = makeRow(oldRow)
rows.push(newRow)
}
oldRow = rows[i]
}
return rows
}
function main() {
console.log(pascal(1))
console.log(pascal(2))
console.log(pascal(3))
console.log(pascal(5))
console.log(pascal(10))
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment