Padovan sequence

The Fibonacci sequence in several ways.
Some are given in the table below, and the referenced video shows some of the geometric
similarities.

::{| class="wikitable"
! Comment !! Padovan !! Fibonacci
|-
|  ||  ||
|-
| Named after. || Richard Padovan || Leonardo of Pisa: Fibonacci
|-
|  ||  ||
|-
| Recurrence initial values. || P(0)=P(1)=P(2)=1 || F(0)=0, F(1)=1
|-
| Recurrence relation. || P(n)=P(n-2)+P(n-3) || F(n)=F(n-1)+F(n-2)
|-
|  ||  ||
|-
| First 10 terms. || 1,1,1,2,2,3,4,5,7,9 || 0,1,1,2,3,5,8,13,21,34
|-
|  ||  ||
|-
| Ratio of successive terms... || Plastic ratio, p || Golden ratio, g
|-
|  || 1.324717957244746025960908854... || 1.6180339887498948482...
|-
| Exact formula of ratios p and q. || ((9+69**.5)/18)**(1/3) + ((9-69**.5)/18)**(1/3) || (1+5**0.5)/2
|-
| Ratio is real root of polynomial. || p: x**3-x-1 || g: x**2-x-1
|-
|  ||  ||
|-
| Spirally tiling the plane using. || Equilateral triangles || Squares
|-
|  ||  ||
|-
| Constants for ... || s= 1.0453567932525329623 || a=5**0.5
|-
| ... Computing by truncation. || P(n)=floor(p**(n-1) / s + .5) || F(n)=floor(g**n / a + .5)
|-
|  ||  ||
|-
| L-System Variables. || A,B,C || A,B
|-
| L-System Start/Axiom. || A || A
|-
| L-System Rules. || A->B,B->C,C->AB || A->B,B->AB
|}

;Task:
* Write a function/method/subroutine to compute successive members of the Padovan series using the recurrence relation.
* Write a function/method/subroutine to compute successive members of the Padovan series using the floor function.
* Show the first twenty terms of the sequence.
* Confirm that the recurrence and floor based functions give the same results for 64 terms,
* Write a function/method/... using the L-system to generate successive strings.
* Show the first 10 strings produced from the L-system
* Confirm that the length of the first 32 strings produced is the Padovan sequence.

Show output here, on this page.

;Ref:
* The Plastic Ratio - Numberphile video.

Solution:
#include <iostream>
#include <map>
#include <cmath>

// Generate the Padovan sequence using the recurrence
// relationship.
int pRec(int n) {
    static std::map<int,int> memo;
    auto it = memo.find(n);
    if (it != memo.end()) return it->second;

    if (n <= 2) memo[n] = 1;
    else memo[n] = pRec(n-2) + pRec(n-3);
    return memo[n];
}

// Calculate the N'th Padovan sequence using the
// floor function.
int pFloor(int n) {
    long const double p = 1.324717957244746025960908854;
    long const double s = 1.0453567932525329623;
    return std::pow(p, n-1)/s + 0.5;
}

// Return the N'th L-system string
std::string& lSystem(int n) {
    static std::map<int,std::string> memo;
    auto it = memo.find(n);
    if (it != memo.end()) return it->second;

    if (n == 0) memo[n] = "A";
    else {
        memo[n] = "";
        for (char ch : memo[n-1]) {
            switch(ch) {
                case 'A': memo[n].push_back('B'); break;
                case 'B': memo[n].push_back('C'); break;
                case 'C': memo[n].append("AB"); break;
            }
        }
    }
    return memo[n];
}

// Compare two functions up to p_N
using pFn = int(*)(int);
void compare(pFn f1, pFn f2, const char* descr, int stop) {
    std::cout << "The " << descr << " functions ";
    int i;
    for (i=0; i<stop; i++) {
        int n1 = f1(i);
        int n2 = f2(i);
        if (n1 != n2) {
            std::cout << "do not match at " << i
                      << ": " << n1 << " != " << n2 << ".\n";
            break;
        }
    }
    if (i == stop) {
        std::cout << "match from P_0 to P_" << stop << ".\n";
    }
}

int main() {
    /* Print P_0 to P_19 */
    std::cout << "P_0 .. P_19: ";
    for (int i=0; i<20; i++) std::cout << pRec(i) << " ";
    std::cout << "\n";

    /* Check that floor and recurrence match up to P_64 */
    compare(pFloor, pRec, "floor- and recurrence-based", 64);

    /* Show first 10 L-system strings */
    std::cout << "\nThe first 10 L-system strings are:\n";
    for (int i=0; i<10; i++) std::cout << lSystem(i) << "\n";
    std::cout << "\n";

    /* Check lengths of strings against pFloor up to P_31 */
    compare(pFloor, [](int n){return (int)lSystem(n).length();},
                            "floor- and L-system-based", 32);
    return 0;
}


Palindromic gapful numbers

Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the
first and last digit are known as   '''gapful numbers'''.

''Evenly divisible''   means divisible with   no   remainder.

All   one-   and two-digit   numbers have this property and are trivially excluded.   Only
numbers    >=  '''100'''   will be considered for this Rosetta Code task.

;Example:
'''1037'''   is a   '''gapful'''   number because it is evenly divisible by the
number   '''17'''   which is formed by the first and last decimal digits
of    '''1037'''.

A palindromic number is   (for this task, a positive integer expressed in base ten),   when the number is
reversed,   is the same as the original number.

;Task:
:*   Show   (nine sets)   the first   '''20'''   palindromic gapful numbers that   ''end''   with:
:::*   the digit   '''1'''
:::*   the digit   '''2'''
:::*   the digit   '''3'''
:::*   the digit   '''4'''
:::*   the digit   '''5'''
:::*   the digit   '''6'''
:::*   the digit   '''7'''
:::*   the digit   '''8'''
:::*   the digit   '''9'''
:*   Show   (nine sets, like above)   of palindromic gapful numbers:
:::*   the last   '''15'''   palindromic gapful numbers   (out of      '''100''')
:::*   the last   '''10'''   palindromic gapful numbers   (out of                '''1,000''')       {optional}

For other ways of expressing the (above) requirements, see the   ''discussion''   page.

;Note:
All palindromic gapful numbers are divisible by eleven.

;Related tasks:
:*   palindrome detection.
:*   gapful numbers.

;Also see:
:*   The OEIS entry:   A108343 gapful numbers.

Solution:
#include <iostream>
#include <cstdint>

typedef uint64_t integer;

integer reverse(integer n) {
    integer rev = 0;
    while (n > 0) {
        rev = rev * 10 + (n % 10);
        n /= 10;
    }
    return rev;
}

// generates base 10 palindromes greater than 100 starting
// with the specified digit
class palindrome_generator {
public:
    palindrome_generator(int digit) : power_(10), next_(digit * power_ - 1),
        digit_(digit), even_(false) {}
    integer next_palindrome() {
        ++next_;
        if (next_ == power_ * (digit_ + 1)) {
            if (even_)
                power_ *= 10;
            next_ = digit_ * power_;
            even_ = !even_;
        }
        return next_ * (even_ ? 10 * power_ : power_)
            + reverse(even_ ? next_ : next_/10);
    }
private:
    integer power_;
    integer next_;
    int digit_;
    bool even_;
};

bool gapful(integer n) {
    integer m = n;
    while (m >= 10)
        m /= 10;
    return n % (n % 10 + 10 * m) == 0;
}

template<size_t len>
void print(integer (&array)[9][len]) {
    for (int digit = 1; digit < 10; ++digit) {
        std::cout << digit << ":";
        for (int i = 0; i < len; ++i)
            std::cout << ' ' << array[digit - 1][i];
        std::cout << '\n';
    }
}

int main() {
    const int n1 = 20, n2 = 15, n3 = 10;
    const int m1 = 100, m2 = 1000;

    integer pg1[9][n1];
    integer pg2[9][n2];
    integer pg3[9][n3];

    for (int digit = 1; digit < 10; ++digit) {
        palindrome_generator pgen(digit);
        for (int i = 0; i < m2; ) {
            integer n = pgen.next_palindrome();
            if (!gapful(n))
                continue;
            if (i < n1)
                pg1[digit - 1][i] = n;
            else if (i < m1 && i >= m1 - n2)
                pg2[digit - 1][i - (m1 - n2)] = n;
            else if (i >= m2 - n3)
                pg3[digit - 1][i - (m2 - n3)] = n;
            ++i;
        }
    }

    std::cout << "First " << n1 << " palindromic gapful numbers ending in:\n";
    print(pg1);

    std::cout << "\nLast " << n2 << " of first " << m1 << " palindromic gapful numbers ending in:\n";
    print(pg2);

    std::cout << "\nLast " << n3 << " of first " << m2 << " palindromic gapful numbers ending in:\n";
    print(pg3);

    return 0;
}


Pancake numbers

Adrian Monk has problems and an assistant,  Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.

The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.

[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?

Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).

;References
# Bill Gates and the pancake problem
# A058986

Solution:
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <numeric>
#include <iomanip>

std::vector<int32_t> flip_stack(std::vector<int32_t>& stack, const int32_t index) {
	reverse(stack.begin(), stack.begin() + index);
	return stack;
}

std::pair<std::vector<int32_t>, int32_t> pancake(const int32_t number) {
	std::vector<int32_t> initial_stack(number);
	std::iota(initial_stack.begin(), initial_stack.end(), 1);
	std::map<std::vector<int32_t>, int32_t> stack_flips = { std::make_pair(initial_stack, 1) };
	std::queue<std::vector<int32_t>> queue;
	queue.push(initial_stack);

	while ( ! queue.empty() ) {
		std::vector<int32_t> stack = queue.front();
		queue.pop();

		const int32_t flips = stack_flips[stack] + 1;
		for ( int i = 2; i <= number; ++i ) {
			std::vector<int32_t> flipped = flip_stack(stack, i);
			if ( stack_flips.find(flipped) == stack_flips.end() ) {
				stack_flips[flipped] = flips;
				queue.push(flipped);
			}
		}
    }

	auto ptr = std::max_element(
		stack_flips.begin(), stack_flips.end(),
		[] ( const auto & pair1, const auto & pair2 ) {
	    	return pair1.second < pair2.second;
		}
	);

	return std::make_pair(ptr->first, ptr->second);
}

int main() {
	for ( int32_t n = 1; n <= 9; ++n ) {
		std::pair<std::vector<int32_t>, int32_t> result = pancake(n);
		std::cout << "pancake(" << n << ") = " << std::setw(2) << result.second << ". Example [";
		for ( uint64_t i = 0; i < result.first.size() - 1; ++i ) {
			std::cout << result.first[i] << ", ";
		}
		std::cout << result.first.back() << "]" << std::endl;
	}
}


Pangram checker

