Javascript检查数组中的项是否连续

时间:2015-12-13 22:28:38

标签: javascript jquery arrays

假设我有一个包含值[1,2,3,6,7]的数组。

如何检查数组以查看它是否包含3个连续数字。例如,上面的数组保持[1,2,3],所以这将在我的函数中返回false。

        var currentElement = null;
        var counter = 0;

        //check if the array contains 3 or more consecutive numbers:
        for (var i = 0; i < bookedAppArray.length; i++) {
            if ((bookedAppArray[i] != currentElement) && (bookedAppArray[i] === bookedAppArray[i - 1] + 1)) {

                if (counter > 2) {
                    return true;
                }

                currentElement = bookedAppArray[i];
                counter++;
            } else {
                counter = 1;
            }
        }

        if(counter > 2){
            return true;
        } else{
            return false;
        }

5 个答案:

答案 0 :(得分:1)

此解决方案

  • 检查数组的长度是否大于2
  • 从位置2迭代数组
  • 获取索引之前位置2和1之间的差异
  • 检查绝对差异是否为1
  • 检查位置1之前和指数之间的差异是否等于差异
  • 如果是,则返回false,因为找到了连续的元素。
  • 如果没有,请按1
  • 增加索引

&#13;
&#13;
function consecutive(array) {
    var i = 2, d;
    while (i < array.length) {
        d = array[i - 1] - array[i - 2];
        if (Math.abs(d) === 1 && d === array[i] - array[i - 1]) {
            return false;
        }
        i++;
    }
    return true;
}

document.write(consecutive([1]) + '<br>');             // true
document.write(consecutive([2, 4, 6]) + '<br>');       // true
document.write(consecutive([9, 8, 7]) + '<br>');       // false
document.write(consecutive([1, 2, 3, 6, 7]) + '<br>'); // false
document.write(consecutive([1, 2, 3, 4, 5]) + '<br>'); // false
&#13;
&#13;
&#13;

答案 1 :(得分:0)

从逻辑上思考,这应该像迭代数组一样简单,只需检查当前数据之前的两个索引。

只需将1添加到上一个索引,将2添加到该索引之前的那个,它们应该都是相同的,就像这样

function hasThree(arr) {
    var res = false;

    arr.forEach(function(item, index) {
        var l1 = arr[index - 1], // get previous
            l2 = arr[index - 2]; // get the one before the previous

        if ( l1 && l2 ) { // if two previous exist

            // add 1, and then 2, and see if all are equal

            if ( item === l1 + 1 && item === l2 + 2 ) res = true;
        }
    });

    return res;
}

FIDDLE

答案 2 :(得分:0)

有趣的问题。这是我的尝试。

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <tiff.h>
#include <tiffio.h>

#include <stdint.h>
#include <string>
#include <vector>
#include <stdexcept>
#include <cstdio>
#include <cassert>

// just tiny exception generator
void except(bool condition, const std::string &message = "")
{
    if (!condition)
        throw std::runtime_error("Error: " + message);
}

