Skip to content

Commit c7e85f6

Browse files
Merge pull request #90 from wakidurrahman/feat/coding-challenges-lucky_sevens
feat: implement
2 parents 5895bf5 + b7c7831 commit c7e85f6

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/code-challenges/bubble-sort.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,54 @@ const bubbleSortVariationRecursive = function (array, pointer = array.length - 1
4646
};
4747

4848
bubbleSortVariationRecursive([6, 5, 3, 1, 8, 7, 2, 4]);
49+
50+
/**
51+
* Lucky Sevens
52+
* 002: Write a function called lucky_sevens which takes an array of integers and returns true if any three consecutive elements sum to 7.
53+
*/
54+
55+
function luckySevensVariationOne(arrayOfIntegers) {
56+
// Array length
57+
const len = arrayOfIntegers.length;
58+
// If array of length is less than 3 elements then this challenge is not possible.
59+
if (len < 3) {
60+
return 'Not possible';
61+
}
62+
63+
// Because we know there are at least 3 elements we can
64+
// Start the loop at the 3rd element in the array (i = 2);
65+
// and check it along with the two previous elements (i - 1) and (i - 2)
66+
67+
for (let i = 0; i < len; i++) {
68+
if (arrayOfIntegers[i] + arrayOfIntegers[i - 1] + arrayOfIntegers[i - 2] === 7) {
69+
return true;
70+
}
71+
}
72+
73+
// if loop is finished and no elements summed to 7;
74+
return false;
75+
}
76+
77+
luckySevensVariationOne([2, 1, 5, 1, 0]);
78+
79+
function luckySevensVariationTwo(array) {
80+
const len = array.length;
81+
82+
// Iterate through the array.
83+
84+
for (let i = 0; i < len - 2; i++) {
85+
let sum = array[i] + array[i + 1] + array[i + 2];
86+
87+
if (sum === 7) {
88+
return true; // Found three consecutive elements that sum to 3;
89+
}
90+
}
91+
92+
return false; // No three consecutive elements sum to 7;
93+
}
94+
95+
let numbersOfLuckySeven = [1, 2, 3, 4, 5, 6, 1];
96+
console.log(luckySevensVariationTwo(numbers)); // Output: true
97+
98+
var numbers2OfLuckySeven = [1, 2, 3, 4, 5, 6, 2];
99+
console.log(luckySevensVariationTwo(numbers2OfLuckySeven)); // Output: false

0 commit comments

Comments
 (0)