A pangram is a sentence that contains all the letters of the English alphabet at least once.

For example:   ''The quick brown fox jumps over the lazy dog''.

;Task:
Write a function or method to check a sentence to see if it is a   pangram   (or not)   and show its use.

;Related tasks:
:*   determine if a string has all the same characters
:*   determine if a string has all unique characters

Solution:
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>

const std::string alphabet("abcdefghijklmnopqrstuvwxyz");

bool is_pangram(std::string s)
{
    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
    std::sort(s.begin(), s.end());
    return std::includes(s.begin(), s.end(), alphabet.begin(), alphabet.end());
}

int main()
{
    const auto examples = {"The quick brown fox jumps over the lazy dog",
                           "The quick white cat jumps over the lazy dog"};

    std::cout.setf(std::ios::boolalpha);
    for (auto& text : examples) {
        std::cout << "Is \"" << text << "\" a pangram? - " << is_pangram(text) << std::endl;
    }
}


Parsing/RPN calculator algorithm

Create a stack-based evaluator for an expression in   reverse Polish notation (RPN)   that also shows the changes in the stack as each individual token is processed ''as a table''.

* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the   [[Parsing/Shunting-yard algorithm]]   task:
         3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here

;Notes:
*    '''^'''    means exponentiation in the expression above.
*    '''/'''    means division.

;See also:
*   [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
*   Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
*   [[Parsing/RPN to infix conversion]].
*   [[Arithmetic evaluation]].

Solution:
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <iterator>
#include <cstdlib>

double rpn(const std::string &expr){
  std::istringstream iss(expr);
  std::vector<double> stack;
  std::cout << "Input\tOperation\tStack after" << std::endl;
  std::string token;
  while (iss >> token) {
    std::cout << token << "\t";
    double tokenNum;
    if (std::istringstream(token) >> tokenNum) {
      std::cout << "Push\t\t";
      stack.push_back(tokenNum);
    } else {
      std::cout << "Operate\t\t";
      double secondOperand = stack.back();
      stack.pop_back();
      double firstOperand = stack.back();
      stack.pop_back();
      if (token == "*")
	stack.push_back(firstOperand * secondOperand);
      else if (token == "/")
	stack.push_back(firstOperand / secondOperand);
      else if (token == "-")
	stack.push_back(firstOperand - secondOperand);
      else if (token == "+")
	stack.push_back(firstOperand + secondOperand);
      else if (token == "^")
	stack.push_back(std::pow(firstOperand, secondOperand));
      else { //just in case
	std::cerr << "Error" << std::endl;
	std::exit(1);
      }
    }
    std::copy(stack.begin(), stack.end(), std::ostream_iterator<double>(std::cout, " "));
    std::cout << std::endl;
  }
  return stack.back();
}

int main() {
  std::string s = " 3 4 2 * 1 5 - 2 3 ^ ^ / + ";
  std::cout << "Final answer: " << rpn(s) << std::endl;

  return 0;
}


Parsing/RPN to infix conversion

Create a program that takes an infix notation.

* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}

* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                    ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                    *   ||  3  ||   left  ||  multiplication
|- || align="center"
|                    /   ||  3  ||   left  ||     division
|- || align="center"
|                    +   ||  2  ||   left  ||     addition
|- || align="center"
|                    -   ||  2  ||   left  ||   subtraction
|}

;See also:
*   [[Parsing/Shunting-yard algorithm]]   for a method of generating an RPN from an infix expression.
*   [[Parsing/RPN calculator algorithm]]   for a method of calculating a final value from this output RPN expression.
*   Postfix to infix   from the RubyQuiz site.

Solution:
#include <iostream>
#include <stack>
#include <string>
#include <map>
#include <set>

using namespace std;

struct Entry_
{
	string expr_;
	string op_;
};

bool PrecedenceLess(const string& lhs, const string& rhs, bool assoc)
{
	static const map<string, int> KNOWN({ { "+", 1 }, { "-", 1 }, { "*", 2 }, { "/", 2 }, { "^", 3 } });
	static const set<string> ASSOCIATIVE({ "+", "*" });
	return (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0);
}
void Parenthesize(Entry_* old, const string& token, bool assoc)
{
	if (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc))
		old->expr_ = '(' + old->expr_ + ')';
}

void AddToken(stack<Entry_>* stack, const string& token)
{
	if (token.find_first_of("0123456789") != string::npos)
		stack->push(Entry_({ token, string() }));	// it's a number, no operator
	else
	{	// it's an operator
		if (stack->size() < 2)
			cout<<"Stack underflow";
		auto rhs = stack->top();
		Parenthesize(&rhs, token, false);
		stack->pop();
		auto lhs = stack->top();
		Parenthesize(&lhs, token, true);
		stack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_;
		stack->top().op_ = token;
	}
}

string ToInfix(const string& src)
{
	stack<Entry_> stack;
	for (auto start = src.begin(), p = src.begin(); ; ++p)
	{
		if (p == src.end() || *p == ' ')
		{
			if (p > start)
				AddToken(&stack, string(start, p));
			if (p == src.end())
				break;
			start = p + 1;
		}
	}
	if (stack.size() != 1)
		cout<<"Incomplete expression";
	return stack.top().expr_;
}

int main(void)
{
	try
	{
		cout << ToInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +") << "\n";
		cout << ToInfix("1 2 + 3 4 + ^ 5 6 + ^") << "\n";
		return 0;
	}
	catch (...)
	{
		cout << "Failed\n";
		return -1;
	}
}


Parsing/Shunting-yard algorithm

Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output
as each individual token is processed.

* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
::::  3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"

! operator !! associativity !! operation
|- || align="center"
|                     ^   ||  4  ||  right  ||  exponentiation
|- || align="center"
|                     *   ||  3  ||  left   ||  multiplication
|- || align="center"
|                     /   ||  3  ||  left   ||  division
|- || align="center"
|                     +   ||  2  ||  left   ||  addition
|- || align="center"
|                     -   ||  2  ||  left   ||  subtraction
|}

;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.

;Note
The handling of functions and arguments is not required.

;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].

Solution:
#include <ciso646>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

using std::vector;
using std::string;

//-------------------------------------------------------------------------------------------------
// throw error( "You ", profanity, "ed up!" );  // Don't mess up, okay?
//-------------------------------------------------------------------------------------------------
#include <exception>
#include <stdexcept>
template <typename...Args> std::runtime_error error( Args...args )
{
  return std::runtime_error( (std::ostringstream{} << ... << args).str() );
};

//-------------------------------------------------------------------------------------------------
// Stack
//-------------------------------------------------------------------------------------------------
// Let us co-opt a vector for our stack type.
// C++ pedants: no splicing possible == totally okay to do this.
//
// Note: C++ provides a more appropriate std::stack class, except that the task requires us to
// be able to display its contents, and that kind of access is an expressly non-stack behavior.

template <typename T> struct stack : public std::vector <T>
{
  using base_type = std::vector <T> ;
  T        push ( const T& x ) { base_type::push_back( x ); return x; }
  const T& top  ()             { return base_type::back(); }
  T        pop  ()             { T x = std::move( top() ); base_type::pop_back(); return x; }
  bool     empty()             { return base_type::empty(); }
};

//-------------------------------------------------------------------------------------------------
using Number = double;
//-------------------------------------------------------------------------------------------------
// Numbers are already too awesome to need extra diddling.

//-------------------------------------------------------------------------------------------------
// Operators
//-------------------------------------------------------------------------------------------------
using Operator_Name = string;
using Precedence    = int;
enum class Associates { none, left_to_right, right_to_left };

struct Operator_Info { Precedence precedence; Associates associativity; };

std::unordered_map <Operator_Name, Operator_Info>  Operators =
{
  { "^", { 4, Associates::right_to_left } },
  { "*", { 3, Associates::left_to_right } },
  { "/", { 3, Associates::left_to_right } },
  { "+", { 2, Associates::left_to_right } },
  { "-", { 2, Associates::left_to_right } },
};

Precedence precedence   ( const Operator_Name& op ) { return Operators[ op ].precedence; }
Associates associativity( const Operator_Name& op ) { return Operators[ op ].associativity; }

//-------------------------------------------------------------------------------------------------
using Token = string;
//-------------------------------------------------------------------------------------------------
bool is_number           ( const Token& t ) { return regex_match( t, std::regex{ R"z((\d+(\.\d*)?|\.\d+)([Ee][\+\-]?\d+)?)z" } ); }
bool is_operator         ( const Token& t ) { return Operators.count( t ); }
bool is_open_parenthesis ( const Token& t ) { return t == "("; }
bool is_close_parenthesis( const Token& t ) { return t == ")"; }
bool is_parenthesis      ( const Token& t ) { return is_open_parenthesis( t ) or is_close_parenthesis( t ); }

//-------------------------------------------------------------------------------------------------
// std::cout << a_vector_of_something;
//-------------------------------------------------------------------------------------------------
// Weird C++ stream operator stuff (for I/O).
// Don't worry if this doesn't look like it makes any sense.
//
template <typename T> std::ostream& operator << ( std::ostream& outs, const std::vector <T> & xs )
{
  std::size_t n = 0;  for (auto x : xs) outs << (n++ ? " " : "") << x;  return outs;
}

//-------------------------------------------------------------------------------------------------
// Progressive_Display
//-------------------------------------------------------------------------------------------------
// This implements the required task:
//   "use the algorithm to show the changes in the operator
//    stack and RPN output as each individual token is processed"
//
#include <iomanip>

struct Progressive_Display
{
  string token_name;
  string token_type;

  Progressive_Display()  // Header for the table we are going to generate
  {
    std::cout << "\n"
      "  INPUT │ TYPE │ ACTION           │ STACK        │ OUTPUT\n"
      "────────┼──────┼──────────────────┼──────────────┼─────────────────────────────\n";
  }

  Progressive_Display& operator () ( const Token& token )  // Ready the first two columns
  {
    token_name = token;
    token_type = is_operator   ( token ) ? "op"
               : is_parenthesis( token ) ? "()"
               : is_number     ( token ) ? "num"
               : "";
    return *this;
  }

  Progressive_Display& operator () (  // Display all columns of a row
    const string         & description,
    const stack  <Token> & stack,
    const vector <Token> & output )
  {
    std::cout                                                              << std::right
      << std::setw(  7 ) << token_name                            << " │ " << std::left
      << std::setw(  4 ) << token_type                            << " │ "
      << std::setw( 16 ) << description                           << " │ "
      << std::setw( 12 ) << (std::ostringstream{} << stack).str() << " │ "
      <<                    output                                << "\n";
    return operator () ( "" );  // Reset the first two columns to empty for next iteration
  }
};

