The Odin Project - Fundamentals 4 Exercises - sumAll - javascript

I am stuck in the sumAll exercise from the Fundamentals 4 portion of the Odin Project. I managed to pass the test in which I need the result to be ‘ERROR’. However, I cannot figure out the correct code to pass the other tests. Where did I go wrong?
This is the exercise:
const sumAll = require(’./sumAll’)
describe(‘sumAll’, function() {
it(‘sums numbers within the range’, function() {
expect(sumAll(1, 4)).toEqual(10);
});
it(‘works with large numbers’, function() {
expect(sumAll(1, 4000)).toEqual(8002000);
});
it(‘works with larger number first’, function() {
expect(sumAll(123, 1)).toEqual(7626);
});
it(‘returns ERROR with negative numbers’, function() {
expect(sumAll(-10, 4)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, “90”)).toEqual(‘ERROR’);
});
it(‘returns ERROR with non-number parameters’, function() {
expect(sumAll(10, [90, 1])).toEqual(‘ERROR’);
});
});
My code:
const sumAll = function(a, b) {
const arr = [];
if (a < b) {
while (a <= b) {
arr.push(a++);
}
} else if (b < a) {
while (b <= a) {
arr.push(b++);
}
} else {
arr.push(a);
}
if (a < 0 || b < 0) {
return “ERROR”;
} else if (typeof a !== NaN || typeof b !== NaN) {
return “ERROR”;
}
return arr.reduce((a, b) => a + b);
}
module.exports = sumAll

I made in this way:
const sumAll = function (x, y) {
if (x > 0 && y > 0 && typeof x === 'number' && typeof y === 'number') {
var valorx = x;
var valory = y;
var total = 0;
if (x < y) {
for (var i = valorx; i <= valory; i++) {
total += i;
}
return total;
} else if (x > y) {
for (var i = valory; i <= valorx; i++) {
total += i;
}
return total;
}
} else {
return 'ERROR'
}
}
module.exports = sumAll

this how it work for me
const sumAll = function (startN, endN) {
//create variable to store total sum
let sum = 0;
check if input parameter in number:
if (typeof startN != "number" || typeof endN != "number") return "ERROR";
check if input numbers greter than 0:
else if (startN < 0 || endN < 0) return "ERROR";
and last check is, if last number greater than the first number then initial number will be the last number otherwise start number will be the initial:
else if (startN < endN) {
for (i = startN; i <= endN; i++) {
sum += i;
}
} else {
for (i = endN; i <= startN; i++) {
sum += i;
}
}
then return sum:
return sum;
};
you can make all these in one check but this are more readable.

That's how i did it. Quite similar but i avoided using for loops.
const sumAll = function(n,m) {
if (n<0 || m<0 || typeof(m) !== 'number' || typeof(n) !== 'number'){
return 'ERROR'
}else {
if(n<m){
n1 = n
n2 = m
}else{
n1 = m
n2 = n
}
return (n1+n2)*(n2/2)}
};
I first checked whether the input is valid, then decided the values of the two variables depending on which is bigger and finally calculated the sum.

Related

How to add to a variable when addition is in an for-loop

This is a problem from codewars. Heres my code.
function narcissistic(value) {
var total = 0
var valLength = value.length
const digit = [...`${value}`];
for(var i = 0; i < value.length; i++){
total += Math.pow(value.length , digit)
}
if(total == value){ return true
} else {
return false
}
}
The problem I'm having is I don't why when I do total += value.length * digit[i] it isn't adding to total. Any ideas?
You can try something like this:
You need to convert the function parameters into an array with different values and then calculate the power of each number and then add to the total.
Also, try to use let instead of var as it is better for block-level scope.
function narcissistic(value) {
let total = 0;
const digit = [...`${value}`];
for (let i = 0; i < digit.length; i++) {
total += Math.pow(digit[i], digit.length);
}
if(total === value) {
return true;
} else {
return false;
}
}
console.log(narcissistic(153));
console.log(narcissistic(432));
This function can return you the required value
function narcissistic(value) {
const stringValue = [...`${value}`];
const len = stringValue.length;
const sum = stringValue.reduce((prev, current) => {
return prev + Math.pow(parseInt(current, 10), len);
}, 0)
return `${value}` === sum.toString();
}

Run IndexOf more than one time JS

How to search multiple same values and look if it meets the conditions without regex? Suppose that I have this string ***6**5****8*9***2
What I need to do is to check if the string has at least three times *** altogether and then if the number before and after the *** sums 11. In the example given, these conditions are met because: First, the string has three *** altogether, and then 9 + 2 is 11.
I have solved this problem using regex, match, and replace, but how I can do it without applying to those solutions.
I have tried to do this without regex but it did not work because indexOf is only giving me one result:
string = "***6**5****8*9***2";
for (var i = 0; i < string.length; i++) {
let where = (string.indexOf("***"));
let a = parseInt(string.charAt(where - 1));
let b = parseInt(string.charAt(where + 3));
if (a + b == 11){
isTrue = true;
}
}
You could split the string by stars amd keep the starts in the array then check if the value starts with a star, check the length and the left and right element for sum.
var string = "***6**5****8*9***2",
parts = string.split(/(\*+)/),
result = parts.some((s, i, { [i - 1]: l, [i + 1]: r }) =>
s[0] === '*' && s.length >= 3 && +l + +r === 11
);
console.log(result);
console.log(parts);
I tried to create a solution based off of your existing code:
string = "***6**5****8*9***2***4";
let where = 0;
// Skip leading *
while (where < string.length && '*' == string.charAt(where)) {
where += 1;
}
while (true) {
// Find three stars based on previous result
where = string.indexOf("***", where);
// No more triples
if (where == -1) break;
// Convert to digit - will be NaN if not a digit
let a = parseInt(string.charAt(where - 1));
// Find trailing digit
let j = where + 1;
// Skip to next non * char
while (j < string.length && '*' == string.charAt(j)) {
j += 1;
}
// No matches - quit
if (j == string.length) break;
// Parse digit
let b = parseInt(string.charAt(j));
// Do the math
if (!isNaN(a) && !isNaN(b)){
console.log(`${a} + ${b} = ${a+b}`);
}
where = j;
}
I wrote a simple Parser.I hope it can help you
string = "***6**5****8*9***2";
class Parser {
static parse(string) {
var lexer = new Lexer(string);
var token = lexer.getToken();
var prevNumberToken = null ;
while (token.type !== TOKEN_TYPE_END) {
if(token.type === TOKEN_TYPE_NUMBER){
if(prevNumberToken && prevNumberToken.value + token.value === 11 ) {
return true;
}
prevNumberToken = token ;
} else if(token.type !== TOKEN_TYPE_THREESTARS){
prevNumberToken = null ;
}
token = lexer.getToken();
}
return false;
}
}
class Lexer {
constructor(string) {
this._string = string;
this._index = -1;
this._len = string.length;
}
getToken() {
if (this._index < 0) {
this._index = 0;
return new Token(TOKEN_TYPE_START, '', -1);
}
if (this._index >= this._len) {
return new Token(TOKEN_TYPE_END, '', this._len);
}
if (this._string[this._index] === "*") {
return this._getStarToken()
} else {
return this._getNumberToken();
}
}
_getStarToken() {
var stars = "";
var i = this._index;
while (this._index < this._len && this._string[this._index] === "*") {
stars += "*";
this._index++;
}
if (stars.length === 3) {
return new Token(TOKEN_TYPE_THREESTARS, stars, i)
}
return new Token(TOKEN_TYPE_STARS, stars, i)
}
_getNumberToken() {
var numbers = "";
var i = this._index;
while (this._index < this._len && this._string[this._index] !== "*") {
if (this._string[this._index] >= "0" && this._string[this._index] <= "90") {
numbers += this._string[this._index];
this._index++;
} else {
throw new Error("invalid character")
}
}
return new Token(TOKEN_TYPE_NUMBER, parseInt(numbers), i);
}
}
class Token {
constructor(type, value, index) {
this._type = type
this._index = index
this._value = value
}
get type() { return this._type }
get index() { return this._index }
get value() { return this._value }
}
const TOKEN_TYPE_START = 1;
const TOKEN_TYPE_NUMBER = 2;
const TOKEN_TYPE_THREESTARS = 4;
const TOKEN_TYPE_STARS = 8;
const TOKEN_TYPE_END = 16;
console.log(Parser.parse(string));

