Search code examples
rubyrecursionmultidimensional-arraysaas

Problems calling a recursive function on a multi-dimensional nested array


I am trying to split the sub-arrays if there are more than 8. I have tried calling the rps_tournament_winner function on players if it has a flattened length longer than 16 but I get a "stack too deep error".

Do I have to work on the players variable or tournament? I'm looking for a nudge in the right direction; not a complete solution.

def rps_tournament_winner(tournament)
  return rps_game_winner(tournament) if tournament.flatten.length == 4
  players = tournament.flatten(2)  

  while players.length > 1
    players = players.each_slice(2).map { |x| rps_game_winner(x) }
  end

  players[0]
end

Solution

  • I solved it using recursion

    class WrongNumberOfPlayersError < StandardError ; end
    class NoSuchStrategyError < StandardError ; end
    
    def rps_game_winner(game)
      raise WrongNumberOfPlayersError unless game.length == 2
      if game[0][0].is_a?(Array) then
        winner1 = rps_game_winner(game[0])
        winner2 = rps_game_winner(game[1])
        game = [winner1, winner2]
      end
      raise NoSuchStrategyError unless /^(P|R|S){2}$/ =~ game[0][1] + game[1][1]
      case game[0][1]
        when "R"
          if game[1][1] == "P" then
            game[1]
          else
            game[0]
          end
        when "P"
          if game[1][1] == "S" then
            game[1]
          else 
            game[0]
          end
        when "S"
          if game[1][1] == "R" then
            game[1]
          else
            game[0]
          end
      end
    end
    
    def rps_tournament_winner(tournament)
      rps_game_winner(tournament)
    end