//-------------------------------------------------------------------------------------------------
vector <Token> parse( const vector <Token> & tokens )
//-------------------------------------------------------------------------------------------------
{
  vector <Token> output;
  stack  <Token> stack;

  Progressive_Display display;

  for (auto token : tokens)  // Shunting Yard takes a single linear pass through the tokens

    //.........................................................................
    if (is_number( token ))
    {
      output.push_back( token );
      display( token )( "num --> output", stack, output );
    }

    //.........................................................................
    else if (is_operator( token ) or is_parenthesis( token ))
    {
      display( token );

      if (!is_open_parenthesis( token ))
      {
        // pop --> output
        //   : until '(' if token is ')'
        //   : while prec(token) > prec(top)
        //   : while prec(token) == prec(top) AND assoc(token) is left-to-right
        while (!stack.empty()
          and (   (is_close_parenthesis( token ) and !is_open_parenthesis( stack.top() ))
               or (precedence( stack.top() ) > precedence( token ))
               or (    (precedence( stack.top() ) == precedence( token ))
                   and (associativity( token ) == Associates::left_to_right))))
        {
          output.push_back( stack.pop() );
          display( "pop --> output", stack, output );
        }

        // If we popped until '(' because token is ')', toss both parens
        if (is_close_parenthesis( token ))
        {
          stack.pop();
          display( "pop", stack, output );
        }
      }

      // Everything except ')' --> stack
      if (!is_close_parenthesis( token ))
      {
        stack.push( token );
        display( "push op", stack, output );
      }
    }

    //.........................................................................
    else throw error( "unexpected token: ", token );

  // Anything left on the operator stack just gets moved to the output

  display( "END" );
  while (!stack.empty())
  {
    output.push_back( stack.pop() );
    display( "pop --> output", stack, output );
  }

  return output;
}

//-------------------------------------------------------------------------------------------------
int main( int argc, char** argv )
//-------------------------------------------------------------------------------------------------
try
{
  auto tokens   = vector <Token> ( argv+1, argv+argc );
  auto rpn_expr = parse( tokens );
  std::cout
    << "\nInfix = " << tokens
    << "\nRPN   = " << rpn_expr
    << "\n";
}
catch (std::exception e)
{
  std::cerr << "error: " << e.what() << "\n";
  return 1;
}


Parsing/Shunting-yard algorithm

Solution:
#include <iostream>
#include <sstream>
#include <stack>

std::string infixToPostfix(const std::string& infix) {
    const std::string ops = "-+/*^";
    std::stringstream ss;
    std::stack<int> s;

    std::stringstream input(infix);
    std::string token;
    while (std::getline(input, token, ' ')) {
        if (token.empty()) {
            continue;
        }

        char c = token[0];
        size_t idx = ops.find(c);

        // check for operator
        if (idx != std::string::npos) {
            while (!s.empty()) {
                int prec2 = s.top() / 2;
                int prec1 = idx / 2;
                if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {
                    ss << ops[s.top()] << ' ';
                    s.pop();
                } else break;
            }
            s.push(idx);
        } else if (c == '(') {
            s.push(-2); // -2 stands for '('
        } else if (c == ')') {
            // until '(' on stack, pop operators.
            while (s.top() != -2) {
                ss << ops[s.top()] << ' ';
                s.pop();
            }
            s.pop();
        } else {
            ss << token << ' ';
        }
    }

    while (!s.empty()) {
        ss << ops[s.top()] << ' ';
        s.pop();
    }

    return ss.str();
}

int main() {
    std::string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
    std::cout << "infix:   " << infix << '\n';
    std::cout << "postfix: " << infixToPostfix(infix) << '\n';

    return 0;
}


Particle fountain

Implement a particle fountain.

Emulate a fountain of water droplets in a gravitational field being sprayed up and then falling back down.

The particle fountain should be generally ordered but individually chaotic; the particles should be going mostly in the same direction, but should have slightly different vectors.

Your fountain should have at least several hundred particles in motion at any one time, and ideally several thousand.

It is optional to have the individual particle interact with each other.

If at all possible, link to a short video clip of your fountain in action.

Off-site link to a demo video

Solution:
#include <SDL2/SDL.h>

#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <memory>
#include <random>
#include <tuple>
#include <vector>

auto now() {
    using namespace std::chrono;
    auto time = system_clock::now();
    return duration_cast<milliseconds>(time.time_since_epoch()).count();
}

auto hsv_to_rgb(int h, double s, double v) {
    double hp = h / 60.0;
    double c = s * v;
    double x = c * (1 - std::abs(std::fmod(hp, 2) - 1));
    double m = v - c;
    double r = 0, g = 0, b = 0;
    if (hp <= 1) {
        r = c;
        g = x;
    } else if (hp <= 2) {
        r = x;
        g = c;
    } else if (hp <= 3) {
        g = c;
        b = x;
    } else if (hp <= 4) {
        g = x;
        b = c;
    } else if (hp <= 5) {
        r = x;
        b = c;
    } else {
        r = c;
        b = x;
    }
    r += m;
    g += m;
    b += m;
    return std::make_tuple(Uint8(r * 255), Uint8(g * 255), Uint8(b * 255));
}

class ParticleFountain {
public:
    ParticleFountain(int particles, int width, int height);
    void run();

private:
    struct WindowDeleter {
        void operator()(SDL_Window* window) const { SDL_DestroyWindow(window); }
    };
    struct RendererDeleter {
        void operator()(SDL_Renderer* renderer) const {
            SDL_DestroyRenderer(renderer);
        }
    };
    struct PointInfo {
        double x = 0;
        double y = 0;
        double vx = 0;
        double vy = 0;
        double lifetime = 0;
    };

    void update(double df);
    bool handle_event();
    void render();
    double rand() { return dist_(rng_); }
    double reciprocate() const {
        return reciprocate_ ? range_ * std::sin(now() / 1000.0) : 0.0;
    }

    std::unique_ptr<SDL_Window, WindowDeleter> window_;
    std::unique_ptr<SDL_Renderer, RendererDeleter> renderer_;
    int width_;
    int height_;
    std::vector<PointInfo> point_info_;
    std::vector<SDL_Point> points_;
    int num_points_ = 0;
    double saturation_ = 0.4;
    double spread_ = 1.5;
    double range_ = 1.5;
    bool reciprocate_ = false;
    std::mt19937 rng_;
    std::uniform_real_distribution<> dist_;
};

ParticleFountain::ParticleFountain(int n, int width, int height)
    : width_(width), height_(height), point_info_(n), points_(n, {0, 0}),
      rng_(std::random_device{}()), dist_(0.0, 1.0) {
    window_.reset(SDL_CreateWindow(
        "C++ Particle System!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
        width, height, SDL_WINDOW_RESIZABLE));
    if (window_ == nullptr)
        throw std::runtime_error(SDL_GetError());

    renderer_.reset(
        SDL_CreateRenderer(window_.get(), -1, SDL_RENDERER_ACCELERATED));
    if (renderer_ == nullptr)
        throw std::runtime_error(SDL_GetError());
}

void ParticleFountain::run() {
    for (double df = 0.0001;;) {
        auto start = now();
        if (!handle_event())
            break;
        update(df);
        render();
        df = (now() - start) / 1000.0;
    }
}

void ParticleFountain::update(double df) {
    int pointidx = 0;
    for (PointInfo& point : point_info_) {
        bool willdraw = false;
        if (point.lifetime <= 0.0) {
            if (rand() < df) {
                point.lifetime = 2.5;
                point.x = width_ / 20.0;
                point.y = height_ / 10.0;
                point.vx =
                    (spread_ * rand() - spread_ / 2 + reciprocate()) * 10.0;
                point.vy = (rand() - 2.9) * height_ / 20.5;
                willdraw = true;
            }
        } else {
            if (point.y > height_ / 10.0 && point.vy > 0)
                point.vy *= -0.3;
            point.vy += (height_ / 10.0) * df;
            point.x += point.vx * df;
            point.y += point.vy * df;
            point.lifetime -= df;
            willdraw = true;
        }
        if (willdraw) {
            points_[pointidx].x = std::floor(point.x * 10.0);
            points_[pointidx].y = std::floor(point.y * 10.0);
            ++pointidx;
        }
    }
    num_points_ = pointidx;
}

bool ParticleFountain::handle_event() {
    bool result = true;
    SDL_Event event;
    while (result && SDL_PollEvent(&event)) {
        switch (event.type) {
        case SDL_QUIT:
            result = false;
            break;
        case SDL_WINDOWEVENT:
            if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
                width_ = event.window.data1;
                height_ = event.window.data2;
            }
            break;
        case SDL_KEYDOWN:
            switch (event.key.keysym.scancode) {
            case SDL_SCANCODE_UP:
                saturation_ = std::min(saturation_ + 0.1, 1.0);
                break;
            case SDL_SCANCODE_DOWN:
                saturation_ = std::max(saturation_ - 0.1, 0.0);
                break;
            case SDL_SCANCODE_PAGEUP:
                spread_ = std::min(spread_ + 0.1, 5.0);
                break;
            case SDL_SCANCODE_PAGEDOWN:
                spread_ = std::max(spread_ - 0.1, 0.2);
                break;
            case SDL_SCANCODE_RIGHT:
                range_ = std::min(range_ + 0.1, 2.0);
                break;
            case SDL_SCANCODE_LEFT:
                range_ = std::max(range_ - 0.1, 0.1);
                break;
            case SDL_SCANCODE_SPACE:
                reciprocate_ = !reciprocate_;
                break;
            case SDL_SCANCODE_Q:
                result = false;
                break;
            default:
                break;
            }
            break;
        }
    }
    return result;
}

void ParticleFountain::render() {
    SDL_Renderer* renderer = renderer_.get();
    SDL_SetRenderDrawColor(renderer, 0x0, 0x0, 0x0, 0xff);
    SDL_RenderClear(renderer);
    auto [red, green, blue] = hsv_to_rgb((now() % 5) * 72, saturation_, 1);
    SDL_SetRenderDrawColor(renderer, red, green, blue, 0x7f);
    SDL_RenderDrawPoints(renderer, points_.data(), num_points_);
    SDL_RenderPresent(renderer);
}

int main() {
    std::cout << "Use UP and DOWN arrow keys to modify the saturation of the "
                 "particle colors.\n"
                 "Use PAGE UP and PAGE DOWN keys to modify the \"spread\" of "
                 "the particles.\n"
                 "Toggle reciprocation off / on with the SPACE bar.\n"
                 "Use LEFT and RIGHT arrow keys to modify angle range for "
                 "reciprocation.\n"
                 "Press the \"q\" key to quit.\n";

    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
        std::cerr << "ERROR: " << SDL_GetError() << '\n';
        return EXIT_FAILURE;
    }

    try {
        ParticleFountain pf(3000, 800, 800);
        pf.run();
    } catch (const std::exception& ex) {
        std::cerr << "ERROR: " << ex.what() << '\n';
        SDL_Quit();
        return EXIT_FAILURE;
    }

    SDL_Quit();
    return EXIT_SUCCESS;
}