Javascript anagram algorithm [duplicate]

I'm trying to compare two strings to see if they are anagrams.
My problem is that I'm only comparing the first letter in each string. For example, "Mary" and "Army" will return true but unfortunately so will "Mary" and Arms."
How can I compare each letter of both strings before returning true/false?
Here's a jsbin demo (click the "Console" tab to see the results"):
http://jsbin.com/hasofodi/1/edit
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
for (i=0; i<y.length; i++) {
if(y.length===z.length) {
if (y[i]===z[i]){
console.log(a + " and " + b + " are anagrams!");
break;
}
else {
console.log(a + " and " + b + " are not anagrams.");
break;
}
}
else {
console.log(a + " has a different amount of letters than " + b);
}
break;
}
}
compare("mary", "arms");
Instead of comparing letter by letter, after sorting you can join the arrays to strings again, and let the browser do the comparison:
function compare (a, b) {
var y = a.split("").sort().join(""),
z = b.split("").sort().join("");
console.log(z === y
? a + " and " + b + " are anagrams!"
: a + " and " + b + " are not anagrams."
);
}
If you want to write a function, without using inbuilt one, Check the below solution.
function isAnagram(str1, str2) {
if(str1 === str2) {
return true;
}
let srt1Length = str1.length;
let srt2Length = str2.length;
if(srt1Length !== srt2Length) {
return false;
}
var counts = {};
for(let i = 0; i < srt1Length; i++) {
let index = str1.charCodeAt(i)-97;
counts[index] = (counts[index] || 0) + 1;
}
for(let j = 0; j < srt2Length; j++) {
let index = str2.charCodeAt(j)-97;
if (!counts[index]) {
return false;
}
counts[index]--;
}
return true;
}
This considers case sensitivity and removes white spaces AND ignore all non-alphanumeric characters
function compare(a,b) {
var c = a.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
var d = b.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
return (c ===d) ? "Anagram":"Not anagram";
}
Quick one-liner solution with javascript functions - toLowerCase(), split(), sort() and join():
Convert input string to lowercase
Make array of the string with split()
Sort the array alphabetically
Now join the sorted array into a string using join()
Do the above steps to both strings and if after sorting strings are the same then it will be anargam.
// Return true if two strings are anagram else return false
function Compare(str1, str2){
if (str1.length !== str2.length) {
return false
}
return str1.toLowerCase().split("").sort().join("") === str2.toLowerCase().split("").sort().join("")
}
console.log(Compare("Listen", "Silent")) //true
console.log(Compare("Mary", "arms")) //false
No need for sorting, splitting, or joining. The following two options are efficient ways to go:
//using char array for fast lookups
const Anagrams1 = (str1 = '', str2 = '') => {
if (str1.length !== str2.length) {
return false;
}
if (str1 === str2) {
return true;
}
const charCount = [];
let startIndex = str1.charCodeAt(0);
for (let i = 0; i < str1.length; i++) {
const charInt1 = str1.charCodeAt(i);
const charInt2 = str2.charCodeAt(i);
startIndex = Math.min(charInt1, charInt2);
charCount[charInt1] = (charCount[charInt1] || 0) + 1;
charCount[charInt2] = (charCount[charInt2] || 0) - 1;
}
while (charCount.length >= startIndex) {
if (charCount.pop()) {
return false;
}
}
return true;
}
console.log(Anagrams1('afc','acf'))//true
console.log(Anagrams1('baaa','bbaa'))//false
console.log(Anagrams1('banana','bananas'))//false
console.log(Anagrams1('',' '))//false
console.log(Anagrams1(9,'hey'))//false
//using {} for fast lookups
function Anagrams(str1 = '', str2 = '') {
if (str1.length !== str2.length) {
return false;
}
if (str1 === str2) {
return true;
}
const lookup = {};
for (let i = 0; i < str1.length; i++) {
const char1 = str1[i];
const char2 = str2[i];
const remainingChars = str1.length - (i + 1);
lookup[char1] = (lookup[char1] || 0) + 1;
lookup[char2] = (lookup[char2] || 0) - 1;
if (lookup[char1] > remainingChars || lookup[char2] > remainingChars) {
return false;
}
}
for (let i = 0; i < str1.length; i++) {
if (lookup[str1[i]] !== 0 || lookup[str2[i]] !== 0) {
return false;
}
}
return true;
}
console.log(Anagrams('abc', 'cba'));//true
console.log(Anagrams('abcc', 'cbaa')); //false
console.log(Anagrams('abc', 'cde')); //false
console.log(Anagrams('aaaaaaaabbbbbb','bbbbbbbbbaaaaa'));//false
console.log(Anagrams('banana', 'ananab'));//true
Cleanest and most efficient solution for me
function compare(word1, word2) {
const { length } = word1
if (length !== word2.length) {
return false
}
const charCounts = {}
for (let i = 0; i < length; i++) {
const char1 = word1[i]
const char2 = word2[i]
charCounts[char1] = (charCounts[char1] || 0) + 1
charCounts[char2] = (charCounts[char2] || 0) - 1
}
for (const char in charCounts) {
if (charCounts[char]) {
return false
}
}
return true
}
I modified your function to work.
It will loop through each letter of both words UNTIL a letter doesn't match (then it knows that they AREN'T anagrams).
It will only work for words that have the same number of letters and that are perfect anagrams.
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
areAnagrams = true;
for (i=0; i<y.length && areAnagrams; i++) {
console.log(i);
if(y.length===z.length) {
if (y[i]===z[i]){
// good for now
console.log('up to now it matches');
} else {
// a letter differs
console.log('a letter differs');
areAnagrams = false;
}
}
else {
console.log(a + " has a different amount of letters than " + b);
areAnagrams = false;
}
}
if (areAnagrams) {
console.log('They ARE anagrams');
} else {
console.log('They are NOT anagrams');
}
return areAnagrams;
}
compare("mary", "arms");
A more modern solution without sorting.
function(s, t) {
if(s === t) return true
if(s.length !== t.length) return false
let count = {}
for(let letter of s)
count[letter] = (count[letter] || 0) + 1
for(let letter of t) {
if(!count[letter]) return false
else --count[letter]
}
return true;
}
function validAnagramOrNot(a, b) {
if (a.length !== b.length)
return false;
const lookup = {};
for (let i = 0; i < a.length; i++) {
let character = a[i];
lookup[character] = (lookup[character] || 0) + 1;
}
for (let i = 0; i < b.length; i++) {
let character = b[i];
if (!lookup[character]) {
return false;
} else {
lookup[character]--;
}
}
return true;
}
validAnagramOrNot("a", "b"); // false
validAnagramOrNot("aza", "zaa"); //true
Here's my contribution, I had to do this exercise for a class! I'm finally understanding how JS works, and as I was able to came up with a solution (it's not - by far - the best one, but it's ok!) I'm very happy I can share this one here, too! (although there are plenty solutions here already, but whatever :P )
function isAnagram(string1, string2) {
// first check: if the lenghts are different, not an anagram
if (string1.length != string2.length)
return false
else {
// it doesn't matter if the letters are capitalized,
// so the toLowerCase method ensures that...
string1 = string1.toLowerCase()
string2 = string2.toLowerCase()
// for each letter in the string (I could've used for each :P)
for (let i = 0; i < string1.length; i++) {
// check, for each char in string2, if they are NOT somewhere at string1
if (!string1.includes(string2.charAt(i))) {
return false
}
else {
// if all the chars are covered
// and the condition is the opposite of the previous if
if (i == (string1.length - 1))
return true
}
}
}
}
First of all, you can do the length check before the for loop, no need to do it for each character...
Also, "break" breaks the whole for loop. If you use "continue" instead of "break", it skips the current step.
That is why only the first letters are compared, after the first one it quits the for loop.
I hope this helps you.
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
if(y.length==z.length) {
for (i=0; i<y.length; i++) {
if (y[i]!==z[i]){
console.log(a + " and " + b + " are not anagrams!");
return false;
}
}
return true;
} else { return false;}}
compare("mary", "arms");
Make the function return false if the length between words differ and if it finds a character between the words that doesn't match.
// check if two strings are anagrams
var areAnagrams = function(a, b) {
// if length is not the same the words can't be anagrams
if (a.length != b.length) return false;
// make words comparable
a = a.split("").sort().join("");
b = b.split("").sort().join("");
// check if each character match before proceeding
for (var i = 0; i < a.length; i++) {
if ((a.charAt(i)) != (b.charAt(i))) {
return false;
}
}
// all characters match!
return true;
};
It is specially effective when one is iterating through a big dictionary array, as it compares the first letter of each "normalised" word before proceeding to compare the second letter - and so on. If one letter doesn't match, it jumps to the next word, saving a lot of time.
In a dictionary with 1140 words (not all anagrams), the whole check was done 70% faster than if using the method in the currently accepted answer.
an anagram with modern javascript that can be use in nodejs. This will take into consideration empty strings, whitespace and case-sensitivity. Basically takes an array or a single string as input. It relies on sorting the input string and then looping over the list of words and doing the same and then comparing the strings to each other. It's very efficient. A more efficient solution may be to create a trie data structure and then traversing each string in the list. looping over the two words to compare strings is slower than using the built-in string equality check.
The function does not allow the same word as the input to be considered an anagram, as it is not an anagram. ;) useful edge-case.
const input = 'alerting';
const list1 = 'triangle';
const list2 = ['', ' ', 'alerting', 'buster', 'integral', 'relating', 'no', 'fellas', 'triangle', 'chucking'];
const isAnagram = ((input, list) => {
if (typeof list === 'string') {
list = [list];
}
const anagrams = [];
const sortedInput = sortWord(input).toLowerCase();
const inputLength = sortedInput.length;
list.forEach((element, i) => {
if ( inputLength === element.length && input !== element ) {
const sortedElement = sortWord(element).toLowerCase();
if ( sortedInput === sortedElement) {
anagrams.push(element);
}
}
});
return anagrams;
})
const sortWord = ((word) => {
return word.split('').sort().join('');
});
console.log(`anagrams for ${input} are: ${isAnagram(input, list1)}.`);
console.log(`anagrams for ${input} are: ${isAnagram(input, list2)}.`);
Here is a simple algorithm:
1. Remove all unnecessary characters
2. make objects of each character
3. check to see if object length matches and character count matches - then return true
const stripChar = (str) =>
{
return str.replace(/[\W]/g,'').toLowerCase();
}
const charMap = str => {
let MAP = {};
for (let char of stripChar(str)) {
!MAP[char] ? (MAP[char] = 1) : MAP[char]++;
}
return MAP;
};
const anagram = (str1, str2) => {
if(Object.keys(charMap(str1)).length!==Object.keys(charMap(str2)).length) return false;
for(let char in charMap(str1))
{
if(charMap(str1)[char]!==charMap(str2)[char]) return false;
}
return true;
};
console.log(anagram("rail safety","!f%airy tales"));
I think this is quite easy and simple.
function checkAnagrams(str1, str2){
var newstr1 = str1.toLowerCase().split('').sort().join();
var newstr2 = str2.toLowerCase().split('').sort().join();
if(newstr1 == newstr2){
console.log("String is Anagrams");
}
else{
console.log("String is Not Anagrams");
}
}
checkAnagrams("Hello", "lolHe");
checkAnagrams("Indian", "nIndisn");
//The best code so far that checks, white space, non alphabets
//characters
//without sorting
function anagram(stringOne,stringTwo){
var newStringOne = ""
var newStringTwo = ''
for(var i=0; i<stringTwo.length; i++){
if(stringTwo[i]!= ' ' && isNaN(stringTwo[i]) == true){
newStringTwo = newStringTwo+stringTwo[i]
}
}
for(var i=0; i<stringOne.length; i++){
if(newStringTwo.toLowerCase().includes(stringOne[i].toLowerCase())){
newStringOne=newStringOne+stringOne[i].toLowerCase()
}
}
console.log(newStringOne.length, newStringTwo.length)
if(newStringOne.length==newStringTwo.length){
console.log("Anagram is === to TRUE")
}
else{console.log("Anagram is === to FALSE")}
}
anagram('ddffTTh####$', '#dfT9t#D##H$F')
function anagrams(str1,str2){
//spliting string into array
let arr1 = str1.split("");
let arr2 = str2.split("");
//verifying array lengths
if(arr1.length !== arr2.length){
return false;
}
//creating objects
let frqcounter1={};
let frqcounter2 ={};
// looping through array elements and keeping count
for(let val of arr1){
frqcounter1[val] =(frqcounter1[val] || 0) + 1;
}
for(let val of arr2){
frqcounter2[val] =(frqcounter2[val] || 0) + 1;
}
console.log(frqcounter1);
console.log(frqcounter2);
//loop for every key in first object
for(let key in frqcounter1){
//if second object does not contain same frq count
if(frqcounter2[key] !== frqcounter1[key]){
return false;
}
}
return true;
}
anagrams('anagrams','nagramas');
The fastest Algorithm
const isAnagram = (str1, str2) => {
if (str1.length !== str2.length) {
return false
}
const obj = {}
for (let i = 0; i < str1.length; i++) {
const letter = str1[i]
obj[letter] ? obj[letter] += 1 : obj[letter] = 1
}
for (let i = 0; i < str2.length; i++) {
const letter = str2[i]
if (!obj[letter]) {
return false
}
else {
obj[letter] -= 1
}
}
return true
}
console.log(isAnagram('lalalalalalalalala', 'laalallalalalalala'))
console.time('1')
isAnagram('lalalalalalalalala', 'laalallalalalalala') // about 0.050ms
console.timeEnd('1')
const anagram = (strA, strB) => {
const buildAnagram = (str) => {
const charObj = {};
for(let char of str.replace(/[^\w]/g).toLowerCase()) {
charObj[char] = charObj[char] + 1 || 1;
}
return charObj;
};
const strObjAnagramA = buildAnagram(strA);
const strObjAnagramB = buildAnagram(strB);
if(Object.keys(strObjAnagramA).length !== Object.keys(strObjAnagramB).length) {
console.log(strA + ' and ' + strB + ' is not an anagram');
return false;
}
for(let char in strObjAnagramA) {
if(strObjAnagramA[char] !== strObjAnagramB[char]) {
console.log(strA + ' and ' + strB + ' is not an anagram');
return false;
}
}
return true; } //console.log(anagram('Mary','Arms')); - false
Similar approach with filter function
const str1 = 'triangde'
const str2 = 'integral'
const st1 = str1.split('')
const st2 = str2.split('')
const item = st1.filter((v)=>!st2.includes(v))
const result = item.length === 0 ? 'Anagram' : 'Not anagram' + ' Difference - ' + item;
console.log(result)