bool write_fax(
    const std::string &name, const cv::Mat &src, uint8_t threshold = 150)
{
    cv::Mat image;
    if (src.channels() == 3)
        cv::cvtColor(src, image, CV_BGR2GRAY);
    else if (src.channels() == 4)
        cv::cvtColor(src, image, CV_BGRA2GRAY);
    else
        src.copyTo(image);

    if (image.depth() != CV_8U)
    {
        cv::Mat tmp;
        image.convertTo(tmp, CV_8U);
        std::swap(image, tmp);
    }

    int width = image.cols;
    int height = image.rows;

    // do NOT put "wb" as the mode, because the b means "big endian" mode, not "binary" mode.
    // http://www.remotesensing.org/libtiff/man/TIFFOpen.3tiff.html
    TIFF* pTiffHandle = TIFFOpen(name.c_str(), "w");
    if (!pTiffHandle)
    {
        printf("can't open TIFF descriptor\n");
        return false;
    }

    try
    {
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGEWIDTH, width), "width");
    except(TIFFSetField(pTiffHandle, TIFFTAG_IMAGELENGTH, height), "length");
    except(TIFFSetField(pTiffHandle, TIFFTAG_BITSPERSAMPLE, 1), "bits per sample");
    except(TIFFSetField(pTiffHandle, TIFFTAG_SAMPLESPERPIXEL, 1), "samples per pixel");
    except(TIFFSetField(pTiffHandle, TIFFTAG_ROWSPERSTRIP, 1), "rows per strip");

    except(TIFFSetField(pTiffHandle, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4), "compression");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_FILLORDER, FILLORDER_MSB2LSB), "photometric");
    except(TIFFSetField(pTiffHandle, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG), "planar config");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_PREDICTOR, predictor), "predictor");
    //except(TIFFSetField(pTiffHandle, TIFFTAG_STRIPOFFSETS, strip_offsets), "strip offsets");

    // not necessary
    except(TIFFSetField(pTiffHandle, TIFFTAG_XRESOLUTION, 200.0), "res x");
    except(TIFFSetField(pTiffHandle, TIFFTAG_YRESOLUTION, 200.0), "res y");
    except(TIFFSetField(pTiffHandle, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH), "res unit");

    std::vector<uchar> _buffer(width / 8 + 8, 0);
    uchar* buffer = &_buffer[0];
    int bytes = int(width / 8.0 + 0.5);
    for (int y = 0; y < height; ++y)
    {
        uint8_t *src_row = image.ptr(y);
        for (int x = 0; x < width; ++x, ++src_row)
        {
            uint8_t eight_pixels = buffer[x / 8];
            eight_pixels = eight_pixels << 1;
            if (*src_row < threshold)
                eight_pixels = eight_pixels | 1;  //
            buffer[x / 8] = eight_pixels;
        }

        // for the some reason writeEncodedStrip doesn't work
//      except(TIFFWriteEncodedStrip(pTiffHandle, y, buffer, bytes) != -1, "write scanline");
        except(TIFFWriteScanline(pTiffHandle, buffer, y,  bytes) != -1, "write scanline");
    }

    }
    catch (const std::runtime_error &e)
    {
        printf("TIFF writing: %s\n", e.what());
        TIFFClose(pTiffHandle);
        return false;
    }

    TIFFClose(pTiffHandle);
    return true;
}

答案 3 :(得分:0)

这里是一个。只需确保对数组进行排序

function checkIfConsecutive(Arr) {
          let isCnsc = true;
          for (st in Arr ) {
               if ( Arr[parseInt(st)+1]-Arr[parseInt(st)] > 1 && !isNaN(Arr[parseInt(st)+1]-Arr[parseInt(st)] )) {
                    isCnsc = false;
               }
          }
           return isCnsc;
     }

答案 4 :(得分:-1)

尝试使用Array.prototype.some()Array.prototype.filter()

&#13;
&#13;
var arr1 = [1, 2, 3, 9, 8, 7];
var arr2 = [1, 2, "a", 3];
var check = function(a) {
  // for each element in array `a` 
  return !a.some(function(item, index) { 
    // slice next three elements, including current element `item` from `a` array
    var next = a.slice(index, 3);
    console.log(next);
    // if next three items in array `a` are type `Number`
    // return `false`, else return `true`
    return next.filter(Number).length === 3 ? true : false
  })
};
// each item in `arr1` returns `false` , where item is followed
// by two numbers
// `arr2` returns `true` , where item is not followed by two numbers
console.log(check([1,2,3]), check(arr1), check(arr2)) // `false`, `false`, `true`
&#13;
&#13;
&#13;

或者,使用for循环,Array.prototype.every()

&#13;
&#13;
var arr1 = [1, 2, 3, 9, 8, 7];
var arr2 = [1, 2, "a", 3];
var check = function(a) {
  var res;
  for (var i = 0; i < a.length; i++) {
    // if `a[i]` is followed by two numbers, return `false`
    if (a.slice(i, 3).every(function(n) {
      return typeof n === "number"
    })) {
      res = false;
      break;
    } 
    // if `a[i]` is not followed by two numbers, return `true`
    else {
      res = true;
      break;
    }
  }
  return res
}
console.log(check([1,2,3]), check(arr1), check(arr2)) // `false`, `false` , `true`
&#13;
&#13;
&#13;