-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReal_Interview_Questions.js
More file actions
101 lines (85 loc) · 2.42 KB
/
Real_Interview_Questions.js
File metadata and controls
101 lines (85 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* FinacPlus Software Interview Question
* Write a special cipher that is a combination of Caesar’s cipher followed by a simple
* RLE. The function should receive a string and the rotation number as parameters.
* Input: special Cipher(“AABCCC”, 3) Output: D2EF3
*/
function specialCipher(str, rotation) {
// Step 1: Caesar Cipher
let shifted = "";
for (let ch of str) {
let code = ch.charCodeAt(0) - 65;
let newChar = String.fromCharCode(((code + rotation) % 26) + 65);
shifted += newChar;
}
// Step 2: RLE
let result = "";
let count = 1;
for (let i = 1; i <= shifted.length; i++) {
if (shifted[i] === shifted[i - 1]) {
count++;
} else {
result += shifted[i - 1];
if (count > 1) result += count;
count = 1;
}
}
return result;
}
// Example
// console.log(specialCipher("AABCCC", 3)); // D2EF3
/**
* Prob-8 Shop with 6 units
* Write a program that finds the most optimized set of 6 units to shop with for values
* fewer than 100. Example: Units used are 1, 2, 5, 10, 20, 50 1: 1 (1 unit used) 2: 2 (1
* unit used) 3: 1+2 (2 units used) 4: 2+2 (2 units used) … 98: 1+2+5+20+20+50 (6 units
* used) 99: 2+2+5+20+20+50 (6 units used) AVG of units = 3.4
*/
function shopWith6Units(amount) {
const units = [1, 2, 5, 10, 20, 50];
const dp = Array.from({ length: amount + 1 }, () => ({
units: [],
count: Infinity,
}));
dp[0].count = 0;
for (let i = 1; i <= amount; i++) {
for (let unit of units) {
if (i >= unit) {
const newCount = dp[i - unit].count + 1;
if (newCount < dp[i].count) {
dp[i].count = newCount;
dp[i].units = [...dp[i - unit].units, unit];
}
}
}
}
return dp[amount].units;
}
// Example
// console.log(shopWith6Units(99)); // [ 50, 20, 20, 5, 2, 2 ]
// Function Currying
function sum(a) {
return function (b) {
return function (c) {
return a + b + c;
}
};
}
// Example
// console.log(sum(2)(3)(4)); // 9
// Generator Function to yield Fibonacci numbers
function* fibonacciGenerator() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a + b];
}
}
// Example
// const fibGen = fibonacciGenerator();
// console.log(fibGen.next().value); // 0
// console.log(fibGen.next().value); // 1
// console.log(fibGen.next().value); // 1
// console.log(fibGen.next().value); // 2
// console.log(fibGen.next().value); // 3
// console.log(fibGen.next().value); // 5