Connection

[!success]

  • [[Loops in Go]]

Textio has group chats that make communicating with multiple people much more efficient--if the chat doesn't descend into chaos. Instead of sending the message multiple times to individual people, you send one message to all of them at once.

Assignment

Complete the countConnections function that takes an integer groupSize representing the number of people in the group chat and returns an integer representing the number of connections between them. For each additional person in the group, the number of new connections continues to grow. Use a for loop to accumulate the number of connections instead of directly using a mathematical formula.

To make sure you’re picturing it right:

  • If there are two people, how many possible connections exist between them?

  • If you add a third person, how many new connections are created with the rest?

πŸ”— Counting Connections in a Group β€” Go

Problem

Given a group of groupSize people, calculate how many unique 1:1 connections exist.

  • A connection is a pair of people

  • (A, B) is the same as (B, A)

  • People cannot connect to themselves


Key Insight

When people join a group one at a time:

  • Person #1 adds 0 connections

  • Person #2 connects to 1 existing person β†’ +1

  • Person #3 connects to 2 existing people β†’ +2

  • Person #n connects to n βˆ’ 1 existing people

Total connections = 1 + 2 + 3 + ... + (groupSize βˆ’ 1)


Approach

1

Handle edge cases

If groupSize <= 1, there are no connections.

2

Track total connections

Use an accumulator variable to hold the total number of connections.

3

Use a loop to simulate adding each person

Iterate from the second person up to groupSize.

4

Add connections per new person

Each new person adds person - 1 connections to the accumulator.

5

Return the total

After the loop, return the accumulated total.


Go Implementation