Files
freecodecamp--freecodecamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/6a22d77ddf034bc4e35b1d54.md
T
wehub-resource-sync dde272c4b8
i18n - Build Validation / Validate i18n Builds (24) (push) Has been cancelled
CI - Node.js / Lint (24) (push) Has been cancelled
CI - Node.js / Build (24) (push) Has been cancelled
CI - Node.js / Test (24) (push) Has been cancelled
CI - Node.js / Test - Upcoming Changes (24) (push) Has been cancelled
CI - Node.js / Test - i18n (italian, 24) (push) Has been cancelled
CI - Node.js / Test - i18n (portuguese, 24) (push) Has been cancelled
CD - Docker - GHCR Images / Build and Push Images (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 11:55:53 +08:00

1.8 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
6a22d77ddf034bc4e35b1d54 Challenge 347: Game Theory 28 challenge-347

--description--

Given two equal length strings representing two players' strategies for a game, return the scores as an array [player1, player2].

  • The given strings will only contain one of two letters: "C" (cooperate) or "D" (defect).
  • Each character represents one round, scored as follows:
    • If both players cooperate, each scores 3.
    • If both players defect, each scores 1.
    • If one player defects and the other cooperates, the defector scores 5 and the cooperator scores 0.

--hints--

playGame("CCCC", "CCCC") should return [12, 12].

assert.deepEqual(playGame("CCCC", "CCCC"), [12, 12]);

playGame("DDDD", "DDDD") should return [4, 4].

assert.deepEqual(playGame("DDDD", "DDDD"), [4, 4]);

playGame("CCDD", "CDDD") should return [5, 10].

assert.deepEqual(playGame("CCDD", "CDDD"), [5, 10]);

playGame("CCCDCDCCCDDC", "CCDDCDCDDCCD") should return [24, 34].

assert.deepEqual(playGame("CCCDCDCCCDDC", "CCDDCDCDDCCD"), [24, 34]);

playGame("DDCCDDDDCDDCDDDCDD", "CCDCCCDCCCDCCCCDCC") should return [66, 21].

assert.deepEqual(playGame("DDCCDDDDCDDCDDDCDD", "CCDCCCDCCCDCCCCDCC"), [66, 21]);

--seed--

--seed-contents--

function playGame(p1, p2) {

  return p1;
}

--solutions--

function playGame(p1, p2) {
  let scores = [0, 0];

  for (let i = 0; i < p1.length; i++) {
    if (p1[i] === 'C' && p2[i] === 'C') {
      scores[0] += 3; scores[1] += 3;
    } else if (p1[i] === 'D' && p2[i] === 'D') {
      scores[0] += 1; scores[1] += 1;
    } else if (p1[i] === 'D' && p2[i] === 'C') {
      scores[0] += 5; scores[1] += 0;
    } else {
      scores[0] += 0; scores[1] += 5;
    }
  }

  return scores;
}