首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在n和数组中是否存在X数

在n和数组中是否存在X数
EN

Stack Overflow用户
提问于 2019-05-27 02:41:50
回答 1查看 111关注 0票数 1

我希望在下面的数组中找到x数是否存在。为了在里面找到x数,数组中的任何元素都可以得到给定的x数。这是基于元素的有一个内部数组并检查它是否存在。这不像是升职和合并。

代码语言:javascript
复制
let arrr = [
    4,
    7,
    6,
    2,
    7,
    6
];
  • 示例:如果X=16,那么结果应该是4,6,6 = 16 (真)
  • 示例:如果X=11,那么结果应该是4,7 = 11 (真)
  • 示例:如果X=18的结果应该是4,6,6,2 = 18 (true)
EN

回答 1

Stack Overflow用户

发布于 2019-05-27 05:23:01

它没有被优化,但它有效:

代码语言:javascript
复制
    function Contains(array, value) {
        const str = array.reduce((p, c) => p + c.toString(), "");
        const fn = function (active, rest, a) {
            const sum = rest.split("").reduce((p, c) => p + Number(c), 0);
            if (sum === value) return true;
            if (!active && !rest) return;
            if (!rest) {
                a.push(active);
            } else {
                if (fn(active + rest[0], rest.slice(1), a) === true) return true;
                if (fn(active, rest.slice(1), a) === true) return true;
            }
            return a;
        }
        const result = fn("", str, []) === true;
        return result === true;
    }
    Contains(array, value)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56319055

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档