Pascal's triangle/Puzzle

This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.

           [ 151]
          [  ][  ]
        [40][  ][  ]
      [  ][  ][  ][  ]
    [ X][11][ Y][ 4][ Z]

Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).

;Task:
Write a program to find a solution to this puzzle.

Solution:
#include <iostream>
#include <iomanip>

inline int sign(int i) {
    return i < 0 ? -1 : i > 0;
}

inline int& E(int *x, int row, int col) {
    return x[row * (row + 1) / 2 + col];
}

int iter(int *v, int *diff) {
    // enforce boundary conditions
    E(v, 0, 0) = 151;
    E(v, 2, 0) = 40;
    E(v, 4, 1) = 11;
    E(v, 4, 3) = 4;

    // calculate difference from equilibrium
    for (auto i = 1u; i < 5u; i++)
        for (auto j = 0u; j <= i; j++) {
            E(diff, i, j) = 0;
            if (j < i)
                E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j);
            if (j)
                E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j);
        }

    for (auto i = 0u; i < 4u; i++)
        for (auto j = 0u; j < i; j++)
            E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j);

    E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2);

    // do feedback, check if we are done
    uint sum;
    int e = 0;
    for (auto i = sum = 0u; i < 15u; i++) {
        sum += !!sign(e = diff[i]);

        // 1/5-ish feedback strength on average.  These numbers are highly magical, depending on nodes' connectivities
        if (e >= 4 || e <= -4)
            v[i] += e / 5;
        else if (rand() < RAND_MAX / 4)
            v[i] += sign(e);
    }
    return sum;
}

void show(int *x) {
    for (auto i = 0u; i < 5u; i++)
        for (auto j = 0u; j <= i; j++)
            std::cout << std::setw(4u) << *(x++) << (j < i ? ' ' : '\n');
}

int main() {
    int v[15] = { 0 }, diff[15] = { 0 };
    for (auto i = 1u, s = 1u; s; i++) {
        s = iter(v, diff);
        std::cout << "pass " << i << ": " << s << std::endl;
    }
    show(v);

    return 0;
}


Password generator

Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
          lower-case letters:  a --> z
          upper-case letters:  A --> Z
                      digits:  0 --> 9
  other printable characters:  !"#$%&'()*+,-./:;<=>?@[]^_{|}~
  (the above character list excludes white-space, backslash and grave)

The generated password(s) must include   ''at least one''   (of each of the four groups):
    lower-case letter,
    upper-case letter,
    digit  (numeral),   and
    one  "other"  character.

The user must be able to specify the password length and the number of passwords to generate.

The passwords should be displayed or written to a file, one per line.

The randomness should be from a system source or library.

The program should implement a help option or button which should describe the program and options when invoked.

You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.

For example:            Il1     O0     5S     2Z            where the characters are:
::::*   capital eye, lowercase ell, the digit one
::::*   capital oh, the digit zero
::::*   the digit five, capital ess
::::*   the digit two, capital zee

Solution:
#include <iostream>
#include <string>
#include <algorithm>
#include <ctime>

const std::string CHR[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
                            "0123456789", "!\"#$%&'()*+,-./:;<=>?@[]^_{|}~" };
const std::string UNS = "O0l1I5S2Z";

std::string createPW( int len, bool safe ) {
    std::string pw;
    char t;
    for( int x = 0; x < len; x += 4 ) {
        for( int y = x; y < x + 4 && y < len; y++ ) {
            do {
                t = CHR[y % 4].at( rand() % CHR[y % 4].size() );
            } while( safe && UNS.find( t ) != UNS.npos );
            pw.append( 1, t );
        }
    }
    std::random_shuffle( pw.begin(), pw.end() );
    return pw;
}
void generate( int len, int count, bool safe ) {
    for( int c = 0; c < count; c++ ) {
        std::cout << createPW( len, safe ) << "\n";
    }
    std::cout << "\n\n";
}
int main( int argc, char* argv[] ){
    if( argv[1][1] == '?' || argc < 5 ) {
        std::cout << "Syntax: PWGEN length count safe seed /?\n"
                     "length:\tthe length of the password(min 4)\n"
                     "count:\thow many passwords should be generated\n"
                     "safe:\t1 will exclude visually similar characters, 0 won't\n"
                     "seed:\tnumber to seed the random generator or 0\n"
                     "/?\tthis text\n\n";
    } else {
        int l = atoi( argv[1] ),
            c = atoi( argv[2] ),
            e = atoi( argv[3] ),
            s = atoi( argv[4] );
        if( l < 4 ) {
            std::cout << "Passwords must be at least 4 characters long.\n\n";
        } else {
            if (s == 0) {
               std::srand( time( NULL ) );
            } else {
               std::srand( unsigned( s ) );
            }
            generate( l, c, e != 0 );
        }
    }
    return 0;
}


Peaceful chess queen armies

In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.

\
|
/

=
=

=
=

/
|
\

/

|

\

|

The goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.

;Task:
# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).
# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
# Display here results for the m=4, n=5 case.

;References:
* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
* A250000 OEIS

Solution:
#include <iostream>
#include <vector>

enum class Piece {
    empty,
    black,
    white
};

typedef std::pair<int, int> position;

bool isAttacking(const position &queen, const position &pos) {
    return queen.first == pos.first
        || queen.second == pos.second
        || abs(queen.first - pos.first) == abs(queen.second - pos.second);
}

bool place(const int m, const int n, std::vector<position> &pBlackQueens, std::vector<position> &pWhiteQueens) {
    if (m == 0) {
        return true;
    }
    bool placingBlack = true;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            auto pos = std::make_pair(i, j);
            for (auto queen : pBlackQueens) {
                if (queen == pos || !placingBlack && isAttacking(queen, pos)) {
                    goto inner;
                }
            }
            for (auto queen : pWhiteQueens) {
                if (queen == pos || placingBlack && isAttacking(queen, pos)) {
                    goto inner;
                }
            }
            if (placingBlack) {
                pBlackQueens.push_back(pos);
                placingBlack = false;
            } else {
                pWhiteQueens.push_back(pos);
                if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
                    return true;
                }
                pBlackQueens.pop_back();
                pWhiteQueens.pop_back();
                placingBlack = true;
            }

        inner: {}
        }
    }
    if (!placingBlack) {
        pBlackQueens.pop_back();
    }
    return false;
}

void printBoard(int n, const std::vector<position> &blackQueens, const std::vector<position> &whiteQueens) {
    std::vector<Piece> board(n * n);
    std::fill(board.begin(), board.end(), Piece::empty);

    for (auto &queen : blackQueens) {
        board[queen.first * n + queen.second] = Piece::black;
    }
    for (auto &queen : whiteQueens) {
        board[queen.first * n + queen.second] = Piece::white;
    }

    for (size_t i = 0; i < board.size(); ++i) {
        if (i != 0 && i % n == 0) {
            std::cout << '\n';
        }
        switch (board[i]) {
        case Piece::black:
            std::cout << "B ";
            break;
        case Piece::white:
            std::cout << "W ";
            break;
        case Piece::empty:
        default:
            int j = i / n;
            int k = i - j * n;
            if (j % 2 == k % 2) {
                std::cout << "x ";
            } else {
                std::cout << "* ";
            }
            break;
        }
    }

    std::cout << "\n\n";
}

int main() {
    std::vector<position> nms = {
        {2, 1}, {3, 1}, {3, 2}, {4, 1}, {4, 2}, {4, 3},
        {5, 1}, {5, 2}, {5, 3}, {5, 4}, {5, 5},
        {6, 1}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6},
        {7, 1}, {7, 2}, {7, 3}, {7, 4}, {7, 5}, {7, 6}, {7, 7},
    };

    for (auto nm : nms) {
        std::cout << nm.second << " black and " << nm.second << " white queens on a " << nm.first << " x " << nm.first << " board:\n";
        std::vector<position> blackQueens, whiteQueens;
        if (place(nm.second, nm.first, blackQueens, whiteQueens)) {
            printBoard(nm.first, blackQueens, whiteQueens);
        } else {
            std::cout << "No solution exists.\n\n";
        }
    }

    return 0;
}


Perfect shuffle

A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:

::: 7 8 9 J Q K-7  8  9  J  Q  K-7 J 8 Q 9 K

When you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:

::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}

'''''The Task'''''

# Write a function that can perform a perfect shuffle on an even-sized list of values.
# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under "Test Cases" below.
#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all "cards" are unique within each deck.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''

::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}

Solution:
#include <iostream>
#include <algorithm>
#include <vector>

int pShuffle( int t ) {
    std::vector<int> v, o, r;

    for( int x = 0; x < t; x++ ) {
        o.push_back( x + 1 );
    }

    r = o;
    int t2 = t / 2 - 1, c = 1;

    while( true ) {
        v = r;
        r.clear();

        for( int x = t2; x > -1; x-- ) {
            r.push_back( v[x + t2 + 1] );
            r.push_back( v[x] );
        }

        std::reverse( r.begin(), r.end() );

        if( std::equal( o.begin(), o.end(), r.begin() ) ) return c;
        c++;
    }
}

int main() {
    int s[] = { 8, 24, 52, 100, 1020, 1024, 10000 };
    for( int x = 0; x < 7; x++ ) {
        std::cout << "Cards count: " << s[x] << ", shuffles required: ";
        std::cout << pShuffle( s[x] ) << ".\n";
    }
    return 0;
}


Perfect totient numbers

Generate and show here, the first twenty Perfect totient numbers.

;Related task:
::*   [[Totient function]]

;Also see:
::*   the OEIS      entry for   perfect totient numbers.
::*   mrob            list of the first 54

Solution:
#include <cassert>
#include <iostream>
#include <vector>

class totient_calculator {
public:
    explicit totient_calculator(int max) : totient_(max + 1) {
        for (int i = 1; i <= max; ++i)
            totient_[i] = i;
        for (int i = 2; i <= max; ++i) {
            if (totient_[i] < i)
                continue;
            for (int j = i; j <= max; j += i)
                totient_[j] -= totient_[j] / i;
        }
    }
    int totient(int n) const {
        assert (n >= 1 && n < totient_.size());
        return totient_[n];
    }
    bool is_prime(int n) const {
        return totient(n) == n - 1;
    }
private:
    std::vector<int> totient_;
};

bool perfect_totient_number(const totient_calculator& tc, int n) {
    int sum = 0;
    for (int m = n; m > 1; ) {
        int t = tc.totient(m);
        sum += t;
        m = t;
    }
    return sum == n;
}