"Steps in Primes" of Codewars

I got problems when doing "Steps in Primes" of Codewars.
Make function step(g,m,n) which g=step >= 2 , m=begin number >=2,
n=last number>= n. Step(g,m,n) will return the first match [a,b] which
m < a,b is prime < n and a+g=b.
I did right in basic test cases but when i submit , i got infinity loop somewhere. Can anyone give me suggestion?
function isInt(n) {
if(typeof n==='number' && (n%1)===0) {
return true;
}
else return false;
}
function step(g, m, n) {
if(isInt(g) && isInt(m) && isInt(n) &&g >= 2 && m >= 2 && n>=m) {
var p=[];
var ans=[];
for (var temp=m; temp<=n;temp++)
{
var a=0;
for (var chk=2; chk<temp-1;chk++)
if (temp%chk===0) a++;
if (a===0) p.push(temp);
}
for (var a=0;a<p.length-1;a++)
{
for (var b=a+1;b<p.length;b++)
if (p[b]===(p[a]+g)) return [p[a],p[b]];
}
}
return "nil";
}
this code might help you
function gap(g, m, n) {
var prime-numbers = [];
var final = [];
var prime;
for (var i = m; i <= n; i++) {
prime = true;
for (var j = 2; j < i / 2; j++) {
if (i % j === 0) {
prime = false;
}
}
if (prime) {
prime-numbers.push(i);
}
}
prime-numbers.forEach(function(prime, index) {
if (prime + g === prime-numbers[index + 1]) {
final.push(prime, prime-numbers[index + 1]);
}
});
if (final) return final.slice(0,2);
else return null;
}

