ADS
Algorithms and Data Structures
Loading...
Searching...
No Matches
CoinGame.h

The game of the coins in a line. More...

Files

file  ADS/optimization/CoinGame.h
 The game of the coins in a line: \( n \) coins of values \( V_0 , \ldots , V_{n-1} \) lie in a row, and two players take in turn the first or the last coin left, each one to get the most; coinsInALine() is the most the first player can be sure of, against any play of the other.

Functions

template<class T>
T ADS::coinsInALine (const std::vector< T > &V)
 the most the first player can be sure of in the game of the coins in a line \( V \), both players taking in turn the first or the last coin

Detailed description

The game of the coins in a line.

The definitions, the invariants and the costs of the area are in Theory of optimization.

Function documentation

◆ coinsInALine()

template<class T>
T ADS::coinsInALine ( const std::vector< T > & V)

the most the first player can be sure of in the game of the coins in a line \( V \), both players taking in turn the first or the last coin

In pseudocode (exercise B4 of 22/07/2013, Gioco di monete, of the Esercizi Programmazione dinamica of the book), \( D[ i ] \) holding \( D[ i ][ i + h ] \) for the current length \( h \):

\[\class{pseudocode}{\begin{array}{r@{\quad}l} 1 & \textbf{function}\ \mathrm{coinsInALine}( V[ 0 .. n - 1 ] )\quad \triangleright\ D[ i ] \text{ the best lead on } V[ i .. i + h - 1 ] \cr 2 & \quad D[ 0 .. n ] \gets 0\quad \triangleright\ h = 0 \text{: no coin} \cr 3 & \quad \textbf{for}\ h \gets 1\ \textbf{to}\ n\ \textbf{do}\quad \triangleright\ \text{one row for each length, in place} \cr 4 & \qquad D[ i ] \gets \max\{ V[ i ] - D[ i + 1 ] , V[ i + h - 1 ] - D[ i ] \} \text{ for } i = 0 , \ldots , n - h \cr 5 & \quad \textbf{return}\ ( D[ 0 ] + \textstyle\sum_i V[ i ] ) / 2\quad \triangleright\ \text{the first player's total} \end{array}} \]