int main() {
    totient_calculator tc(10000);
    int count = 0, n = 1;
    std::cout << "First 20 perfect totient numbers:\n";
    for (; count < 20; ++n) {
        if (perfect_totient_number(tc, n))  {
            if (count > 0)
                std::cout << ' ';
            ++count;
            std::cout << n;
        }
    }
    std::cout << '\n';
    return 0;
}


Permutations by swapping

Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.

Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.

Show the permutations and signs of three items, in order of generation ''here''.

Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.

Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.

;References:
* Steinhaus-Johnson-Trotter algorithm
* Johnson-Trotter Algorithm Listing All Permutations
* Heap's algorithm
* Tintinnalogia

;Related tasks:
*   [[Matrix arithmetic]
*   [[Gray code]]

Solution:
#include <iostream>
#include <vector>

using namespace std;

vector<int> UpTo(int n, int offset = 0)
{
	vector<int> retval(n);
	for (int ii = 0; ii < n; ++ii)
		retval[ii] = ii + offset;
	return retval;
}

struct JohnsonTrotterState_
{
	vector<int> values_;
	vector<int> positions_;	// size is n+1, first element is not used
	vector<bool> directions_;
	int sign_;

	JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}

	int LargestMobile() const	// returns 0 if no mobile integer exists
	{
		for (int r = values_.size(); r > 0; --r)
		{
			const int loc = positions_[r] + (directions_[r] ? 1 : -1);
			if (loc >= 0 && loc < values_.size() && values_[loc] < r)
				return r;
		}
		return 0;
	}

	bool IsComplete() const { return LargestMobile() == 0; }

	void operator++()	// implement Johnson-Trotter algorithm
	{
		const int r = LargestMobile();
		const int rLoc = positions_[r];
		const int lLoc = rLoc + (directions_[r] ? 1 : -1);
		const int l = values_[lLoc];
		// do the swap
		swap(values_[lLoc], values_[rLoc]);
		swap(positions_[l], positions_[r]);
		sign_ = -sign_;
		// change directions
		for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
			*pd = !*pd;
	}
};

int main(void)
{
	JohnsonTrotterState_ state(4);
	do
	{
		for (auto v : state.values_)
			cout << v << " ";
		cout << "\n";
		++state;
	} while (!state.IsComplete());
}


Phrase reversals

Given a string of space separated words containing the following phrase:
  rosetta code phrase reversal

:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.

Show your output here.

Solution:
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
#include <sstream>

int main() {
   std::string s = "rosetta code phrase reversal";
   std::cout << "Input : " << s << '\n'
             << "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ;
   std::istringstream is(s);
   std::vector<std::string> words(std::istream_iterator<std::string>(is), {});
   std::cout << "Each word reversed : " ;
   for(auto w : words)
      std::cout << std::string(w.rbegin(), w.rend()) << ' ';
   std::cout << '\n'
             << "Original word order reversed : " ;
   reverse_copy(words.begin(), words.end(), std::ostream_iterator<std::string>(std::cout, " "));
   std::cout << '\n' ;
}


Pig the dice game

The   game of Pig   is a multiplayer game played with a single six-sided die.   The
object of the game is to reach   '''100'''   points or more.
Play is taken in turns.   On each person's turn that person has the option of either:

:# '''Rolling the dice''':   where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again;   or a roll of   '''1'''   loses the player's total points   ''for that turn''   and their turn finishes with play passing to the next player.
:# '''Holding''':   the player's score for that round is added to their total and becomes safe from the effects of throwing a   '''1'''   (one).   The player's turn finishes with play passing to the next player.

;Task:
Create a program to score for, and simulate dice throws for, a two-person game.

;Related task:
*   [[Pig the dice game/Player]]

Solution:
#include <windows.h>
#include <iostream>
#include <string>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const int PLAYERS = 2, MAX_POINTS = 100;

//--------------------------------------------------------------------------------------------------
class player
{
public:
    player() { reset(); }
    void reset()
    {
	name = "";
	current_score = round_score = 0;
    }
    string getName()             { return name; }
    void setName( string n )     { name = n; }
    int getCurrScore()           { return current_score; }
    void addCurrScore()          { current_score += round_score; }
    int getRoundScore()          { return round_score; }
    void addRoundScore( int rs ) { round_score += rs; }
    void zeroRoundScore()        { round_score = 0; }

private:
    string name;
    int current_score, round_score;
};
//--------------------------------------------------------------------------------------------------
class pigGame
{
public:
    pigGame() { resetPlayers(); }

    void play()
    {
	while( true )
	{
	    system( "cls" );
	    int p = 0;
	    while( true )
	    {
		if( turn( p ) )
		{
		    praise( p );
		    break;
		}

		++p %= PLAYERS;
	    }

	    string r;
	    cout << "Do you want to play again ( y / n )? "; cin >> r;
	    if( r != "Y" && r != "y" ) return;
	    resetPlayers();
	}
    }

private:
    void resetPlayers()
    {
	system( "cls" );
	string n;
	for( int p = 0; p < PLAYERS; p++ )
	{
	    _players[p].reset();
	    cout << "Enter name player " << p + 1 << ": "; cin >> n;
	    _players[p].setName( n );
	}

    }

    void praise( int p )
    {
	system( "cls" );
	cout << "CONGRATULATIONS " << _players[p].getName() << ", you are the winner!" << endl << endl;
	cout << "Final Score" << endl;
	drawScoreboard();
	cout << endl << endl;
    }

    void drawScoreboard()
    {
	for( int p = 0; p < PLAYERS; p++ )
	    cout << _players[p].getName() << ": " << _players[p].getCurrScore() << " points" << endl;
	cout << endl;
    }

    bool turn( int p )
    {
	system( "cls" );
	drawScoreboard();
	_players[p].zeroRoundScore();
	string r;
	int die;
	while( true )
	{
	    cout << _players[p].getName() << ", your round score is: " << _players[p].getRoundScore() << endl;
	    cout << "What do you want to do (H)old or (R)oll? "; cin >> r;
	    if( r == "h" || r == "H" )
	    {
		_players[p].addCurrScore();
		return _players[p].getCurrScore() >= MAX_POINTS;
	    }
	    if( r == "r" || r == "R" )
	    {
		die = rand() % 6 + 1;
		if( die == 1 )
		{
	    	    cout << _players[p].getName() << ", your turn is over." << endl << endl;
		    system( "pause" );
		    return false;
		}
		_players[p].addRoundScore( die );
	    }
	    cout << endl;
	}
	return false;
    }

    player	_players[PLAYERS];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    srand( GetTickCount() );
    pigGame pg;
    pg.play();
    return 0;
}
//--------------------------------------------------------------------------------------------------


Pig the dice game/Player

Create a dice simulator and scorer of [[Pig the dice game]] and add to it the ability to play the game to at least one strategy.
* State here the play strategies involved.
* Show play during a game here.

As a stretch goal:
* Simulate playing the game a number of times with two players of given strategies and report here summary statistics such as, but not restricted to, the influence of going first or which strategy seems stronger.

;Game Rules:
The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach 100 points or more.
Play is taken in turns. On each person's turn that person has the option of either

# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of 1 loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.
# '''Holding''': The player's score for that round is added to their total and becomes safe from the effects of throwing a one. The player's turn finishes with play passing to the next player.

;References
* Pig (dice)
* The Math of Being a Pig and Pigs (extra) - Numberphile videos featuring Ben Sparks.

Solution:
#include <windows.h>
#include <iostream>
#include <string>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const int PLAYERS = 4, MAX_POINTS = 100;

//--------------------------------------------------------------------------------------------------
enum Moves { ROLL, HOLD };

//--------------------------------------------------------------------------------------------------
class player
{
public:
    player()                     { current_score = round_score = 0; }
    void addCurrScore()          { current_score += round_score; }
    int getCurrScore()           { return current_score; }
    int getRoundScore()          { return round_score; }
    void addRoundScore( int rs ) { round_score += rs; }
    void zeroRoundScore()        { round_score = 0; }
    virtual int getMove() = 0;
    virtual ~player() {}

protected:
    int current_score, round_score;
};
//--------------------------------------------------------------------------------------------------
class RAND_Player : public player
{
    virtual int getMove()
    {
	if( round_score + current_score >= MAX_POINTS ) return HOLD;

	if( rand() % 10 < 5 ) return ROLL;
	if( round_score > 0 ) return HOLD;
	return ROLL;
    }
};
//--------------------------------------------------------------------------------------------------
class Q2WIN_Player : public player
{
    virtual int getMove()
    {
	if( round_score + current_score >= MAX_POINTS ) return HOLD;

	int q = MAX_POINTS - current_score;
	if( q < 6 ) return ROLL;
	q /= 4;
	if( round_score < q ) return ROLL;
	return HOLD;
    }
};
//--------------------------------------------------------------------------------------------------
class AL20_Player : public player
{
    virtual int getMove()
    {
	if( round_score + current_score >= MAX_POINTS ) return HOLD;

	if( round_score < 20 ) return ROLL;
	return HOLD;
    }
};
//--------------------------------------------------------------------------------------------------
class AL20T_Player : public player
{
    virtual int getMove()
    {
	if( round_score + current_score >= MAX_POINTS ) return HOLD;

	int d = ( 100 * round_score ) / 20;
	if( round_score < 20 && d < rand() % 100 ) return ROLL;
	return HOLD;
    }
};
//--------------------------------------------------------------------------------------------------
class Auto_pigGame
{
public:
    Auto_pigGame()
    {
	_players[0] = new RAND_Player();
	_players[1] = new Q2WIN_Player();
	_players[2] = new AL20_Player();
        _players[3] = new AL20T_Player();
    }

    ~Auto_pigGame()
    {
	delete _players[0];
	delete _players[1];
	delete _players[2];
        delete _players[3];
    }

    void play()
    {
	int die, p = 0;
	bool endGame = false;

	while( !endGame )
	{
	    switch( _players[p]->getMove() )
	    {
		case ROLL:
	    	    die = rand() % 6 + 1;
		    if( die == 1 )
		    {
			cout << "Player " << p + 1 << " rolled " << die << " - current score: " << _players[p]->getCurrScore() << endl << endl;
			nextTurn( p );
			continue;
		    }
		    _players[p]->addRoundScore( die );
		    cout << "Player " << p + 1 << " rolled " << die << " - round score: " << _players[p]->getRoundScore() << endl;
		break;
		case HOLD:
	    	    _players[p]->addCurrScore();
		    cout << "Player " << p + 1 << " holds - current score: " << _players[p]->getCurrScore() << endl << endl;
		    if( _players[p]->getCurrScore() >= MAX_POINTS )
			endGame = true;
		    else nextTurn( p );

	    }
	}
	showScore();
    }

private:
    void nextTurn( int& p )
    {
	_players[p]->zeroRoundScore();
	++p %= PLAYERS;
    }

