Reputation: 23
Write a function offOne(word, book)
which takes
a string called word
and an array of strings called book
.
It returns an array of all the word
s in book
of the same
length that are one letter different.
Examples:
offOne("cat", ["cat", "fat", "flat", "tar"]) => ["fat", "tar"]
offOne("will", ["wilt", "willow", "wail"]) => ["wilt", "wail"]
My function is currently:
function offOne(word, book) {
var array = [];
var count = 0;
for (var i = 0; i < book.length; i++) {
if (book.length === word.length) {
if (word.indexOf(book[i]) !== -1) {
count += 1;
if (count === (book[i].length - 1)) {
array.push(book[i]);
}
}
}
}
return array;
}
Does anyone know how to solve this? I got stuck for a while here.
Upvotes: 0
Views: 2629
Reputation: 19113
The snippets are well addressed with comments. It should help you. Do Check it!
Points to remember for your prep:
filter
instead of foreach
. These will reduce your work.Logical operators
.Best of luck for your course!
My way of doing it
var word = "cat";
var book = ["car", "far", "mars", "call", "bat"]
function compare(elm, word) {
var i = 0
elm.split('').forEach(c => { //tokenize elm of book into array
if (word.indexOf(c) > -1) //check if charecter in present in the word
i += 1 //if yes, increment
})
return i === word.length - 1 ? true : false //return true if length of i is (length of word - 1),
}
function offOne(word, book) {
return book.filter(elm =>
// check, if the length of both strings are not same and
// both strings are not same and
// compare strings, true will be returned if the condition is satisfied in compare()
elm.length === word.length && elm !== word && compare(elm, word)
)
}
console.log(offOne(word, book))
My advanced way of doing it
If you see, this one doesn't have any variables declared inside the functions.
var word = "cat";
var book = ["car", "far", "mars", "call", "bat"]
function compare(elm, word) {
return elm.split('').filter(c => //tokenize elm of book into array
word.indexOf(c) > -1 //check if charecter in present in the word, if yes, return true
).join('').length === word.length - 1 ? true : false //join and check the length of the array is one less than length of the word, if yes, return true
}
function offOne(word, book) {
return book.filter(elm =>
// check, if the length of both strings are not same and
// both strings are not same and
// compare strings, true will be returned if the condition is satisfied in compare()
elm.length === word.length && elm !== word && compare(elm, word)
)
}
console.log(offOne(word, book))
Upvotes: 1
Reputation: 17566
Convert word to array of letters, make this array unique. For each book array item do the same and calculate the number of different characters between them. If only one difference is found, return the item, repeat for each.
Upvotes: 0