Growing delays per account

After a few wrong passwords in a row, each new failure should wait longer, doubling each time, so guessing becomes hopeless while honest typos cost nothing.

What to build

Track failures per account and print the wait after each attempt.

Requirements

  • Each line is user ok or user fail. Counts are kept separately for each user.
  • A success resets that user's count to 0 and prints USER: logged in.
  • A failure adds 1 to the count. If the count is 3 or less print USER: failure N; otherwise print USER: failure N, wait W s, with W = 2^(N − 3).
  • At the end print total wait: T s, the sum of every wait printed.

Input

One attempt per line.

Output

One line per attempt, then the total.

Constraints

Up to 100 attempts. Waits fit in a JavaScript number.

Example

Input:

rahim fail
rahim fail
rahim fail
rahim fail
rahim fail
rahim ok

Output:

rahim: failure 1
rahim: failure 2
rahim: failure 3
rahim: failure 4, wait 2 s
rahim: failure 5, wait 4 s
rahim: logged in
total wait: 6 s

Why it works

Doubling waits grow so fast that a guessing script soon waits days, while a person who mistypes once or twice never waits at all; separate counts mean one user's mistakes never slow another.

Examples

Example 1 · Input
rahim fail
rahim fail
rahim fail
rahim fail
rahim fail
rahim ok
Expected output
rahim: failure 1
rahim: failure 2
rahim: failure 3
rahim: failure 4, wait 2 s
rahim: failure 5, wait 4 s
rahim: logged in
total wait: 6 s
Example 2 · Input
a fail
b fail
a ok
b fail
Expected output
a: failure 1
b: failure 1
a: logged in
b: failure 2
total wait: 0 s

Hints

Hint 1

Keep a Map from user to their current run of failures.

Solution

Show one correct solution (try it yourself first)
const failures = new Map();
let total = 0;
let line = prompt();
while (line !== null) {
  if (line.trim()) {
    const [user, result] = line.trim().split(/\s+/);
    if (result === "ok") {
      failures.set(user, 0);
      console.log(`${user}: logged in`);
    } else {
      const n = (failures.get(user) ?? 0) + 1;
      failures.set(user, n);
      if (n <= 3) console.log(`${user}: failure ${n}`);
      else {
        const wait = 2 ** (n - 3);
        total += wait;
        console.log(`${user}: failure ${n}, wait ${wait} s`);
      }
    }
  }
  line = prompt();
}
console.log(`total wait: ${total} s`);

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Broken authentication and sessions →