确定数组是算术还是几何级数(来自Coderbyte) [英] determine if array is arithmetic or geometric progression (from Coderbyte)

查看:69
本文介绍了确定数组是算术还是几何级数(来自Coderbyte)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就coderbyte而言,这是我的功能代码。
但我觉得不应该这么复杂。
我错过了一个简单的伎俩吗?

Here is my functional code, as far as coderbyte is concerned. But I have a feeling it shouldn't be this complicated. Am I missing a simple trick?

function ArithGeo(arr)
{
    var array_type = -1;
    if (arr.length <= 2) return true;

    var a = arr[1], r = a/arr[0], i;
    for (i = 2; i < arr.length; ++i) {
        if ((a *= r) == arr[i]){
            array_type = "Geometric";
        }
        else{
            array_type = -1;
            break;
        }
    }

    if (array_type == "Geometric")
        return array_type;


    a = arr[1], d = a - arr[0], i;
    for (i = 2; i < arr.length; ++i) {
        if ((a += d) == arr[i]){
            array_type = "Arithmetic";
        }
        else {
            array_type = -1;
            break;
        }
    }
    return array_type;
}

ArithGeo([3,9,15,21,27, 28]);


推荐答案

对于算术级数,从前一个元素中减去每个元素;他们的差别应该是平等的;对于几何,将每个元素除以前一个元素,该比例应保持不变。当你遇到0时除以零,javascript给你Inf(它肯定不是几何级数)。因为浮点数不准确,您可能希望存储这些值的最小值和最大值,然后查看它们是否彼此足够接近。

For arithmetic progression, subtract each element from previous element; their difference should be equal; for geometric, divide each element by the previous element, the ratio should stay the same. As for divide by zero when you meet 0, javascript gives you Inf (and it certainly is not a geometric progression). Because floats are inaccurate, maybe you'd want to store the min and max of these values and then see if they are close enough to each other.

function arithGeo(arr) {
    var minRatio = 1/0,
        maxRatio = -1/0,
        minDiff  = 1/0,
        maxDiff  = -1/0,
        epsilon  = 0.000001,
        i,
        ratio,
        diff;

    if (arr.length <= 2) {
        return;
    }

    for (i = 1; i < arr.length; ++i) {
        diff  = arr[i] - arr[i - 1];
        ratio = arr[i] / arr[i - 1];
        minDiff  = Math.min(diff, minDiff);
        maxDiff  = Math.max(diff, maxDiff);
        minRatio = Math.min(ratio, minRatio);
        maxRatio = Math.max(ratio, maxRatio);
    }

    if (Math.abs(minDiff - maxDiff) < epsilon) {
        return "Arithmetic";
    }

    if (Math.abs(minRatio - maxRatio) < epsilon) {
        return "Geometric";
    }

    return;
}

alert(arithGeo([3,9,15,21,27,28]));
alert(arithGeo([3,9,15,21,27]));
alert(arithGeo([4,2,1,0.5]));

这篇关于确定数组是算术还是几何级数(来自Coderbyte)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