Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2183 from AkifhanIlgaz/1137
Browse files Browse the repository at this point in the history
Create: 1137-n-th-tribonacci-number
  • Loading branch information
tahsintunan authored Feb 1, 2023
2 parents 7c0aaa7 + 7a552de commit 981c896
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 0 deletions.
29 changes: 29 additions & 0 deletions go/1137-n-th-tribonacci-number.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

func main() {

}

func tribonacci(n int) int {
t := [3]int{0, 1, 1}

if n < 3 {
return t[n]
}

for i := 3; i < n+1; i++ {
t[0], t[1], t[2] = t[1], t[2], sum(t)
}

return t[2]
}

func sum(arr [3]int) int {
total := 0

for _, val := range arr {
total += val
}

return total
}
19 changes: 19 additions & 0 deletions javascript/1137-n-th-tribonacci-number.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @param {number} n
* @return {number}
*/
var tribonacci = function (n) {
let t = [0, 1, 1];

if (n < 3) return t[n];

for (let i = 3; i < n + 1; i++) {
[t[0], t[1], t[2]] = [t[1], t[2], sum(t)];
}

return t[2];
};

function sum(arr) {
return arr.reduce((a, b) => a + b);
}
17 changes: 17 additions & 0 deletions rust/1137-n-th-tribonacci-number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
impl Solution {
pub fn tribonacci(n: i32) -> i32 {
let mut t = [0, 1, 1];

if n <= 2 {
return t[n as usize];
}

for i in 3..(n + 1) as usize {
t.swap(0, 1);
t.swap(1, 2);
t[2] = t.iter().sum();
}

t[2]
}
}
15 changes: 15 additions & 0 deletions typescript/1137-n-th-tribonacci-number.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function tribonacci(n: number): number {
let t = [0, 1, 1];

if (n < 3) return t[n];

for (let i = 3; i < n + 1; i++) {
[t[0], t[1], t[2]] = [t[1], t[2], sum(t)];
}

return t[2];
}

function sum(arr: number[]): number {
return arr.reduce((a, b) => a + b);
}

0 comments on commit 981c896

Please sign in to comment.