|
| 1 | +export {}; |
| 2 | + |
| 3 | +// O(1) - Constant Time |
| 4 | +function secondsInDays(numberOfDays: number): number { |
| 5 | + if (numberOfDays <= 0 || !Number.isInteger(numberOfDays)) { |
| 6 | + throw new Error('Invalid number of days'); |
| 7 | + } |
| 8 | + return 60 * 60 * 24 * numberOfDays; |
| 9 | +} |
| 10 | + |
| 11 | +console.log('O(1) - Constant Time'); |
| 12 | +console.log('Seconds in 1 day: ', secondsInDays(1)); // 86400 |
| 13 | +console.log('Seconds in 10 days: ', secondsInDays(10)); // 864000 |
| 14 | +console.log('Seconds in 100 days: ', secondsInDays(100)); // 8640000 |
| 15 | + |
| 16 | +// O(n) - Linear Time |
| 17 | +function calculateTotalExpenses(monthlyExpenses: number[]): number { |
| 18 | + let total = 0; |
| 19 | + for (let i = 0; i < monthlyExpenses.length; i++) { |
| 20 | + total += monthlyExpenses[i]!; |
| 21 | + } |
| 22 | + return total; |
| 23 | +} |
| 24 | + |
| 25 | +console.log('*******************'); |
| 26 | +console.log('O(n) - Linear Time'); |
| 27 | +console.log('January: ', calculateTotalExpenses([100, 200, 300])); // 600 |
| 28 | +console.log('February: ', calculateTotalExpenses([200, 300, 400])); // 900 |
| 29 | +console.log('March: ', calculateTotalExpenses([30, 40, 50, 100, 50])); // 270 |
| 30 | + |
| 31 | +// O(n^2) - Quadratic Time |
| 32 | +function calculateExpensesMatrix(monthlyExpenses: number[][]): number { |
| 33 | + let total = 0; |
| 34 | + for (let i = 0; i < monthlyExpenses.length; i++) { |
| 35 | + for (let j = 0; j < monthlyExpenses[i]!.length; j++) { |
| 36 | + total += monthlyExpenses[i]![j]!; |
| 37 | + } |
| 38 | + } |
| 39 | + return total; |
| 40 | +} |
| 41 | + |
| 42 | +console.log('************************'); |
| 43 | +console.log('O(n^2) - Quadratic Time'); |
| 44 | +const monthlyExpenses = [ |
| 45 | + [100, 105, 100, 115, 120, 135], |
| 46 | + [180, 185, 185, 185, 200, 210], |
| 47 | + [30, 30, 30, 30, 30, 30], |
| 48 | + [2000, 2000, 2000, 2000, 2000, 2000], |
| 49 | + [600, 620, 610, 600, 620, 600], |
| 50 | + [150, 100, 130, 200, 150, 100] |
| 51 | +]; |
| 52 | +console.log('Total expenses: ', calculateExpensesMatrix(monthlyExpenses)); // 18480 |
| 53 | + |
| 54 | +// calculating the time complexity of the function calculateExpensesMatrix |
| 55 | +function multiplicationTable(num: number, x: number): void { |
| 56 | + let s = ''; |
| 57 | + const numberOfAsterisks = num * x; |
| 58 | + for (let i = 1; i <= numberOfAsterisks; i++) { |
| 59 | + s += '*'; |
| 60 | + } |
| 61 | + console.log(s); |
| 62 | + |
| 63 | + for (let i = 1; i <= num; i++) { |
| 64 | + console.log(`Multiplication table for ${i} with x = ${x}`); |
| 65 | + for (let j = 1; j <= x; j++) { |
| 66 | + console.log(`${i} * ${j} = `, i * j); |
| 67 | + } |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +// to see the output of this file use the command: node src/02-bigOnotation/01-big-o-intro.ts |
0 commit comments