for loop number sequence of (1,1,2,2,3,3, etc.)

I looked it up and this pattern is Hofstadter Female sequence. The equations are:
M(n) = n-F(M(n-1))
F(n) = n-M(F(n-1))
but I'm not sure how to put that into code.
So far I have:
while () {
_p++
_r++
if (_p % 2 === 0) {
_r = _p - 1;
}
}
Any help?
Without memoization:
function F(n)
{
return 0 < n ? n - M(F(n-1)) : 1
}
function M(n)
{
return 0 < n ? n - F(M(n-1)) : 0
}
var N = 10;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {
f.push(F(i));
m.push(M(i));
}
console.log('F: ' + f.join(','))
console.log('M: ' + m.join(','))
Output:
F: 1,1,2,2,3,3,4,5,5,6,6
M: 0,0,1,2,2,3,4,4,5,6,6
http://jsfiddle.net/KtGBg/1/
Recursion should be avoided, if possible, so you can cache the already-calculated values for F(n) and M(n) :
var f = new Array();
var m = new Array();
function F(n){
if(f[n] != undefined) {
return f[n];
}
if (n==0) {
value = 1;
} else {
value = n - M(F(n-1));
}
f[n] = value;
return value;
}
function M(n){
if(m[n] != undefined) {
return m[n];
}
if (n==0) {
value = 0;
} else {
value = n - F(M(n-1));
}
m[n] = value;
return value;
}
This yields a much faster result for greater numbers (try it with 10000)
how about:
function F(n){
if (n==0) return 1
else return n - M(F(n-1))
}
function M(n){
if (n==0) return 0
else return n - F(M(n-1))
}
var str = ""
for(var i=0; i<=10; i++) str += F(i) + ", "
console.log(str.substr(0,str.length-2))
Similar to GaborSch's answer, you could use Doug Crockford's memoizer function, which can be found in Chapter 4 of Javascript: The Good Parts. Using memoization took the calculation time for the first 150 terms of the male and female Hofstadter sequences down to 256 ms as compared to almost 8 seconds without memoization.
var memoizer = function (memo, formula) {
var recur = function (n) {
var result = memo[n];
if (typeof result !== 'number') {
result = formula(recur, n);
memo[n] = result;
}
return result;
};
return recur;
};
var maleHofstadter = memoizer([0], function (recur, n) {
return n - femaleHofstadter(recur(n-1));
});
var femaleHofstadter = memoizer([1], function (recur, n) {
return n - maleHofstadter(recur(n-1));
});
var N = 150;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {
f.push(femaleHofstadter(i));
m.push(maleHofstadter(i));
}
console.log('F: ' + f.join(','));
console.log('M: ' + m.join(','));

Categories