如何计算符合“if”条件的元素数量?

7
private static int chain(int n){
        int count = 0;
        while(n > 1){
            if(n % 2 == 0){
                count++; //the value is not stored
                return chain(n/2);
            }
            count++; //same thing
            return chain(3*n+1);
        }
        return count; //prints the initial value (0)
    }
}

我需要打印出链式方法重复出现的次数。
4个回答

10

这样怎么样:

public static int chain(int n) {
    return chain(n, 0);
}

private static int chain(int n, int count) {
    if (n > 1) {  // no need for a while-loop, it will never get past 1 iteration
        if (n % 2 == 0) {
            return chain(n / 2, count + 1);
        }
        return chain(3 * n + 1, count + 1);
    }
    return count;
}

对我来说,这种方法比在方法外部声明静态字段更加清晰,主要是因为我不想担心每次调用chain时都需要将静态字段重置为0。


1
这一切都是为了避免静态,天啊 =),不过回答很好。 - dardo
1
好的,这是大师级的方法。我需要的是更简单的东西,让我的思维能够轻松掌握,没有任何问题。无论如何,你有我的支持。 - Deneb A.

5

我不太明白你在问什么。但是如果你想让计数器在方法外生存,而不是每次调用方法时创建一个局部副本,你可以将其设置为静态。

static int count=0;

另一个选项是为此方法创建一个返回对象,其中包含n和count。 - Jesan Fafon

4

将方法中的count变量移除,并将其作为类的静态成员。为了遵循DRY原则,应在方法顶部递增count变量,以防止重复。

private static int count = 0;

private static int chain(int n) {
    count++;

    while(n > 1) {
        if(n % 2 == 0) {
            return chain(n/2);
        }

        return chain(3*n+1);
    }

return count;
}

2
这个方法可以运行,但是我认为在编写递归方法时,正确的做法是传入一个计数变量。这样可以将方法的状态保留在调用栈中,而不是在类变量中。正如其他人提到的,这个版本不是线程安全的。 - aglassman
虽然在你提出问题的情境下,这是完全可以接受的。 - aglassman
@aglassman 我同意。A.R.S.的回答非常清楚地描述了如何做到这一点;) - Laf

1
这个方法似乎也有效,而且不使用那个丑陋的额外参数。
我稍微调整了算法(将chain(3 * n + 1)放在一个else部分),假设这实际上是对Collatz猜想的Hailstone序列长度进行测量的尝试。最初的声明只会导致堆栈溢出。
当传入27时,此代码确实产生111
private static int recursiveChain(int n) {
  if (n > 1) {
    if (n % 2 == 0) {
      return 1 + recursiveChain(n / 2);
    } else {
      return 1 + recursiveChain(3 * n + 1);
    }
  } else {
    return 0;
  }
}

迭代版本看起来与原始问题惊人地相似:

private static int iterativeChain(int n) {
  int count = 0;
  while (n > 1) {
    count += 1;
    if (n % 2 == 0) {
      n = n / 2;
    } else {
      n = 3 * n + 1;
    }
  }
  return count;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接