首页 > 解决方案 > 为没有参数的乘法创建递归算法

问题描述

在计算排名时,相同类型的连续Trails的数量会越来越高。例如,“冰”类型的一条路径的排名为 4。如果紧随其后有另一条冰路径,则第二条路径的排名为 8 (2 *4)。如果该序列中有第三条冰迹,它将具有 12 (3 * 4) 的排名。斜坡的整体排名是其所有路径排名的总和,该值必须分配给名为的实例变量排行。

Trail 是一个数组类型。所以,一个例子是 [3, 3, 3, 3] 所以总排名应该是 30。我正在尝试创建一个递归算法。

    public int calculateRank () {
        for (int i = 0; i < count; i++) {
            if (trail[i].equals(0)) {
                ranking = 0;
            } else if (trail[i + 1] == trail[i]) {
                ranking = calculateRank() * trail[i];
            }
        ranking += ranking;
        }
        return ranking;
    
    }

步道班


public class Trail {
    
    private String ID;
    private String type;
    private int rank;
    
    public Trail (String ID, String type) {
        this.ID = ID;
        this.type = type;
        
        if (type == "ice") {
            rank = 4;
        } else if (type == "trees") {
            rank = 3;
        } else if (type == "rocks") {
            rank = 2;
        } else if (type == "slalom") {
            rank = 1;
        } else {
            rank = 0;
        }
    }
    
    public int getRank () {
        return rank;
    }
    
    public void setRank (int newRank)  {
        this.rank = newRank;
    }
    
    public String getType () {
        return type;
    }
    
    public void setType (String newType)  {
        this.type = newType;
    }
    
    public String getID () {
        return ID;
    }
    
    public void setID (String newID)  {
        this.ID = newID;
    }
    
    public String toString () {
        String s = "";
        s += this.rank;
        return s;
    }

}

然而这是我写的。我不完全理解我写的代码和 b. 它会导致编译错误。

标签: java

解决方案


推荐阅读