Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Function 1:
- * This is based on the observation that the 3 different example
- * series were all contained in the larger series:
- * 6 : 6, 3, 10, 5, 8, 4, 2, 1
- * 10 : 10, 5, 8, 4, 2, 1
- * 4 : 4, 2, 1
- * So, if I just produced all the numbers in the series, then this
- * should work fine. This approach is more general than just handling
- * 6, 10, and 4. It handles all of the numbers given in series.
- * However... there's not enough information in the question to
- * suggest that this was a CORRECT generalization.
- */
- function seriesOf(num) {
- function next(num) {
- if (num == 6) return 3;
- if (num == 3) return 10;
- if (num == 10) return 5;
- if (num == 16) return 8;
- if (num == 8) return 4;
- if (num == 4) return 2;
- if (num == 2) return 1;
- }
- if (num == 1) return [1];
- else {
- let series = [num];
- while () {
- let n = next(num);
- series.push(n);
- if (n == 1) break;
- }
- return series;
- }
- }
- /* Function 2:
- * Source: <https://en.wikipedia.org/wiki/Collatz_conjecture>
- */
- function seriesOf(num) {
- function collatz(num) {
- return (num % 2 == 0) ? num / 2 : 3*num + 1;
- }
- let series = [num];
- while(collatz(num) != 1) series.push(collatz(num));
- return series;
- }
- /* Function 3:
- * This was the initial pattern that I saw. After sleeping on it, I
- * remembered that I saw a similar sequence before as part of a
- * problem in a class of mine. The sequence is from the Collatz'
- * Conjecture problem, and it turns out that the Collatz' sequence if
- * probably what this problem was hunting for. However, the quesion
- * doesn't actually say enough to guarantee that.
- *
- * Note that, while my function might look similar to collatz, it's
- * different, because for some numbers, the produced results would be
- * different.
- */
- function seriesOf(num) {
- let series = [num];
- let current = num;
- // position in sequence of element at the end of series.
- let posInSequence = 0;
- function isPowerOf2(num) {
- // A number is a power of two if it's base 2 logarithm is an
- // integer.
- let actual = Math.log2(num);
- let nearestIntegerExponent = Math.round(actual);
- return actual == nearestIntegerExponent;
- }
- function isOdd(n) { return (n % 2) == 1; };
- function isEven(n) { return !isOdd(n); };
- while (true) {
- if (isPowerOf2(current)) series.push(current / 2);
- if (isEven(posInSequence)) series.push(current / 2);
- if (isOdd(posInSequence)) series.push(3 * current + 1);
- posInSequence++;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement