проверить, что слово является изограммой с чистым JavaScript - PullRequest
0 голосов
/ 02 мая 2018

Как проверить, является ли данное слово изограммой с чистым javascript, используя функцию. функция должна возвращать true или false.

Изограмма - это слово с повторяющимся символом.

Я знаю, что этот код работает, но мне нужно лучшее решение.

function isIsogram(word){
    x = false; y = false;
    for(i = 0; i < word.length; i++){
        wordl = word.substring(0,i)
        wordr = word.substring(i)
        x = wordl.includes(word.charAt(i))
        y = wordr.includes(word.charAt(i))
        //console.log(x,wordl,wordr)
    }
    return x&&y
}
isIsogram("thomas");//False
isIsogram("moses"); //True

Ответы [ 5 ]

0 голосов
/ 02 мая 2018

А как же:

> function isIsogram(word) {
... var a = word.split('')
... var b = Array.from(new Set(a))
... return a.length === b.length;
... }
undefined
> isIsogram("mesos")
false
> isIsogram("thomas")
true

Или лучше (проверка каждого символа только один раз):

> function isIsogram2(word) {
... for(var i=0,len=word.length-1;i<len;++i) {
..... var c = word[i]
..... if(word.indexOf(c,i+1) !== -1) return false;
..... }
... return true;
... }
undefined
> isIsogram2("mesos")
false
> isIsogram2("thomas")
true
0 голосов
/ 02 мая 2018

Вот простой подход с использованием .split() и .every():

let isIsogram = (str) => str.split("").every((c, i) => str.indexOf(c) == i);
                            
console.log(isIsogram("thomas"));   /* no repeating letter */
console.log(isIsogram("moses"));    /* s repeat 2 times */
console.log(isIsogram("hello"));    /* l repeat 2 times */
console.log(isIsogram("world"));    /* no repeating letter */
console.log(isIsogram("a b c"));    /* space character repeat 2 times */

Docs:

0 голосов
/ 02 мая 2018

Опираясь на ответ Киши:

function isIsogram(sWord)
 {
  for (iCharIndex = 0; iCharIndex < sWord.length; iCharIndex++)
    if (sWord.substring(iCharIndex + 1).includes(sWord.charAt(iCharIndex)))
      return false;
  return true;
 }

Если символ в текущей позиции (charAt) найден (includes) справа от текущей позиции (substring), возвращается false. В противном случае цикл продолжается до конца и возвращается true.

0 голосов
/ 02 мая 2018

Удалите повторяющиеся буквы из строки, затем проверьте обе длины. если это же изограмма.

function isIsogram(str){
 return str.split('').filter((item, pos, arr)=> arr.indexOf(item) == pos).length == str.length;
}
console.log(isIsogram('thomas'));
console.log(isIsogram('moses'));
0 голосов
/ 02 мая 2018
function isIsogram(word){
    x = false; y = false;
    for(i = 0; i < word.length; i++){
        wordl = word.substring(0,i)
        wordr = word.substring(i)
        x = wordl.includes(word.charAt(i))
        y = wordr.includes(word.charAt(i))
        //console.log(x,wordl,wordr)
    }
    return x&&y
}
isIsogram("thomas");//False
isIsogram("moses"); //True
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...