    void showScore()
    {
	cout << endl;
	cout << "Player   I (RAND): "  << _players[0]->getCurrScore() << endl;
	cout << "Player  II (Q2WIN): " << _players[1]->getCurrScore() << endl;
        cout << "Player III (AL20): " << _players[2]->getCurrScore() << endl;
	cout << "Player  IV (AL20T): "  << _players[3]->getCurrScore() << endl << endl << endl;

	system( "pause" );
    }

    player*	_players[PLAYERS];
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    srand( GetTickCount() );
    Auto_pigGame pg;
    pg.play();
    return 0;
}
//--------------------------------------------------------------------------------------------------


Plasma effect

The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.

;Task
Create a plasma effect.

;See also
* Computer Graphics Tutorial (lodev.org)
* Plasma (bidouille.org)

Solution:
#include <windows.h>
#include <math.h>
#include <string>

const int BMP_SIZE = 240, MY_TIMER = 987654;

class myBitmap {
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap() {
        DeleteObject( pen ); DeleteObject( brush );
        DeleteDC( hdc ); DeleteObject( bmp );
    }
    bool create( int w, int h ) {
        BITMAPINFO bi;
        ZeroMemory( &bi, sizeof( bi ) );
        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
        bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
        bi.bmiHeader.biCompression = BI_RGB;
        bi.bmiHeader.biPlanes      = 1;
        bi.bmiHeader.biWidth       =  w;
        bi.bmiHeader.biHeight      = -h;

        HDC dc = GetDC( GetConsoleWindow() );
        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
        if( !bmp ) return false;

        hdc = CreateCompatibleDC( dc );
        SelectObject( hdc, bmp );
        ReleaseDC( GetConsoleWindow(), dc );

        width = w; height = h;
        return true;
    }
    void clear( BYTE clr = 0 ) {
        memset( pBits, clr, width * height * sizeof( DWORD ) );
    }
    void setBrushColor( DWORD bClr ) {
        if( brush ) DeleteObject( brush );
        brush = CreateSolidBrush( bClr );
        SelectObject( hdc, brush );
    }
    void setPenColor( DWORD c ) {
        clr = c; createPen();
    }
    void setPenWidth( int w ) {
        wid = w; createPen();
    }
    void saveBitmap( std::string path ) {
        BITMAPFILEHEADER fileheader;
        BITMAPINFO       infoheader;
        BITMAP           bitmap;
        DWORD            wb;

        GetObject( bmp, sizeof( bitmap ), &bitmap );
        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];

        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

        infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
        infoheader.bmiHeader.biCompression = BI_RGB;
        infoheader.bmiHeader.biPlanes = 1;
        infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
        infoheader.bmiHeader.biHeight = bitmap.bmHeight;
        infoheader.bmiHeader.biWidth = bitmap.bmWidth;
        infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

        fileheader.bfType    = 0x4D42;
        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
        CloseHandle( file );

        delete [] dwpBits;
    }
    HDC getDC() const     { return hdc; }
    DWORD* bits()          { return ( DWORD* )pBits; }
private:
    void createPen() {
        if( pen ) DeleteObject( pen );
        pen = CreatePen( PS_SOLID, wid, clr );
        SelectObject( hdc, pen );
    }
    HBITMAP bmp; HDC    hdc;
    HPEN    pen; HBRUSH brush;
    void    *pBits; int width, height, wid;
    DWORD    clr;
};
class plasma
{
public:
    plasma() {
        currentTime = 0; _WD = BMP_SIZE >> 1; _WV = BMP_SIZE << 1;
        _bmp.create( BMP_SIZE, BMP_SIZE ); _bmp.clear();
        plasma1 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
        plasma2 = new BYTE[BMP_SIZE * BMP_SIZE * 4];
        int i, j, dst = 0;
        double temp;
        for( j = 0; j < BMP_SIZE * 2; j++ ) {
            for( i = 0; i < BMP_SIZE * 2; i++ ) {
                plasma1[dst] = ( BYTE )( 128.0 + 127.0 * ( cos( ( double )hypot( BMP_SIZE - j, BMP_SIZE - i ) / 64.0 ) ) );
                plasma2[dst] = ( BYTE )( ( sin( ( sqrt( 128.0 + ( BMP_SIZE - i ) * ( BMP_SIZE - i ) +
                               ( BMP_SIZE - j ) * ( BMP_SIZE - j ) ) - 4.0 ) / 32.0 ) + 1 ) * 90.0 );
                dst++;
            }
        }
    }
    void update() {
        DWORD dst;
        BYTE a, c1,c2, c3;
        currentTime += ( double )( rand() % 2 + 1 );

        int x1 = _WD + ( int )( ( _WD - 1 ) * sin( currentTime  / 137 ) ),
            x2 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime /  75 ) ),
            x3 = _WD + ( int )( ( _WD - 1 ) * sin( -currentTime / 125 ) ),
            y1 = _WD + ( int )( ( _WD - 1 ) * cos( currentTime  / 123 ) ),
            y2 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime /  85 ) ),
            y3 = _WD + ( int )( ( _WD - 1 ) * cos( -currentTime / 108 ) );

        int src1 = y1 * _WV + x1, src2 = y2 * _WV + x2, src3 = y3 * _WV + x3;

        DWORD* bits = _bmp.bits();
        for( int j = 0; j < BMP_SIZE; j++ ) {
            dst = j * BMP_SIZE;
            for( int i= 0; i < BMP_SIZE; i++ ) {
                a = plasma2[src1] + plasma1[src2] + plasma2[src3];
                c1 = a << 1; c2 = a << 2; c3 = a << 3;
                bits[dst + i] = RGB( c1, c2, c3 );
                src1++; src2++; src3++;
            }
            src1 += BMP_SIZE; src2 += BMP_SIZE; src3 += BMP_SIZE;
        }
        draw();
    }
    void setHWND( HWND hwnd ) { _hwnd = hwnd; }
private:
    void draw() {
        HDC dc = _bmp.getDC(), wdc = GetDC( _hwnd );
        BitBlt( wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );
        ReleaseDC( _hwnd, wdc );
    }
    myBitmap _bmp; HWND _hwnd; float _ang;
    BYTE *plasma1, *plasma2;
    double currentTime; int _WD, _WV;
};
class wnd
{
public:
    wnd() { _inst = this; }
    int wnd::Run( HINSTANCE hInst ) {
        _hInst = hInst; _hwnd = InitAll();
        SetTimer( _hwnd, MY_TIMER, 15, NULL );
        _plasma.setHWND( _hwnd );
        ShowWindow( _hwnd, SW_SHOW );
        UpdateWindow( _hwnd );
        MSG msg;
        ZeroMemory( &msg, sizeof( msg ) );
        while( msg.message != WM_QUIT ) {
            if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 ) {
                TranslateMessage( &msg );
                DispatchMessage( &msg );
            }
        }
        return UnregisterClass( "_MY_PLASMA_", _hInst );
    }
private:
    void wnd::doPaint( HDC dc ) { _plasma.update(); }
    void wnd::doTimer()         { _plasma.update(); }
    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) {
        switch( msg ) {
            case WM_PAINT: {
                    PAINTSTRUCT ps;
                    _inst->doPaint( BeginPaint( hWnd, &ps ) );
                    EndPaint( hWnd, &ps );
                    return 0;
                }
            case WM_DESTROY: PostQuitMessage( 0 ); break;
            case WM_TIMER: _inst->doTimer(); break;
            default: return DefWindowProc( hWnd, msg, wParam, lParam );
        }
        return 0;
    }
    HWND InitAll() {
        WNDCLASSEX wcex;
        ZeroMemory( &wcex, sizeof( wcex ) );
        wcex.cbSize        = sizeof( WNDCLASSEX );
        wcex.style         = CS_HREDRAW | CS_VREDRAW;
        wcex.lpfnWndProc   = ( WNDPROC )WndProc;
        wcex.hInstance     = _hInst;
        wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
        wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
        wcex.lpszClassName = "_MY_PLASMA_";

        RegisterClassEx( &wcex );

        RECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };
        AdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );
        int w = rc.right - rc.left, h = rc.bottom - rc.top;
        return CreateWindow( "_MY_PLASMA_", ".: Plasma -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );
    }
    static wnd* _inst; HINSTANCE _hInst; HWND _hwnd; plasma _plasma;
};
wnd* wnd::_inst = 0;
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) {
    wnd myWnd;
    return myWnd.Run( hInstance );
}


Playfair cipher

Implement a  Playfair cipher for encryption and decryption.

The user must be able to choose   '''J'''  =  '''I'''      or   no   '''Q'''   in the alphabet.

The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.

;Output example:
                 HI DE TH EG OL DI NT HE TR EX ES TU MP

Solution:
#include <iostream>
#include <string>

using namespace std;

class playfair
{
public:
    void doIt( string k, string t, bool ij, bool e )
    {
	createGrid( k, ij ); getTextReady( t, ij, e );
	if( e ) doIt( 1 ); else doIt( -1 );
	display();
    }

private:
    void doIt( int dir )
    {
	int a, b, c, d; string ntxt;
	for( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )
	{
	    if( getCharPos( *ti++, a, b ) )
		if( getCharPos( *ti, c, d ) )
		{
		    if( a == c )     { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }
		    else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }
		    else             { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }
		}
	}
	_txt = ntxt;
    }

    void display()
    {
	cout << "\n\n OUTPUT:\n=========" << endl;
	string::iterator si = _txt.begin(); int cnt = 0;
	while( si != _txt.end() )
	{
	    cout << *si; si++; cout << *si << " "; si++;
	    if( ++cnt >= 26 ) cout << endl, cnt = 0;
	}
	cout << endl << endl;
    }

    char getChar( int a, int b )
    {
	return _m[ (b + 5) % 5 ][ (a + 5) % 5 ];
    }

    bool getCharPos( char l, int &a, int &b )
    {
	for( int y = 0; y < 5; y++ )
	    for( int x = 0; x < 5; x++ )
		if( _m[y][x] == l )
		{ a = x; b = y; return true; }

	return false;
    }

    void getTextReady( string t, bool ij, bool e )
    {
	for( string::iterator si = t.begin(); si != t.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( *si == 'J' && ij ) *si = 'I';
	    else if( *si == 'Q' && !ij ) continue;
	    _txt += *si;
	}
	if( e )
	{
	    string ntxt = ""; size_t len = _txt.length();
	    for( size_t x = 0; x < len; x += 2 )
	    {
		ntxt += _txt[x];
		if( x + 1 < len )
		{
		    if( _txt[x] == _txt[x + 1] ) ntxt += 'X';
		    ntxt += _txt[x + 1];
		}
	    }
	    _txt = ntxt;
	}
	if( _txt.length() & 1 ) _txt += 'X';
    }

    void createGrid( string k, bool ij )
    {
	if( k.length() < 1 ) k = "KEYWORD";
	k += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; string nk = "";
	for( string::iterator si = k.begin(); si != k.end(); si++ )
	{
	    *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;
	    if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;
	    if( nk.find( *si ) == -1 ) nk += *si;
	}
	copy( nk.begin(), nk.end(), &_m[0][0] );
    }

    string _txt; char _m[5][5];
};

