Блог пользователя ChallaAjay

Автор ChallaAjay, история, 2 часа назад, По-английски

Okay, here's a challenge.

The code below is supposed to find the maximum element in a non-empty array. It compiles, and it looks pretty normal.

int ans = 0;

for (int i = 0; i < n; i++) {
    if (a[i] > ans) {
        ans = a[i];
    }
}

cout << ans << '\n';

Find a valid input for which this code fails.

Rules: - Give the smallest counterexample you can find. - Explain why the output is wrong. - Bonus: fix it without changing the overall approach.

Try to find the bug before opening the comments.

Let's see who catches it first

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

»
2 часа назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

its when the array contains negatives... like if the array a is [-1,-2]. your code outputs 0. which is wrong. cause the answer is -1. initialize the answer to a[0].

  • »
    »
    11 минут назад, скрыть # ^ |
    ← Rev. 2  
    Проголосовать: нравится 0 Проголосовать: не нравится

    bro the answer is -2 T_T. Edit: I'm so dumb it is maximum

    • »
      »
      »
      6 минут назад, скрыть # ^ |
       
      Проголосовать: нравится 0 Проголосовать: не нравится

      we are not talking about the minimum bro. its max we are talking about.

»
108 минут назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

its obvious due to ans = 0; on the case [-1] for example, set ans to INT_MIN

Funny bonus
»
67 минут назад, скрыть # |
← Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

Technically by default if the array contains long longs over the integer limit, the compiler won't tell u and make ans overflow and weird