Introduction

Welcome! Are you ready to dive into the world of array manipulations? Today, we’ll explore an engaging problem that combines logic, simulation, and programming skills. Imagine a small town with houses, balloons, and a unique sharing game.

Let’s uncover the solution step by step!

Task Statement

In a small town, houses are numbered sequentially from 1 to n, each initially holding a specific number of balloons. During a town festival, the houses participate in a game where they share balloons according to these rules:

  1. At each step, each house sends half of its balloons to the next house. For the last house, the next house is the first one, creating a circular pattern.
  2. The number of balloons shared is always rounded down (e.g., if a house has 5 balloons, it sends 2).
  3. The game ends when the number of balloons at each house stops changing between steps.

Your task is to implement a Ruby function simulate_balloon_game(balloons) that simulates this game and returns the number of steps it takes for the balloon distribution to stabilize.

Example:

If balloons = [4, 1, 2], the output should be 3. Here’s why:

  • After step 1: [3, 3, 1]
  • After step 2: [2, 3, 2]
  • After step 3: [2, 3, 2] (no change from the previous step)

Thus, it takes 3 steps for the game to stabilize.

Solution Building: Step 1 - Understanding the Problem

This task requires understanding cyclic arrays, where the last index wraps around to the first. For example, house n sends balloons to house 1. This cyclical behavior makes it essential to handle array indices carefully. Using modular arithmetic (%) helps manage this wrapping behavior efficiently.

Solution Building: Step 2 - Setting Up the Loop

We’ll start by setting up a loop to simulate each step of the game. The loop will terminate when the balloon distribution stops changing.

Here's the foundation of our solution:

Ruby
def simulate_balloon_game(balloons)
  steps = 0
  loop do
    steps += 1
    new_balloons = balloons.dup  # Create a copy to hold updated values
    # Balloon sharing logic will be implemented here
    break if new_balloons == balloons  # Stop when no change occurs
    balloons = new_balloons  # Update for the next step
  end
  steps
end

This snippet tracks the number of steps and ensures that we terminate the loop once the balloon distribution stabilizes.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal