2016-10-23 57 views
0

編寫一個函數offOne(word, book)這需要一個名爲word的字符串和一個名爲book的字符串數組。 它返回一個字母不同的長度相同的 的book中的所有word s的數組。將一個單詞與一個數組中的單詞進行比較

例子:

offOne("cat", ["cat", "fat", "flat", "tar"]) => ["fat", "tar"] 
offOne("will", ["wilt", "willow", "wail"]) => ["wilt", "wail"] 

我的功能目前:

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; 
} 

有誰知道如何解決這個問題?我在這裏呆了一段時間。

+1

或者可能是面試前的篩選問題? –

+0

從我的觀點來看,這個問題並不完全符合這個意義。你的問題到底是什麼?我懷疑你會得到一個答案,提供算法來解決你的任務。函數定義對我來說沒有多大意義,我有這樣的感覺,那就是你不瞭解JavaScript;嘗試從那裏開始:書的長度和單詞的長度 - 爲什麼要比較一個字符串的長度和數組的長度? – Elyasin

+0

這是我準備課程的50道準備題之一。 – DoeDoeDoe

回答

1

該片段已經很好的解決了評論。它應該幫助你。請檢查它!

要記住的要點爲您準備:

  1. 不要聲明不必要的變數。它消耗內存,這是不好的。
  2. 請勿使用不必要的循環。在使用循環之前檢查可用的語言API。像,我用filter而不是foreach。這些會減少你的工作。
  3. 始終考慮Logical operators
  4. 使代碼變得簡單。

爲您的課程祝您好運!

我做的方式,

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))

我做的先進方式,

如果你看到,這一個不具有內聲明的變量功能。

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))

0

將字轉換爲字母數組,使此數組唯一。對於每個書籍數組項目執行相同的操作並計算它們之間不同字符的數量。如果只發現一個差異,則返回該項目,重複每個項目。

+0

所以我不得不拆分這個詞,迭代它們,檢查indexOf書,但我如何檢查是否只有一個區別被發現? – DoeDoeDoe

+0

您可以迭代一個數組的元素,併爲每個不包含在第二個數組中的項目增加計數器。這些是編程的基礎。 –

相關問題