int main( int argc, char* argv[] )
{
    string key, i, txt; bool ij, e;
    cout << "(E)ncode or (D)ecode? "; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );
    cout << "Enter a en/decryption key: "; getline( cin, key );
    cout << "I <-> J (Y/N): "; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );
    cout << "Enter the text: "; getline( cin, txt );
    playfair pf; pf.doIt( key, txt, ij, e ); return system( "pause" );
}


Plot coordinate pairs

Plot a function represented as     x,  y     numerical arrays.

Post the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):
       x = {0,   1,    2,    3,    4,    5,     6,     7,     8,     9};
       y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};

This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].

Solution:
#include <windows.h>
#include <string>
#include <vector>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
const int HSTEP = 46, MWID = 40, MHEI = 471;
const float VSTEP = 2.3f;

//--------------------------------------------------------------------------------------------------
class vector2
{
public:
    vector2() { x = y = 0; }
    vector2( float a, float b )  { x = a; y = b; }
    void set( float a, float b ) { x = a; y = b; }
    float x, y;
};
//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteObject( brush );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO    bi;
	ZeroMemory( &bi, sizeof( bi ) );
	bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes      = 1;
	bi.bmiHeader.biWidth       =  w;
	bi.bmiHeader.biHeight      = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;
	return true;
    }

    void clear( BYTE clr = 0 )
    {
	memset( pBits, clr, width * height * sizeof( DWORD ) );
    }

    void setBrushColor( DWORD bClr )
    {
	if( brush ) DeleteObject( brush );
	brush = CreateSolidBrush( bClr );
	SelectObject( hdc, brush );
    }

    void setPenColor( DWORD c ) { clr = c; createPen(); }

    void setPenWidth( int w )   { wid = w; createPen(); }

    void saveBitmap( string path )
    {
	BITMAPFILEHEADER fileheader;
	BITMAPINFO       infoheader;
	BITMAP           bitmap;
	DWORD            wb;

	GetObject( bmp, sizeof( bitmap ), &bitmap );
	DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];

	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }

private:
    void createPen()
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, wid, clr );
	SelectObject( hdc, pen );
    }

    HBITMAP bmp;
    HDC     hdc;
    HPEN    pen;
    HBRUSH  brush;
    void    *pBits;
    int     width, height, wid;
    DWORD   clr;
};
//--------------------------------------------------------------------------------------------------
class plot
{
public:
    plot() { bmp.create( 512, 512 ); }

    void draw( vector<vector2>* pairs )
    {
	bmp.clear( 0xff );
	drawGraph( pairs );
	plotIt( pairs );

	HDC dc = GetDC( GetConsoleWindow() );
	BitBlt( dc, 0, 30, 512, 512, bmp.getDC(), 0, 0, SRCCOPY );
	ReleaseDC( GetConsoleWindow(), dc );
	//bmp.saveBitmap( "f:\\rc\\plot.bmp" );
    }

private:
    void drawGraph( vector<vector2>* pairs )
    {
	HDC dc = bmp.getDC();
	bmp.setPenColor( RGB( 240, 240, 240 ) );
	DWORD b = 11, c = 40, x;
	RECT rc; char txt[8];

	for( x = 0; x < pairs->size(); x++ )
	{
	    MoveToEx( dc, 40, b, NULL ); LineTo( dc, 500, b );
	    MoveToEx( dc, c, 11, NULL ); LineTo( dc, c, 471 );

	    wsprintf( txt, "%d", ( pairs->size() - x ) * 20 );
	    SetRect( &rc, 0, b - 9, 36, b + 11 );
	    DrawText( dc, txt, lstrlen( txt ), &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );

	    wsprintf( txt, "%d", x );
	    SetRect( &rc, c - 8, 472, c + 8, 492 );
	    DrawText( dc, txt, lstrlen( txt ), &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE );

	    c += 46; b += 46;
	}

	SetRect( &rc, 0, b - 9, 36, b + 11 );
	DrawText( dc, "0", 1, &rc, DT_RIGHT | DT_VCENTER | DT_SINGLELINE );

	bmp.setPenColor( 0 ); bmp.setPenWidth( 3 );
	MoveToEx( dc, 40, 11, NULL ); LineTo( dc, 40, 471 );
	MoveToEx( dc, 40, 471, NULL ); LineTo( dc, 500, 471 );
    }

    void plotIt( vector<vector2>* pairs )
    {
	HDC dc = bmp.getDC();
	HBRUSH br = CreateSolidBrush( 255 );
	RECT rc;

	bmp.setPenColor( 255 ); bmp.setPenWidth( 2 );
	vector<vector2>::iterator it = pairs->begin();
	int a = MWID + HSTEP * static_cast<int>( ( *it ).x ), b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
	MoveToEx( dc, a, b, NULL );
	SetRect( &rc, a - 3, b - 3, a + 3, b + 3 ); FillRect( dc, &rc, br );

	it++;
	for( ; it < pairs->end(); it++ )
	{
	    a = MWID + HSTEP * static_cast<int>( ( *it ).x );
	    b = MHEI - static_cast<int>( VSTEP * ( *it ).y );
	    SetRect( &rc, a - 3, b - 3, a + 3, b + 3 );
	    FillRect( dc, &rc, br ); LineTo( dc, a, b );
	}

	DeleteObject( br );
    }

    myBitmap bmp;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );
    plot pt;
    vector<vector2> pairs;
    pairs.push_back( vector2( 0, 2.7f ) ); pairs.push_back( vector2( 1, 2.8f ) );
    pairs.push_back( vector2( 2.0f, 31.4f ) ); pairs.push_back( vector2( 3.0f, 38.1f ) );
    pairs.push_back( vector2( 4.0f, 58.0f ) ); pairs.push_back( vector2( 5.0f, 76.2f ) );
    pairs.push_back( vector2( 6.0f, 100.5f ) ); pairs.push_back( vector2( 7.0f, 130.0f ) );
    pairs.push_back( vector2( 8.0f, 149.3f ) ); pairs.push_back( vector2( 9.0f, 180.0f ) );

    pt.draw( &pairs );
    system( "pause" );

    return 0;
}
//--------------------------------------------------------------------------------------------------


Poker hand analyser

Create a program to parse a single five card poker hand and rank it according to this list of poker hands.

A poker hand is specified as a space separated list of five playing cards.

Each input card has two characters indicating face and suit.

;Example:
::::'''2d'''       (two of diamonds).

Faces are:    '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''

Suits are:    '''h''' (hearts),   '''d''' (diamonds),   '''c''' (clubs),   and   '''s''' (spades),   or
alternatively,   the unicode card-suit characters:

Duplicate cards are illegal.

The program should analyze a single hand and produce one of the following outputs:
  straight-flush
  four-of-a-kind
  full-house
  flush
  straight
  three-of-a-kind
  two-pair
  one-pair
  high-card
  invalid

;Examples:
    2 2 2 k q:   three-of-a-kind
    2 5 7 8 9:   high-card
    a 2 3 4 5:   straight
    2 3 2 3 3:   full-house
    2 7 2 3 3:   two-pair
    2 7 7 7 7:   four-of-a-kind
    10 j q k a:  straight-flush
    4 4 k 5 10:  one-pair
    q 10 7 6 q:  invalid

The programs output for the above examples should be displayed here on this page.

;Extra credit:
# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
# allow two jokers
::* use the symbol   '''joker'''
::* duplicates would be allowed (for jokers only)
::* five-of-a-kind would then be the highest hand

;More extra credit examples:
    joker  2  2  k  q:     three-of-a-kind
    joker  5  7  8  9:     straight
    joker  2  3  4  5:     straight
    joker  3  2  3  3:     four-of-a-kind
    joker  7  2  3  3:     three-of-a-kind
    joker  7  7  7  7:     five-of-a-kind
    joker  j  q  k  A:     straight-flush
    joker  4  k  5 10:     one-pair
    joker  k  7  6  4:     flush
    joker  2  joker  4  5:  straight
    joker  Q  joker  A 10:  straight
    joker  Q  joker  A 10:  straight-flush
    joker  2  2  joker  q:  four-of-a-kind

;Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards_for_FreeCell]]
* [[War Card_Game]]
* [[Go Fish]]

Solution:
#include <iostream>
#include <sstream>
#include <algorithm>
#include <vector>

using namespace std;

class poker
{
public:
    poker() { face = "A23456789TJQK"; suit = "SHCD"; }
    string analyze( string h )
    {
	memset( faceCnt, 0, 13 ); memset( suitCnt, 0, 4 ); vector<string> hand;
	transform( h.begin(), h.end(), h.begin(), toupper ); istringstream i( h );
	copy( istream_iterator<string>( i ), istream_iterator<string>(), back_inserter<vector<string> >( hand ) );
	if( hand.size() != 5 ) return "invalid hand."; vector<string>::iterator it = hand.begin();
	sort( it, hand.end() ); if( hand.end() != adjacent_find( it, hand.end() ) ) return "invalid hand.";
	while( it != hand.end() )
	{
	    if( ( *it ).length() != 2 ) return "invalid hand.";
	    int n = face.find( ( *it ).at( 0 ) ), l = suit.find( ( *it ).at( 1 ) );
	    if( n < 0 || l < 0 ) return "invalid hand.";
	    faceCnt[n]++; suitCnt[l]++; it++;
	}
	cout << h << ": "; return analyzeHand();
    }
private:
    string analyzeHand()
    {
	bool p1 = false, p2 = false, t = false, f = false, fl = false, st = false;
	for( int x = 0; x < 13; x++ )
	    switch( faceCnt[x] )
	    {
		case 2: if( p1 ) p2 = true; else p1 = true; break;
		case 3: t = true; break;
		case 4: f = true;
	    }
	for( int x = 0; x < 4; x++ )if( suitCnt[x] == 5 ){ fl = true; break; }

	if( !p1 && !p2 && !t && !f )
        {
	    int s = 0;
	    for( int x = 0; x < 13; x++ )
	    {
		if( faceCnt[x] ) s++; else s = 0;
		if( s == 5 ) break;
	    }
	    st = ( s == 5 ) || ( s == 4 && faceCnt[0] && !faceCnt[1] );
	}

	if( st && fl ) return "straight-flush";
	else if( f ) return "four-of-a-kind";
	else if( p1 && t ) return "full-house";
	else if( fl ) return "flush";
	else if( st ) return "straight";
	else if( t ) return "three-of-a-kind";
	else if( p1 && p2 ) return "two-pair";
	else if( p1 ) return "one-pair";
        return "high-card";
    }
    string face, suit;
    unsigned char faceCnt[13], suitCnt[4];
};

