当单词乱序时,如何使控制台打印 false? Node.js

How do you make the console print false when the words are out of order? Node.js

当前代码在 message == 'john hi' 时使控制台打印为 true,但我需要它在单词乱序时打印 false。

array1 中的元素应该放在第一位,array2 中的元素应该放在第二位,如果我愿意,我应该可以在 array2 之后添加更多数组。

我需要代码执行的操作示例:

message == 'hi john' //打印真

message == 'and hey evan' //打印真

message == 'john hi' //打印false因为array2排在第一位

var array1 = ['hi', 'hello', 'hey']
var array2 = ['john', 'evan', 'matthew']
var message = ''

if (array1.some(element => message.includes(element)) && array2.some(element => message.includes(element))) {
  console.log(true);
}

这个方法怎么样,我们从每个数组中寻找最后一次出现的单词。所以这可能是 [5,0]。这些应该是有序的,如果不符合我们拒绝。

var array1 = ['hi', 'hello', 'hey'];
var array2 = ['john', 'evan', 'matthew'];
var arrayOfArrays = [array1, array2];

function isInOrder(arr)
{  
    for (var i = 0; i < arr.length - 1; i++ ) {
        if (arr[i] > arr[i+1])  return false;
    }
    return true;
}

function wordsAreInOrder(message) {
    var maxIndexes = arrayOfArrays.map((a) => {
          return Math.max.apply(null, a.map((value) => { return message.indexOf(value) }));
    });

    console.log('The latest occurrence of words from each array: ', maxIndexes);

    return isInOrder(maxIndexes);
}

console.log('Is in order: ' + wordsAreInOrder('hi john'));
console.log('Is in order: ' + wordsAreInOrder('and hey evan'));
console.log('Is in order: ' + wordsAreInOrder('john hi'));

这是一种线性算法,可确保:

  1. 数组 1 中的单词永远不会落后于数组 2 中的单词
  2. 数组 2 中的单词永远不会 'hit' 在数组 1 单词
  3. 之前
function checkWordOrder(array1, array2, str) {
    const words = str.split(' ');
    const wordsLength = words.length;
    const array1Length = array1.length;
    const arrayConcat = array1.concat(array2);
    let hitArray1 = false;
    let hitArray2 = false;

    for (let i = 0; i < wordsLength; ++i) {
        const index = arrayConcat.indexOf(words[i]);

        if (index != -1) { // Word is found in either array
            if (index < array1Length) {
                if (hitArray2) return false;
                hitArray1 = true;
            } else if (index >= array1Length) {
                if (!hitArray1) return false;
                hitArray2 = true;
            }
        }
    }

    return true;
}

let array1 = ['hi', 'hello', 'hey'];
let array2 = ['john', 'evan', 'matthew'];

console.log(checkWordOrder(array1, array2, 'hi john'));         // true
console.log(checkWordOrder(array1, array2, 'and hey evan'));    // true
console.log(checkWordOrder(array1, array2, 'john hi'));         // false
console.log(checkWordOrder(array1, array2, 'hi john john hi')); // false
console.log(checkWordOrder(array1, array2, 'random'));          // true