int main( int argc, char* argv[] )
{
    poker p;
    cout << p.analyze( "2h 2d 2s ks qd" ) << endl; cout << p.analyze( "2h 5h 7d 8s 9d" ) << endl;
    cout << p.analyze( "ah 2d 3s 4s 5s" ) << endl; cout << p.analyze( "2h 3h 2d 3s 3d" ) << endl;
    cout << p.analyze( "2h 7h 2d 3s 3d" ) << endl; cout << p.analyze( "2h 7h 7d 7s 7c" ) << endl;
    cout << p.analyze( "th jh qh kh ah" ) << endl; cout << p.analyze( "4h 4c kc 5d tc" ) << endl;
    cout << p.analyze( "qc tc 7c 6c 4c" ) << endl << endl; return system( "pause" );
}


Polyspiral

A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle.

;Task
Animate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.

If animation is not practical in your programming environment, you may show a single frame instead.

;Pseudo code

    set incr to 0.0

    // animation loop
    WHILE true

        incr = (incr + 0.05) MOD 360
        x = width / 2
        y = height / 2
        length = 5
        angle = incr

        // spiral loop
        FOR 1 TO 150
            drawline
            change direction by angle
            length = length + 3
            angle = (angle + incr) MOD 360
        ENDFOR

Solution:
#include <windows.h>
#include <sstream>
#include <ctime>

const float PI = 3.1415926536f, TWO_PI = 2.f * PI;
class vector2
{
public:
    vector2( float a = 0, float b = 0 ) { set( a, b ); }
    void set( float a, float b ) { x = a; y = b; }
    void rotate( float r ) {
        float _x = x, _y = y,
               s = sinf( r ), c = cosf( r ),
               a = _x * c - _y * s, b = _x * s + _y * c;
        x = a; y = b;
    }
    vector2 add( const vector2& v ) {
        x += v.x; y += v.y;
        return *this;
    }
    float x, y;
};
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap(){
        DeleteObject( pen );
        DeleteObject( brush );
        DeleteDC( hdc );
        DeleteObject( bmp );
    }
    bool create( int w, int h ){
        BITMAPINFO    bi;
        ZeroMemory( &bi, sizeof( bi ) );
        bi.bmiHeader.biSize        = sizeof( bi.bmiHeader );
        bi.bmiHeader.biBitCount    = sizeof( DWORD ) * 8;
        bi.bmiHeader.biCompression = BI_RGB;
        bi.bmiHeader.biPlanes      = 1;
        bi.bmiHeader.biWidth       =  w;
        bi.bmiHeader.biHeight      = -h;

        HDC dc = GetDC( GetConsoleWindow() );
        bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
        if( !bmp ) return false;

        hdc = CreateCompatibleDC( dc );
        SelectObject( hdc, bmp );
        ReleaseDC( GetConsoleWindow(), dc );

        width = w; height = h;
        return true;
    }
    void clear( BYTE clr = 0 ){
        memset( pBits, clr, width * height * sizeof( DWORD ) );
    }
    void setBrushColor( DWORD bClr ){
        if( brush ) DeleteObject( brush );
        brush = CreateSolidBrush( bClr );
        SelectObject( hdc, brush );
    }
    void setPenColor( DWORD c ){
        clr = c; createPen();
    }
    void setPenWidth( int w ){
        wid = w; createPen();
    }
    void saveBitmap( std::string path ){
        BITMAPFILEHEADER fileheader;
        BITMAPINFO       infoheader;
        BITMAP           bitmap;
        DWORD            wb;

        GetObject( bmp, sizeof( bitmap ), &bitmap );
        DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
        ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
        ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
        ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

        infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
        infoheader.bmiHeader.biCompression = BI_RGB;
        infoheader.bmiHeader.biPlanes = 1;
        infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
        infoheader.bmiHeader.biHeight = bitmap.bmHeight;
        infoheader.bmiHeader.biWidth = bitmap.bmWidth;
        infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

        fileheader.bfType    = 0x4D42;
        fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
        fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

        GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

        HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
        WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
        WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
        WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
        CloseHandle( file );

        delete [] dwpBits;
    }
    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }
private:
    void createPen(){
        if( pen ) DeleteObject( pen );
        pen = CreatePen( PS_SOLID, wid, clr );
        SelectObject( hdc, pen );
    }
    HBITMAP bmp; HDC hdc;
    HPEN pen; HBRUSH brush;
    void *pBits; int width, height, wid;
    DWORD clr;
};
int main( int argc, char* argv[] ) {
    srand( unsigned( time( 0 ) ) );
    myBitmap bmp;
    bmp.create( 600, 600 ); bmp.clear();
    HDC dc = bmp.getDC();
    float fs = ( TWO_PI ) / 100.f;
    int index = 0;
    std::string a = "f://users//images//test", b;
    float ang, len;
    vector2 p1, p2;

    for( float step = 0.1f; step < 5.1f; step += .05f ) {
        ang = 0; len = 2;
        p1.set( 300, 300 );
        bmp.setPenColor( RGB( rand() % 50 + 200, rand() % 300 + 220, rand() % 50 + 200 ) );
        for( float xx = 0; xx < TWO_PI; xx += fs ) {
            MoveToEx( dc, (int)p1.x, (int)p1.y, NULL );
            p2.set( 0, len ); p2.rotate( ang ); p2.add( p1 );
            LineTo( dc, (int)p2.x, (int)p2.y );
            p1 = p2; ang += step; len += step;
        }
        std::ostringstream ss; ss << index++;
        b = a + ss.str() + ".bmp";
        bmp.saveBitmap( b );
        bmp.clear();
    }
    return 0;
}


Population count

The   ''population count''   is the number of   '''1'''s   (ones)   in the binary representation of a non-negative integer.

''Population count''   is also known as:
::::*   ''pop count''
::::*   ''popcount''
::::*   ''sideways sum''
::::*   ''bit summation''
::::*   ''Hamming weight''

For example,   '''5'''   (which is   '''101'''   in binary)   has a population count of   '''2'''.

''Evil numbers''   are non-negative integers  that have an   ''even''   population count.

''Odious numbers''      are  positive integers that have an    ''odd''   population count.

;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with   '''0'''   (zero indexed).
:* display the   ''pop count''   of the   1st   thirty powers of   '''3'''       ('''30''',   '''31''',   '''32''',   '''33''',   '''34''',      '''329''').
:* display the   1st   thirty     ''evil''        numbers.
:* display the   1st   thirty          ''odious''           numbers.
* display each list of integers on one line   (which may or may not include a title),   each set of integers being shown should be properly identified.

;See also
* The On-Line Encyclopedia of Integer Sequences:   A000120 population count.
* The On-Line Encyclopedia of Integer Sequences:   A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences:   A001969 evil numbers.

Solution:
#include <iostream>
#include <bitset>
#include <climits>

size_t popcount(unsigned long long n) {
  return std::bitset<CHAR_BIT * sizeof n>(n).count();
}

int main() {
  {
    unsigned long long n = 1;
    for (int i = 0; i < 30; i++) {
      std::cout << popcount(n) << " ";
      n *= 3;
    }
    std::cout << std::endl;
  }

  int od[30];
  int ne = 0, no = 0;
  std::cout << "evil  : ";
  for (int n = 0; ne+no < 60; n++) {
    if ((popcount(n) & 1) == 0) {
      if (ne < 30) {
	std::cout << n << " ";
	ne++;
      }
    } else {
      if (no < 30) {
	od[no++] = n;
      }
    }
  }
  std::cout << std::endl;
  std::cout << "odious: ";
  for (int i = 0; i < 30; i++) {
    std::cout << od[i] << " ";
  }
  std::cout << std::endl;

  return 0;
}


Prime triangle

You will require a function f which when given an integer S will return a list of the arrangements of the integers 1 to S such that g1=1 gS=S and generally for n=1 to n=S-1 gn+gn+1 is prime. S=1 is undefined. For S=2 to S=20 print f(S) to form a triangle. Then again for S=2 to S=20 print the number of possible arrangements of 1 to S meeting these requirements.

;See also
:* OEIS:A036440

Solution:
#include <cassert>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

bool is_prime(unsigned int n) {
    assert(n > 0 && n < 64);
    return (1ULL << n) & 0x28208a20a08a28ac;
}

template <typename Iterator>
bool prime_triangle_row(Iterator begin, Iterator end) {
    if (std::distance(begin, end) == 2)
        return is_prime(*begin + *(begin + 1));
    for (auto i = begin + 1; i + 1 != end; ++i) {
        if (is_prime(*begin + *i)) {
            std::iter_swap(i, begin + 1);
            if (prime_triangle_row(begin + 1, end))
                return true;
            std::iter_swap(i, begin + 1);
        }
    }
    return false;
}

template <typename Iterator>
void prime_triangle_count(Iterator begin, Iterator end, int& count) {
    if (std::distance(begin, end) == 2) {
        if (is_prime(*begin + *(begin + 1)))
            ++count;
        return;
    }
    for (auto i = begin + 1; i + 1 != end; ++i) {
        if (is_prime(*begin + *i)) {
            std::iter_swap(i, begin + 1);
            prime_triangle_count(begin + 1, end, count);
            std::iter_swap(i, begin + 1);
        }
    }
}

template <typename Iterator>
void print(Iterator begin, Iterator end) {
    if (begin == end)
        return;
    auto i = begin;
    std::cout << std::setw(2) << *i++;
    for (; i != end; ++i)
        std::cout << ' ' << std::setw(2) << *i;
    std::cout << '\n';
}

int main() {
    auto start = std::chrono::high_resolution_clock::now();
    for (unsigned int n = 2; n < 21; ++n) {
        std::vector<unsigned int> v(n);
        std::iota(v.begin(), v.end(), 1);
        if (prime_triangle_row(v.begin(), v.end()))
            print(v.begin(), v.end());
    }
    std::cout << '\n';
    for (unsigned int n = 2; n < 21; ++n) {
        std::vector<unsigned int> v(n);
        std::iota(v.begin(), v.end(), 1);
        int count = 0;
        prime_triangle_count(v.begin(), v.end(), count);
        if (n > 2)
            std::cout << ' ';
        std::cout << count;
    }
    std::cout << '\n';
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> duration(end - start);
    std::cout << "\nElapsed time: " << duration.count() << " seconds\n";
}