Archimedean spiral

The Archimedean spiral is a spiral named after the Greek mathematician Archimedes.

An Archimedean spiral can be described by the equation:

:\, r=a+b\theta

with real numbers ''a'' and ''b''.

;Task
Draw an Archimedean spiral.

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

const int BMP_SIZE = 600;

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;
};
class spiral {
public:
    spiral() {
        bmp.create( BMP_SIZE, BMP_SIZE );
    }
    void draw( int c, int s ) {
        double a = .2, b = .3, r, x, y;
        int w = BMP_SIZE >> 1;
        HDC dc = bmp.getDC();
        for( double d = 0; d < c * 6.28318530718; d += .002 ) {
            r = a + b * d; x = r * cos( d ); y = r * sin( d );
            SetPixel( dc, ( int )( s * x + w ), ( int )( s * y + w ), 255 );
        }
        // saves the bitmap
        bmp.saveBitmap( "./spiral.bmp" );
    }
private:
    myBitmap bmp;
};
int main(int argc, char* argv[]) {
    spiral s; s.draw( 16, 8 ); return 0;
}


Arena storage pool

Dynamically allocated objects take their memory from a [[heap]].

The memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].

Often a call to allocator is denoted as
P := new T
where   '''T'''   is the type of an allocated object,   and   '''P'''   is a [[reference]] to the object.

The storage pool chosen by the allocator can be determined by either:
* the object type   '''T'''
* the type of pointer   '''P'''

In the former case objects can be allocated only in one storage pool.

In the latter case objects of the type can be allocated in any storage pool or on the [[stack]].

;Task:
The task is to show how allocators and user-defined storage pools are supported by the language.

In particular:
# define an arena storage pool.   An arena is a pool in which objects are allocated individually, but freed by groups.
# allocate some objects (e.g., integers) in the pool.

Explain what controls the storage pool choice in the language.

Solution:
#include <cstdlib>
#include <cassert>
#include <new>

// This class basically provides a global stack of pools; it is not thread-safe, and pools must be destructed in reverse order of construction
// (you definitely want something better in production use :-))
class Pool
{
public:
  Pool(std::size_type sz);
  ~Pool();
  static Pool& current() { return *cur; }
  void* allocate(std::size_type sz, std::size_t alignment);
private:
  char* memory; // char* instead of void* enables pointer arithmetic
  char* free;
  char* end;
  Pool* prev;
  static Pool* cur;

  // prohibit copying
  Pool(Pool const&); // not implemented
  Pool& operator=(Pool const&); // not implemented
};

Pool* pool::cur = 0;

Pool::Pool(std::size_type size):
  memory(static_cast<char*>(::operator new(size))),
  free(memory),
  end(memory + size))
{
  prev = cur;
  cur = this;
}

Pool::~Pool()
{
  ::operator delete(memory);
  cur = prev;
}

void* Pool::allocate(std::size_t size, std::size_t alignment)
{
  char* start = free;

  // align the pointer
  std::size_t extra = (start - memory) % aligment;
  if (extra != 0)
  {
    extra = alignment - extra;
  }

  // test if we can still allocate that much memory
  if (end - free < size + extra)
    throw std::bad_alloc();

  // the free memory now starts after the newly allocated object
  free = start + size + extra;
  return start;
}

// this is just a simple C-like struct, except that it uses a specific allocation/deallocation function.
struct X
{
  int member;
  void* operator new(std::size_t);
  void operator delete(void*) {} // don't deallocate memory for single objects
};

void* X::operator new(std::size_t size)
{
  // unfortunately C++ doesn't offer a portable way to find out alignment
  // however, using the size as alignment is always safe (although usually wasteful)
  return Pool::current().allocate(size, size);
}

// Example program
int main()
{
  Pool my_pool(3*sizeof(X));
  X* p1 = new X; // uses the allocator function defined above
  X* p2 = new X;
  X* p3 = new X;
  delete p3; // doesn't really deallocate the memory because operator delete has an empty body

  try
  {
    X* p4 = new X; // should fail
    assert(false);
  }
  catch(...)
  {
  }

  X* p5 = new X[10]; // uses global array allocation routine because we didn't provide operator new[] and operator delete[]
  delete[] p5; // global array deallocation

  Pool* my_second_pool(1000); // a large pool
  X* p6 = new X; // allocate a new object from that pool
  X* p7 = new X;
  delete my_second_pool // also deallocates the memory for p6 and p7

} // Here my_pool goes out of scope, deallocating the memory for p1, p2 and p3


Arithmetic-geometric mean

{{wikipedia|Arithmetic-geometric mean}}

;Task:
Write a function to compute the arithmetic-geometric mean of two numbers.

The arithmetic-geometric mean of two numbers can be (usefully) denoted as \mathrm{agm}(a,g), and is equal to the limit of the sequence:
: a_0 = a; \qquad g_0 = g
: a_{n+1} = \tfrac{1}{2}(a_n + g_n); \quad g_{n+1} = \sqrt{a_n g_n}.
Since the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.

Demonstrate the function by calculating:
:\mathrm{agm}(1,1/\sqrt{2})

;Also see:
*   mathworld.wolfram.com/Arithmetic-Geometric Mean

Solution:
#include<bits/stdc++.h>
using namespace std;
#define _cin	ios_base::sync_with_stdio(0);	cin.tie(0);
#define rep(a, b)	for(ll i =a;i<=b;++i)

double agm(double a, double g)		//ARITHMETIC GEOMETRIC MEAN
{	double epsilon = 1.0E-16,a1,g1;
	if(a*g<0.0)
	{	cout<<"Couldn't find arithmetic-geometric mean of these numbers\n";
		exit(1);
	}
	while(fabs(a-g)>epsilon)
	{	a1 = (a+g)/2.0;
		g1 = sqrt(a*g);
		a = a1;
		g = g1;
	}
	return a;
}

int main()
{	_cin;    //fast input-output
	double x, y;
	cout<<"Enter X and Y: ";	//Enter two numbers
	cin>>x>>y;
	cout<<"\nThe Arithmetic-Geometric Mean of "<<x<<" and "<<y<<" is "<<agm(x, y);
return 0;
}


Arithmetic numbers

Definition
A positive integer '''n''' is an arithmetic number if the average of its positive divisors is also an integer.

Clearly all odd primes '''p''' must be arithmetic numbers because their only divisors are '''1''' and '''p''' whose sum is even and hence their average must be an integer. However, the prime number '''2''' is not an arithmetic number because the average of its divisors is 1.5.

;Example
30 is an arithmetic number because its 7 divisors are: [1, 2, 3, 5, 6, 10, 15, 30], their sum is 72 and average 9 which is an integer.

;Task
Calculate and show here:

1. The first 100 arithmetic numbers.

2. The '''x'''th arithmetic number where '''x''' = 1,000 and '''x''' = 10,000.

3. How many of the first '''x''' arithmetic numbers are composite.

Note that, technically, the arithmetic number '''1''' is neither prime nor composite.

;Stretch
Carry out the same exercise in 2. and 3. above for '''x''' = 100,000 and '''x''' = 1,000,000.

;References

* Wikipedia: Arithmetic number
* OEIS:A003601 - Numbers n such that the average of the divisors of n is an integer

Solution:
#include <cstdio>

void divisor_count_and_sum(unsigned int n,
			   unsigned int& divisor_count,
			   unsigned int& divisor_sum)
{
  divisor_count = 0;
  divisor_sum = 0;
  for (unsigned int i = 1;; i++)
  {
    unsigned int j = n / i;
    if (j < i)
      break;
    if (i * j != n)
      continue;
    divisor_sum += i;
    divisor_count += 1;
    if (i != j)
    {
      divisor_sum += j;
      divisor_count += 1;
    }
  }
}

int main()
{
  unsigned int arithmetic_count = 0;
  unsigned int composite_count = 0;

  for (unsigned int n = 1; arithmetic_count <= 1000000; n++)
  {
    unsigned int divisor_count;
    unsigned int divisor_sum;
    divisor_count_and_sum(n, divisor_count, divisor_sum);
    unsigned int mean = divisor_sum / divisor_count;
    if (mean * divisor_count != divisor_sum)
      continue;
    arithmetic_count++;
    if (divisor_count > 2)
      composite_count++;
    if (arithmetic_count <= 100)
    {
      // would prefer to use <stream> and <format> in C++20
      std::printf("%3u ", n);
      if (arithmetic_count % 10 == 0)
	std::printf("\n");
    }
    if ((arithmetic_count == 1000) || (arithmetic_count == 10000) ||
	(arithmetic_count == 100000) || (arithmetic_count == 1000000))
    {
      std::printf("\n%uth arithmetic number is %u\n", arithmetic_count, n);
      std::printf("Number of composite arithmetic numbers <= %u: %u\n", n, composite_count);
    }
  }
  return 0;
}


Array length

Determine the amount of elements in an array.

As an example use an array holding the strings 'apple' and 'orange'.

Solution:
std::vector<std::string> fruitV({ "apples", "oranges" });
    std::list<std::string> fruitL({ "apples", "oranges" });
    std::deque<std::string> fruitD({ "apples", "oranges" });
    std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;


Ascending primes

Generate and show all primes with strictly ascending decimal digits.

Aside: Try solving without peeking at existing solutions. I had a weird idea for generating
a prime sieve faster, which needless to say didn't pan out. The solution may be p(r)etty trivial
but generating them quickly is at least mildly interesting.
Tip: filtering all 7,027,260 primes below 123,456,789 probably won't kill you, but there is
at least one significantly better and much faster way, needing a mere 511 odd/prime tests.

;See also
;* OEIS:A052015 - Primes with distinct digits in ascending order

;Related:
*[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't)
*[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted)

Solution:
/*
 *  Ascending primes
 *
 *  Generate and show all primes with strictly ascending decimal digits.
 *
 *
 *  Solution
 *
 *  We only consider positive numbers in the range 1 to 123456789. We would
 *  get 7027260 primes, because there are so many primes smaller than 123456789
 *  (see also Wolfram Alpha).On the other hand, there are only 511 distinct
 *  nonzero positive integers having their digits arranged in ascending order.
 *  Therefore, it is better to start with numbers that have properly arranged
 *  digitsand then check if they are prime numbers.The method of generating
 *  a sequence of such numbers is not indifferent.We want this sequence to be
 *  monotonically increasing, because then additional sorting of results will
 *  be unnecessary. It turns out that by using a queue we can easily get the
 *  desired effect. Additionally, the algorithm then does not use recursion
 *  (although the program probably does not have to comply with the MISRA
 *  standard). The problem to be solved is the queue size, the a priori
 *  assumption that 1000 is good enough, but a bit magical.
 */

#include <cmath>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

queue<unsigned> suspected;
vector<unsigned> primes;

bool isPrime(unsigned n)
{
    if (n == 2)
    {
        return true;
    }
    if (n == 1 || n % 2 == 0)
    {
        return false;
    }
    unsigned root = sqrt(n);
    for (unsigned k = 3; k <= root; k += 2)
    {
        if (n % k == 0)
        {
            return false;
        }
    }
    return true;
}

int main(int argc, char argv[])
{
    for (unsigned k = 1; k <= 9; k++)
    {
        suspected.push(k);
    }

    while (!suspected.empty())
    {
        int n = suspected.front();
        suspected.pop();

        if (isPrime(n))
        {
            primes.push_back(n);
        }

        //  The value of n % 10 gives the least significient digit of n
        //
        for (unsigned k = n % 10 + 1; k <= 9; k++)
        {
            suspected.push(n * 10 + k);
        }
    }

    copy(primes.begin(), primes.end(), ostream_iterator<unsigned>(cout, " "));

    return EXIT_SUCCESS;
}


Associative array/Merging

Define two associative arrays, where one represents the following "base" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 12.75
|-
| "color" || "yellow"
|}

And the other represents "update" data:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

Merge these into a new associative array that contains every key found in either of the source ones.  Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table.  If possible, do this in a way that does not mutate the original two associative arrays.  Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:

::::: {| class="wikitable"
|+
| '''Key''' || '''Value'''
|-
| "name" || "Rocket Skates"
|-
| "price" || 15.25
|-
| "color" || "red"
|-
| "year" || 1974
|}

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

template<typename map_type>
map_type merge(const map_type& original, const map_type& update) {
    map_type result(update);
    result.insert(original.begin(), original.end());
    return result;
}

int main() {
    typedef std::map<std::string, std::string> map;
    map original{
        {"name", "Rocket Skates"},
        {"price", "12.75"},
        {"color", "yellow"}
    };
    map update{
        {"price", "15.25"},
        {"color", "red"},
        {"year", "1974"}
    };
    map merged(merge(original, update));
    for (auto&& i : merged)
        std::cout << "key: " << i.first << ", value: " << i.second << '\n';
    return 0;
}


Attractive numbers

A number is an   ''attractive number''   if the number of its prime factors (whether distinct or not) is also prime.

;Example:
The number   '''20''',   whose prime decomposition is   '''2 x 2 x 5''',   is an   ''attractive number''   because the number of its prime factors   ('''3''')   is also prime.

;Task:
Show sequence items up to   '''120'''.

;Reference:
:*   The OEIS entry:   A063989: Numbers with a prime number of prime divisors.

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

#define MAX 120

using namespace std;

bool is_prime(int n) {
    if (n < 2) return false;
    if (!(n % 2)) return n == 2;
    if (!(n % 3)) return n == 3;
    int d = 5;
    while (d *d <= n) {
        if (!(n % d)) return false;
        d += 2;
        if (!(n % d)) return false;
        d += 4;
    }
    return true;
}

int count_prime_factors(int n) {
    if (n == 1) return 0;
    if (is_prime(n)) return 1;
    int count = 0, f = 2;
    while (true) {
        if (!(n % f)) {
            count++;
            n /= f;
            if (n == 1) return count;
            if (is_prime(n)) f = n;
        }
        else if (f >= 3) f += 2;
        else f = 3;
    }
}

int main() {
    cout << "The attractive numbers up to and including " << MAX << " are:" << endl;
    for (int i = 1, count = 0; i <= MAX; ++i) {
        int n = count_prime_factors(i);
        if (is_prime(n)) {
            cout << setw(4) << i;
            if (!(++count % 20)) cout << endl;
        }
    }
    cout << endl;
    return 0;
}


Average loop length

Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.

;Task:
Write a program or a script that estimates, for each N, the average length until the first such repetition.

Also calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.

This problem comes from the end of Donald Knuth's Christmas tree lecture 2011.

Example of expected output:

 N    average    analytical    (error)
===  =========  ============  =========
  1     1.0000        1.0000  (  0.00%)
  2     1.4992        1.5000  (  0.05%)
  3     1.8784        1.8889  (  0.56%)
  4     2.2316        2.2188  (  0.58%)
  5     2.4982        2.5104  (  0.49%)
  6     2.7897        2.7747  (  0.54%)
  7     3.0153        3.0181  (  0.09%)
  8     3.2429        3.2450  (  0.07%)
  9     3.4536        3.4583  (  0.14%)
 10     3.6649        3.6602  (  0.13%)
 11     3.8091        3.8524  (  1.12%)
 12     3.9986        4.0361  (  0.93%)
 13     4.2074        4.2123  (  0.12%)
 14     4.3711        4.3820  (  0.25%)
 15     4.5275        4.5458  (  0.40%)
 16     4.6755        4.7043  (  0.61%)
 17     4.8877        4.8579  (  0.61%)
 18     4.9951        5.0071  (  0.24%)
 19     5.1312        5.1522  (  0.41%)
 20     5.2699        5.2936  (  0.45%)

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

#define MAX_N 20
#define TIMES 1000000

/**
 * Used to generate a uniform random distribution
 */
static std::random_device rd;  //Will be used to obtain a seed for the random number engine
static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
static std::uniform_int_distribution<> dis;

int randint(int n) {
    int r, rmax = RAND_MAX / n * n;
    dis=std::uniform_int_distribution<int>(0,rmax) ;
    r = dis(gen);
    return r / (RAND_MAX / n);
}

unsigned long long factorial(size_t n) {
    //Factorial using dynamic programming to memoize the values.
    static std::vector<unsigned long long>factorials{1,1,2};
	for (;factorials.size() <= n;)
	    factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
	return factorials[n];
}

long double expected(size_t n) {
    long double sum = 0;
    for (size_t i = 1; i <= n; i++)
        sum += factorial(n) / pow(n, i) / factorial(n - i);
    return sum;
}

int test(int n, int times) {
    int i, count = 0;
    for (i = 0; i < times; i++) {
        unsigned int x = 1, bits = 0;
        while (!(bits & x)) {
            count++;
            bits |= x;
            x = static_cast<unsigned int>(1 << randint(n));
        }
    }
    return count;
}

int main() {
    puts(" n\tavg\texp.\tdiff\n-------------------------------");

    int n;
    for (n = 1; n <= MAX_N; n++) {
        int cnt = test(n, TIMES);
        long double avg = (double)cnt / TIMES;
        long double theory = expected(static_cast<size_t>(n));
        long double diff = (avg / theory - 1) * 100;
        printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast<double>(avg), static_cast<double>(theory), static_cast<double>(diff));
    }
    return 0;
}


Averages/Mean angle

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

#define _USE_MATH_DEFINES
#include <math.h>

template<typename C>
double meanAngle(const C& c) {
    auto it = std::cbegin(c);
    auto end = std::cend(c);

    double x = 0.0;
    double y = 0.0;
    double len = 0.0;
    while (it != end) {
        x += cos(*it * M_PI / 180);
        y += sin(*it * M_PI / 180);
        len++;

        it = std::next(it);
    }

    return atan2(y, x) * 180 / M_PI;
}

void printMean(std::initializer_list<double> init) {
    std::cout << std::fixed << std::setprecision(3) << meanAngle(init) << '\n';
}

int main() {
    printMean({ 350, 10 });
    printMean({ 90, 180, 270, 360 });
    printMean({ 10, 20, 30 });

    return 0;
}


Averages/Pythagorean means

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

double toInverse ( int i ) {
   return  1.0 / i  ;
}

int main( ) {
   std::vector<int> numbers ;
   for ( int i = 1 ; i < 11 ; i++ )
      numbers.push_back( i ) ;
   double arithmetic_mean = std::accumulate( numbers.begin( ) , numbers.end( ) , 0 ) / 10.0 ;
   double geometric_mean =
      pow( std::accumulate( numbers.begin( ) , numbers.end( ) , 1 , std::multiplies<int>( ) ), 0.1 ) ;
   std::vector<double> inverses ;
   inverses.resize( numbers.size( ) ) ;
   std::transform( numbers.begin( ) , numbers.end( ) , inverses.begin( ) , toInverse ) ;
   double harmonic_mean = 10 / std::accumulate( inverses.begin( ) , inverses.end( ) , 0.0 ); //initial value of accumulate must be a double!
   std::cout << "The arithmetic mean is " << arithmetic_mean << " , the geometric mean "
      << geometric_mean << " and the harmonic mean " << harmonic_mean << " !\n" ;
   return 0 ;
}


Averages/Root mean square

Task

Compute the   Root mean square   of the numbers 1..10.

The   ''root mean square''   is also known by its initials RMS (or rms), and as the '''quadratic mean'''.

The RMS is calculated as the mean of the squares of the numbers, square-rooted:

::: x_{\mathrm{rms}} = \sqrt {{{x_1}^2 + {x_2}^2 + \cdots + {x_n}^2} \over n}.

;See also

{{Related tasks/Statistical measures}}

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

int main( ) {
  std::vector<int> numbers ;
  for ( int i = 1 ; i < 11 ; i++ )
    numbers.push_back( i ) ;
  double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast<double>( numbers.size() ) );
  std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ;
  return 0 ;
}


Babbage problem

Charles Babbage
Charles Babbage's analytical engine.

Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
{{quote
 | What is the smallest positive integer whose square ends in the digits 269,696?
 | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
}}
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.

;Task

The task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.

For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].

;Motivation

The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.

Solution:
#include <iostream>

int main( ) {
   int current = 0 ;
   while ( ( current * current ) % 1000000 != 269696 )
      current++ ;
   std::cout << "The square of " << current << " is " << (current * current) << " !\n" ;
   return 0 ;
}


Balanced brackets

'''Task''':
* Generate a string with   '''N'''   opening brackets   '''['''   and with   '''N'''   closing brackets   ''']''',   in some arbitrary order.
* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.

;Examples:
    (empty)      OK
    []           OK
    [][]         OK
    [[][]]       OK
    ][         NOT OK
    ][][       NOT OK
    []][[]     NOT OK

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

std::string generate(int n, char left = '[', char right = ']')
{
    std::string str(std::string(n, left) + std::string(n, right));
    std::random_shuffle(str.begin(), str.end());
    return str;
}

bool balanced(const std::string &str, char left = '[', char right = ']')
{
    int count = 0;
    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
    {
        if (*it == left)
            count++;
        else if (*it == right)
            if (--count < 0) return false;
    }
    return count == 0;
}

int main()
{
    srand(time(NULL)); // seed rng
    for (int i = 0; i < 9; ++i)
    {
        std::string s(generate(i));
        std::cout << (balanced(s) ? " ok: " : "bad: ") << s << "\n";
    }
}


Balanced ternary

Balanced ternary is a way of representing numbers.  Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1.

;Examples:
Decimal 11 = 32 + 31 - 30, thus it can be written as "++-"

Decimal  6 = 32 - 31 + 0 x 30, thus it can be written as "+-0"

;Task:
Implement balanced ternary representation of integers with the following:
# Support arbitrarily large integers, both positive and negative;
# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary).  If your native integers can't support arbitrary length, overflows during conversion must be indicated.
# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.
# Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").

'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-":
* write out ''a'', ''b'' and ''c'' in decimal notation;
* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.

'''Note:''' The pages floating point balanced ternary.

Solution:
#include <iostream>
#include <string>
#include <climits>
using namespace std;

class BalancedTernary {
protected:
	// Store the value as a reversed string of +, 0 and - characters
	string value;

	// Helper function to change a balanced ternary character to an integer
	int charToInt(char c) const {
		if (c == '0')
			return 0;
		return 44 - c;
	}

	// Helper function to negate a string of ternary characters
	string negate(string s) const {
		for (int i = 0; i < s.length(); ++i) {
			if (s[i] == '+')
				s[i] = '-';
			else if (s[i] == '-')
				s[i] = '+';
		}
		return s;
	}

public:
	// Default constructor
	BalancedTernary() {
		value = "0";
	}

	// Construct from a string
	BalancedTernary(string s) {
		value = string(s.rbegin(), s.rend());
	}

	// Construct from an integer
	BalancedTernary(long long n) {
		if (n == 0) {
			value = "0";
			return;
		}

		bool neg = n < 0;
		if (neg)
			n = -n;

		value = "";
		while (n != 0) {
			int r = n % 3;
			if (r == 0)
				value += "0";
			else if (r == 1)
				value += "+";
			else {
				value += "-";
				++n;
			}

			n /= 3;
		}

		if (neg)
			value = negate(value);
	}

	// Copy constructor
	BalancedTernary(const BalancedTernary &n) {
		value = n.value;
	}

	// Addition operators
	BalancedTernary operator+(BalancedTernary n) const {
		n += *this;
		return n;
	}

	BalancedTernary& operator+=(const BalancedTernary &n) {
		static char *add = "0+-0+-0";
		static char *carry = "--000++";

		int lastNonZero = 0;
		char c = '0';
		for (int i = 0; i < value.length() || i < n.value.length(); ++i) {
			char a = i < value.length() ? value[i] : '0';
			char b = i < n.value.length() ? n.value[i] : '0';

			int sum = charToInt(a) + charToInt(b) + charToInt(c) + 3;
			c = carry[sum];

			if (i < value.length())
				value[i] = add[sum];
			else
				value += add[sum];

			if (add[sum] != '0')
				lastNonZero = i;
		}

		if (c != '0')
			value += c;
		else
			value = value.substr(0, lastNonZero + 1); // Chop off leading zeroes

		return *this;
	}

	// Negation operator
	BalancedTernary operator-() const {
		BalancedTernary result;
		result.value = negate(value);
		return result;
	}

	// Subtraction operators
	BalancedTernary operator-(const BalancedTernary &n) const {
		return operator+(-n);
	}

	BalancedTernary& operator-=(const BalancedTernary &n) {
		return operator+=(-n);
	}

	// Multiplication operators
	BalancedTernary operator*(BalancedTernary n) const {
		n *= *this;
		return n;
	}

	BalancedTernary& operator*=(const BalancedTernary &n) {
		BalancedTernary pos = *this;
		BalancedTernary neg = -pos; // Storing an extra copy to avoid negating repeatedly
		value = "0";

		for (int i = 0; i < n.value.length(); ++i) {
			if (n.value[i] == '+')
				operator+=(pos);
			else if (n.value[i] == '-')
				operator+=(neg);
			pos.value = '0' + pos.value;
			neg.value = '0' + neg.value;
		}

		return *this;
	}

	// Stream output operator
	friend ostream& operator<<(ostream &out, const BalancedTernary &n) {
		out << n.toString();
		return out;
	}

	// Convert to string
	string toString() const {
		return string(value.rbegin(), value.rend());
	}

	// Convert to integer
	long long toInt() const {
		long long result = 0;
		for (long long i = 0, pow = 1; i < value.length(); ++i, pow *= 3)
			result += pow * charToInt(value[i]);
		return result;
	}

	// Convert to integer if possible
	bool tryInt(long long &out) const {
		long long result = 0;
		bool ok = true;

		for (long long i = 0, pow = 1; i < value.length() && ok; ++i, pow *= 3) {
			if (value[i] == '+') {
				ok &= LLONG_MAX - pow >= result; // Clear ok if the result overflows
				result += pow;
			} else if (value[i] == '-') {
				ok &= LLONG_MIN + pow <= result; // Clear ok if the result overflows
				result -= pow;
			}
		}

		if (ok)
			out = result;
		return ok;
	}
};

int main() {
	BalancedTernary a("+-0++0+");
	BalancedTernary b(-436);
	BalancedTernary c("+-++-");

	cout << "a = " << a << " = " << a.toInt() << endl;
	cout << "b = " << b << " = " << b.toInt() << endl;
	cout << "c = " << c << " = " << c.toInt() << endl;

	BalancedTernary d = a * (b - c);

	cout << "a * (b - c) = " << d << " = " << d.toInt() << endl;

	BalancedTernary e("+++++++++++++++++++++++++++++++++++++++++");

	long long n;
	if (e.tryInt(n))
		cout << "e = " << e << " = " << n << endl;
	else
		cout << "e = " << e << " is too big to fit in a long long" << endl;

	return 0;
}


Barnsley fern

A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).

;Task:
Create this fractal fern, using the following transformations:
* f1   (chosen 1% of the time)
         xn + 1 = 0
         yn + 1 = 0.16 yn

* f2   (chosen 85% of the time)
         xn + 1 = 0.85 xn + 0.04 yn
         yn + 1 = -0.04 xn + 0.85 yn + 1.6

* f3   (chosen 7% of the time)
         xn + 1 = 0.2 xn - 0.26 yn
         yn + 1 = 0.23 xn + 0.22 yn + 1.6

* f4   (chosen 7% of the time)
         xn + 1 = -0.15 xn + 0.28 yn
         yn + 1 = 0.26 xn + 0.24 yn + 0.44.

Starting position: x = 0, y = 0

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

const int BMP_SIZE = 600, ITERATIONS = static_cast<int>( 15e5 );

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;
};
class fern {
public:
    void draw() {
        bmp.create( BMP_SIZE, BMP_SIZE );
        float x = 0, y = 0; HDC dc = bmp.getDC();
        int hs = BMP_SIZE >> 1;
        for( int f = 0; f < ITERATIONS; f++ ) {
            SetPixel( dc, hs + static_cast<int>( x * 55.f ),
                      BMP_SIZE - 15 - static_cast<int>( y * 55.f ),
                      RGB( static_cast<int>( rnd() * 80.f ) + 20,
                           static_cast<int>( rnd() * 128.f ) + 128,
                           static_cast<int>( rnd() * 80.f ) + 30 ) );
            getXY( x, y );
        }
        bmp.saveBitmap( "./bf.bmp" );
    }
private:
    void getXY( float& x, float& y ) {
        float g, xl, yl;
        g = rnd();
        if( g < .01f ) { xl = 0; yl = .16f * y; }
        else if( g < .07f ) {
            xl = .2f * x - .26f * y;
            yl = .23f * x + .22f * y + 1.6f;
        } else if( g < .14f ) {
            xl = -.15f * x + .28f * y;
            yl = .26f * x + .24f * y + .44f;
        } else {
            xl = .85f * x + .04f * y;
            yl = -.04f * x + .85f * y + 1.6f;
        }
        x = xl; y = yl;
    }
    float rnd() {
        return static_cast<float>( rand() ) / static_cast<float>( RAND_MAX );
    }
    myBitmap bmp;
};
int main( int argc, char* argv[]) {
    srand( static_cast<unsigned>( time( 0 ) ) );
    fern f; f.draw(); return 0;
}


Base64 decode data

See [[Base64 encode data]].

Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.

When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

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

typedef unsigned char ubyte;
const auto BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::vector<ubyte> encode(const std::vector<ubyte>& source) {
    auto it = source.cbegin();
    auto end = source.cend();

    std::vector<ubyte> sink;
    while (it != end) {
        auto b1 = *it++;
        int acc;

        sink.push_back(BASE64[b1 >> 2]);            // first output (first six bits from b1)

        acc = (b1 & 0x3) << 4;                      // last two bits from b1
        if (it != end) {
            auto b2 = *it++;
            acc |= (b2 >> 4);                       // first four bits from b2

            sink.push_back(BASE64[acc]);            // second output

            acc = (b2 & 0xF) << 2;                  // last four bits from b2
            if (it != end) {
                auto b3 = *it++;
                acc |= (b3 >> 6);                   // first two bits from b3

                sink.push_back(BASE64[acc]);        // third output
                sink.push_back(BASE64[b3 & 0x3F]);  // fouth output (final six bits from b3)
            } else {
                sink.push_back(BASE64[acc]);        // third output
                sink.push_back('=');                // fourth output (1 byte padding)
            }
        } else {
            sink.push_back(BASE64[acc]);            // second output
            sink.push_back('=');                    // third output (first padding byte)
            sink.push_back('=');                    // fourth output (second padding byte)
        }
    }
    return sink;
}

int findIndex(ubyte val) {
    if ('A' <= val && val <= 'Z') {
        return val - 'A';
    }
    if ('a' <= val && val <= 'z') {
        return val - 'a' + 26;
    }
    if ('0' <= val && val <= '9') {
        return val - '0' + 52;
    }
    if ('+' == val) {
        return 62;
    }
    if ('/' == val) {
        return 63;
    }
    return -1;
}

std::vector<ubyte> decode(const std::vector<ubyte>& source) {
    if (source.size() % 4 != 0) {
        throw new std::runtime_error("Error in size to the decode method");
    }

    auto it = source.cbegin();
    auto end = source.cend();

    std::vector<ubyte> sink;
    while (it != end) {
        auto b1 = *it++;
        auto b2 = *it++;
        auto b3 = *it++; // might be first padding byte
        auto b4 = *it++; // might be first or second padding byte

        auto i1 = findIndex(b1);
        auto i2 = findIndex(b2);
        auto acc = i1 << 2;     // six bits came from the first byte
        acc |= i2 >> 4;         // two bits came from the first byte

        sink.push_back(acc);    // output the first byte

        if (b3 != '=') {
            auto i3 = findIndex(b3);

            acc = (i2 & 0xF) << 4;  // four bits came from the second byte
            acc |= i3 >> 2;         // four bits came from the second byte

            sink.push_back(acc);    // output the second byte

            if (b4 != '=') {
                auto i4 = findIndex(b4);

                acc = (i3 & 0x3) << 6;  // two bits came from the third byte
                acc |= i4;              // six bits came from the third byte

                sink.push_back(acc);    // output the third byte
            }
        }
    }
    return sink;
}

int main() {
    using namespace std;

    string data = "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLVBhdWwgUi5FaHJsaWNo";
    vector<ubyte> datav{ begin(data), end(data) };
    cout << data << "\n\n" << decode(datav).data() << endl;

    return 0;
}


Benford's law

{{Wikipedia|Benford's_law}}

'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.

In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.

Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.

This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.

A set of numbers is said to satisfy Benford's law if the leading digit d  (d \in \{1, \ldots, 9\}) occurs with probability

:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)

For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).

Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.

You can generate them or load them from a file; whichever is easiest.

Display your actual vs expected distribution.

''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.

Solution:
//to cope with the big numbers , I used the Class Library for Numbers( CLN )
//if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram"
#include <cln/integer.h>
#include <cln/integer_io.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <map>
using namespace cln ;

class NextNum {
public :
   NextNum ( cl_I & a , cl_I & b ) : first( a ) , second ( b ) { }
   cl_I operator( )( ) {
      cl_I result = first + second ;
      first = second ;
      second = result ;
      return result ;
   }
private :
   cl_I first ;
   cl_I second ;
} ;

void findFrequencies( const std::vector<cl_I> & fibos , std::map<int , int> &numberfrequencies  ) {
   for ( cl_I bignumber : fibos ) {
      std::ostringstream os ;
      fprintdecimal ( os , bignumber ) ;//from header file cln/integer_io.h
      int firstdigit = std::atoi( os.str( ).substr( 0 , 1 ).c_str( )) ;
      auto result = numberfrequencies.insert( std::make_pair( firstdigit , 1 ) ) ;
      if ( ! result.second )
	 numberfrequencies[ firstdigit ]++ ;
   }
}

int main( ) {
   std::vector<cl_I> fibonaccis( 1000 ) ;
   fibonaccis[ 0 ] = 0 ;
   fibonaccis[ 1 ] = 1 ;
   cl_I a = 0 ;
   cl_I b = 1 ;
   //since a and b are passed as references to the generator's constructor
   //they are constantly changed !
   std::generate_n( fibonaccis.begin( ) + 2 , 998 , NextNum( a , b ) ) ;
   std::cout << std::endl ;
   std::map<int , int> frequencies ;
   findFrequencies( fibonaccis , frequencies ) ;
   std::cout << "                found                    expected\n" ;
   for ( int i = 1 ; i < 10 ; i++ ) {
      double found = static_cast<double>( frequencies[ i ] ) / 1000 ;
      double expected = std::log10( 1 + 1 / static_cast<double>( i )) ;
      std::cout << i << " :" << std::setw( 16 ) << std::right << found * 100 << " %" ;
      std::cout.precision( 3 ) ;
      std::cout << std::setw( 26 ) << std::right << expected * 100 << " %\n" ;
   }
   return 0 ;
}


Best shuffle

Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.

A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.

Display the result as follows:

 original string, shuffled string, (score)

The score gives the number of positions whose character value did ''not'' change.

;Example:
 tree, eetr, (0)

;Test cases:
 abracadabra
 seesaw
 elk
 grrrrrr
 up
 a

;Related tasks
*   [[Anagrams/Deranged anagrams]]
*   [[Permutations/Derangements]]

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

using namespace std;

template <class S>
class BestShuffle {
public:
    BestShuffle() : rd(), g(rd()) {}

    S operator()(const S& s1) {
        S s2 = s1;
        shuffle(s2.begin(), s2.end(), g);
        for (unsigned i = 0; i < s2.length(); i++)
            if (s2[i] == s1[i])
                for (unsigned j = 0; j < s2.length(); j++)
                    if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {
                        swap(s2[i], s2[j]);
                        break;
                    }
        ostringstream os;
        os << s1 << endl << s2 << " [" << count(s2, s1) << ']';
        return os.str();
    }

private:
    static int count(const S& s1, const S& s2) {
        auto count = 0;
        for (unsigned i = 0; i < s1.length(); i++)
            if (s1[i] == s2[i])
                count++;
        return count;
    }

    random_device rd;
    mt19937 g;
};

int main(int argc, char* arguments[]) {
    BestShuffle<basic_string<char>> bs;
    for (auto i = 1; i < argc; i++)
        cout << bs(basic_string<char>(arguments[i])) << endl;
    return 0;
}


Bin given limits

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

std::vector<int> bins(const std::vector<int>& limits,
                      const std::vector<int>& data) {
    std::vector<int> result(limits.size() + 1, 0);
    for (int n : data) {
        auto i = std::upper_bound(limits.begin(), limits.end(), n);
        ++result[i - limits.begin()];
    }
    return result;
}

void print_bins(const std::vector<int>& limits, const std::vector<int>& bins) {
    size_t n = limits.size();
    if (n == 0)
        return;
    assert(n + 1 == bins.size());
    std::cout << "           < " << std::setw(3) << limits[0] << ": "
              << std::setw(2) << bins[0] << '\n';
    for (size_t i = 1; i < n; ++i)
        std::cout << ">= " << std::setw(3) << limits[i - 1] << " and < "
                  << std::setw(3) << limits[i] << ": " << std::setw(2)
                  << bins[i] << '\n';
    std::cout << ">= " << std::setw(3) << limits[n - 1] << "          : "
              << std::setw(2) << bins[n] << '\n';
}

int main() {
    const std::vector<int> limits1{23, 37, 43, 53, 67, 83};
    const std::vector<int> data1{
        95, 21, 94, 12, 99, 4,  70, 75, 83, 93, 52, 80, 57, 5,  53, 86, 65,
        17, 92, 83, 71, 61, 54, 58, 47, 16, 8,  9,  32, 84, 7,  87, 46, 19,
        30, 37, 96, 6,  98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55};

    std::cout << "Example 1:\n";
    print_bins(limits1, bins(limits1, data1));

    const std::vector<int> limits2{14,  18,  249, 312, 389,
                                   392, 513, 591, 634, 720};
    const std::vector<int> data2{
        445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77,  323, 525,
        570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47,
        731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267,
        248, 477, 549, 238, 62,  678, 98,  534, 622, 907, 406, 714, 184, 391,
        913, 42,  560, 247, 346, 860, 56,  138, 546, 38,  985, 948, 58,  213,
        799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917,
        313, 845, 426, 9,   457, 628, 410, 723, 354, 895, 881, 953, 677, 137,
        397, 97,  854, 740, 83,  216, 421, 94,  517, 479, 292, 963, 376, 981,
        480, 39,  257, 272, 157, 5,   316, 395, 787, 942, 456, 242, 759, 898,
        576, 67,  298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692,
        698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40,
        54,  901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427,
        876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23,
        707, 467, 33,  670, 921, 180, 991, 396, 160, 436, 717, 918, 8,   374,
        101, 684, 727, 749};

    std::cout << "\nExample 2:\n";
    print_bins(limits2, bins(limits2, data2));
}


Bioinformatics/Sequence mutation

Given a string of characters A, C, G, and T representing a DNA sequence write a routine to mutate the sequence, (string) by:
# Choosing a random base position in the sequence.
# Mutate the sequence by  doing one of either:
## '''S'''wap the base at that position by changing it to one of A, C, G, or T. (which has a chance of swapping the base for the same base)
## '''D'''elete the chosen base at the position.
## '''I'''nsert another base randomly chosen from A,C, G, or T into the sequence at that position.
# Randomly generate a test DNA sequence of at least 200 bases
# "Pretty print" the sequence and a count of its size, and the count of each base in the sequence
# Mutate the sequence ten times.
# "Pretty print" the sequence after all mutations, and a count of its size, and the count of each base in the sequence.

;Extra credit:
* Give more information on the individual mutations applied.
* Allow mutations to be weighted and/or chosen.

Solution:
#include <array>
#include <iomanip>
#include <iostream>
#include <random>
#include <string>

class sequence_generator {
public:
    sequence_generator();
    std::string generate_sequence(size_t length);
    void mutate_sequence(std::string&);
    static void print_sequence(std::ostream&, const std::string&);
    enum class operation { change, erase, insert };
    void set_weight(operation, unsigned int);
private:
    char get_random_base() {
        return bases_[base_dist_(engine_)];
    }
    operation get_random_operation();
    static const std::array<char, 4> bases_;
    std::mt19937 engine_;
    std::uniform_int_distribution<size_t> base_dist_;
    std::array<unsigned int, 3> operation_weight_;
    unsigned int total_weight_;
};

const std::array<char, 4> sequence_generator::bases_{ 'A', 'C', 'G', 'T' };

sequence_generator::sequence_generator() : engine_(std::random_device()()),
    base_dist_(0, bases_.size() - 1),
    total_weight_(operation_weight_.size()) {
    operation_weight_.fill(1);
}

sequence_generator::operation sequence_generator::get_random_operation() {
    std::uniform_int_distribution<unsigned int> op_dist(0, total_weight_ - 1);
    unsigned int n = op_dist(engine_), op = 0, weight = 0;
    for (; op < operation_weight_.size(); ++op) {
        weight += operation_weight_[op];
        if (n < weight)
            break;
    }
    return static_cast<operation>(op);
}

void sequence_generator::set_weight(operation op, unsigned int weight) {
    total_weight_ -= operation_weight_[static_cast<size_t>(op)];
    operation_weight_[static_cast<size_t>(op)] = weight;
    total_weight_ += weight;
}

std::string sequence_generator::generate_sequence(size_t length) {
    std::string sequence;
    sequence.reserve(length);
    for (size_t i = 0; i < length; ++i)
        sequence += get_random_base();
    return sequence;
}

void sequence_generator::mutate_sequence(std::string& sequence) {
    std::uniform_int_distribution<size_t> dist(0, sequence.length() - 1);
    size_t pos = dist(engine_);
    char b;
    switch (get_random_operation()) {
    case operation::change:
        b = get_random_base();
        std::cout << "Change base at position " << pos << " from "
            << sequence[pos] << " to " << b << '\n';
        sequence[pos] = b;
        break;
    case operation::erase:
        std::cout << "Erase base " << sequence[pos] << " at position "
            << pos << '\n';
        sequence.erase(pos, 1);
        break;
    case operation::insert:
        b = get_random_base();
        std::cout << "Insert base " << b << " at position "
            << pos << '\n';
        sequence.insert(pos, 1, b);
        break;
    }
}

void sequence_generator::print_sequence(std::ostream& out, const std::string& sequence) {
    constexpr size_t base_count = bases_.size();
    std::array<size_t, base_count> count = { 0 };
    for (size_t i = 0, n = sequence.length(); i < n; ++i) {
        if (i % 50 == 0) {
            if (i != 0)
                out << '\n';
            out << std::setw(3) << i << ": ";
        }
        out << sequence[i];
        for (size_t j = 0; j < base_count; ++j) {
            if (bases_[j] == sequence[i]) {
                ++count[j];
                break;
            }
        }
    }
    out << '\n';
    out << "Base counts:\n";
    size_t total = 0;
    for (size_t j = 0; j < base_count; ++j) {
        total += count[j];
        out << bases_[j] << ": " << count[j] << ", ";
    }
    out << "Total: " << total << '\n';
}

int main() {
    sequence_generator gen;
    gen.set_weight(sequence_generator::operation::change, 2);
    std::string sequence = gen.generate_sequence(250);
    std::cout << "Initial sequence:\n";
    sequence_generator::print_sequence(std::cout, sequence);
    constexpr int count = 10;
    for (int i = 0; i < count; ++i)
        gen.mutate_sequence(sequence);
    std::cout << "After " << count << " mutations:\n";
    sequence_generator::print_sequence(std::cout, sequence);
    return 0;
}


Bioinformatics/base count

Given this string representing ordered DNA bases:

CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT

;Task:
:*   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   ('''A''', '''C''', '''G''', and '''T''')   in the sequence
:*   print the total count of each base in the string.

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

const std::string DEFAULT_DNA = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG"
                                "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG"
                                "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT"
                                "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT"
                                "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG"
                                "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA"
                                "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT"
                                "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG"
                                "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC"
                                "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT";

class DnaBase {
public:
    DnaBase(const std::string& dna = DEFAULT_DNA, int width = 50) : genome(dna), displayWidth(width) {
        // Map each character to a counter
        for (auto elm : dna) {
            if (count.find(elm) == count.end())
                count[elm] = 0;
            ++count[elm];
        }
    }

    void viewGenome() {
        std::cout << "Sequence:" << std::endl;
        std::cout << std::endl;
        int limit = genome.size() / displayWidth;
        if (genome.size() % displayWidth != 0)
            ++limit;

        for (int i = 0; i < limit; ++i) {
            int beginPos = i * displayWidth;
            std::cout << std::setw(4) << beginPos << "  :" << std::setw(4) << genome.substr(beginPos, displayWidth) << std::endl;
        }
        std::cout << std::endl;
        std::cout << "Base Count" << std::endl;
        std::cout << "----------" << std::endl;
        std::cout << std::endl;
        int total = 0;
        for (auto elm : count) {
            std::cout << std::setw(4) << elm.first << " : " << elm.second << std::endl;
            total += elm.second;
        }
        std::cout << std::endl;
        std::cout << "Total: " << total << std::endl;
    }

private:
    std::string genome;
    std::map<char, int> count;
    int displayWidth;
};

int main(void) {
    auto d = new DnaBase();
    d->viewGenome();
    delete d;
    return 0;
}


Brazilian numbers

Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.

Brazilian numbers are defined as:

The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.

;E.G.:

:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.
:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.
:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.
:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.
:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.
:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.
:* ''and so on...''

All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.
More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes >  2

;Task:

Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;

:* the first '''20''' Brazilian numbers;
:* the first '''20 odd''' Brazilian numbers;
:* the first '''20 prime''' Brazilian numbers;

;See also:

:* '''OEIS:A125134 - Brazilian numbers'''
:* '''OEIS:A257521 - Odd Brazilian numbers'''
:* '''OEIS:A085104 - Prime Brazilian numbers'''

Solution:
#include <iostream>

bool sameDigits(int n, int b) {
    int f = n % b;
    while ((n /= b) > 0) {
        if (n % b != f) {
            return false;
        }
    }
    return true;
}

bool isBrazilian(int n) {
    if (n < 7) return false;
    if (n % 2 == 0)return true;
    for (int b = 2; b < n - 1; b++) {
        if (sameDigits(n, b)) {
            return true;
        }
    }
    return false;
}

bool isPrime(int n) {
    if (n < 2)return false;
    if (n % 2 == 0)return n == 2;
    if (n % 3 == 0)return n == 3;
    int d = 5;
    while (d * d <= n) {
        if (n % d == 0)return false;
        d += 2;
        if (n % d == 0)return false;
        d += 4;
    }
    return true;
}

int main() {
    for (auto kind : { "", "odd ", "prime " }) {
        bool quiet = false;
        int BigLim = 99999;
        int limit = 20;
        std::cout << "First " << limit << ' ' << kind << "Brazillian numbers:\n";
        int c = 0;
        int n = 7;
        while (c < BigLim) {
            if (isBrazilian(n)) {
                if (!quiet)std::cout << n << ' ';
                if (++c == limit) {
                    std::cout << "\n\n";
                    quiet = true;
                }
            }
            if (quiet && kind != "") continue;
            if (kind == "") {
                n++;
            }
            else if (kind == "odd ") {
                n += 2;
            }
            else if (kind == "prime ") {
                while (true) {
                    n += 2;
                    if (isPrime(n)) break;
                }
            } else {
                throw new std::runtime_error("Unexpected");
            }
        }
        if (kind == "") {
            std::cout << "The " << BigLim + 1 << "th Brazillian number is: " << n << "\n\n";
        }
    }

    return 0;
}


Break OO privacy

Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object  but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.

Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.

Solution:
#include <iostream>

class CWidget; // Forward-declare that we have a class named CWidget.

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); // Disallow the default constructor.
  CWidget(const CWidget&); // Disallow the copy constructor
  CWidget& operator=(const CWidget&); // Disallow the assignment operator.
public:
  CWidget(CFactory& parent);
  ~CWidget();
};

// CFactory constructors and destructors. Very simple things.
CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}

// CFactory method which creates CWidgets.
CWidget* CFactory::GetWidget()
{
  // Create a new CWidget, tell it we're its parent.
  return new CWidget(*this);
}

// CWidget constructor
CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}


Burrows–Wheeler transform

{{Wikipedia|Burrows-Wheeler_transform}}

The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.

This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.

More importantly, the transformation is reversible, without needing to store any additional data.

The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.

Source: Burrows-Wheeler transform

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

const int STX = 0x02;
const int ETX = 0x03;

void rotate(std::string &a) {
    char t = a[a.length() - 1];
    for (int i = a.length() - 1; i > 0; i--) {
        a[i] = a[i - 1];
    }
    a[0] = t;
}

std::string bwt(const std::string &s) {
    for (char c : s) {
        if (c == STX || c == ETX) {
            throw std::runtime_error("Input can't contain STX or ETX");
        }
    }

    std::string ss;
    ss += STX;
    ss += s;
    ss += ETX;

    std::vector<std::string> table;
    for (size_t i = 0; i < ss.length(); i++) {
        table.push_back(ss);
        rotate(ss);
    }
    //table.sort();
    std::sort(table.begin(), table.end());

    std::string out;
    for (auto &s : table) {
        out += s[s.length() - 1];
    }
    return out;
}

std::string ibwt(const std::string &r) {
    int len = r.length();
    std::vector<std::string> table(len);
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
            table[j] = r[j] + table[j];
        }
        std::sort(table.begin(), table.end());
    }
    for (auto &row : table) {
        if (row[row.length() - 1] == ETX) {
            return row.substr(1, row.length() - 2);
        }
    }
    return {};
}

std::string makePrintable(const std::string &s) {
    auto ls = s;
    for (auto &c : ls) {
        if (c == STX) {
            c = '^';
        } else if (c == ETX) {
            c = '|';
        }
    }
    return ls;
}

int main() {
    auto tests = {
        "banana",
        "appellee",
        "dogwood",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "\u0002ABC\u0003"
    };

    for (auto &test : tests) {
        std::cout << makePrintable(test) << "\n";
        std::cout << " --> ";

        std::string t;
        try {
            t = bwt(test);
            std::cout << makePrintable(t) << "\n";
        } catch (std::runtime_error &e) {
            std::cout << "Error " << e.what() << "\n";
        }

        std::string r = ibwt(t);
        std::cout << " --> " << r << "\n\n";
    }

    return 0;
}


CSV data manipulation

CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.

The CSV format is flexible but somewhat ill-defined.

For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.

;Task:
Read a CSV file, change some values and save the changes back to a file.

For this task we will use the following CSV file:

 C1,C2,C3,C4,C5
 1,5,9,13,17
 2,6,10,14,18
 3,7,11,15,19
 4,8,12,16,20

Suggestions

 Show how to add a column, headed 'SUM', of the sums of the rows.
 If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.

Solution:
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <utility>
#include <functional>
#include <string>
#include <sstream>
#include <algorithm>
#include <cctype>

class CSV
{
public:
    CSV(void) : m_nCols( 0 ), m_nRows( 0 )
    {}

    bool open( const char* filename, char delim = ',' )
    {
        std::ifstream file( filename );

        clear();
        if ( file.is_open() )
        {
            open( file, delim );
            return true;
        }

        return false;
    }

    void open( std::istream& istream, char delim = ',' )
    {
        std::string         line;

        clear();
        while ( std::getline( istream, line ) )
        {
            unsigned int nCol = 0;
            std::istringstream    lineStream(line);
            std::string           cell;

            while( std::getline( lineStream, cell, delim ) )
            {
                m_oData[std::make_pair( nCol, m_nRows )] = trim( cell );
                nCol++;
            }
            m_nCols = std::max( m_nCols, nCol );
            m_nRows++;
        }
    }

    bool save( const char* pFile, char delim = ',' )
    {
        std::ofstream ofile( pFile );
        if ( ofile.is_open() )
        {
            save( ofile );
            return true;
        }
        return false;
    }

    void save( std::ostream& ostream, char delim = ',' )
    {
        for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ )
        {
            for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ )
            {
                ostream << trim( m_oData[std::make_pair( nCol, nRow )] );
                if ( (nCol+1) < m_nCols )
                {
                    ostream << delim;
                }
                else
                {
                    ostream << std::endl;
                }
            }
        }
    }

    void clear()
    {
        m_oData.clear();
        m_nRows = m_nCols = 0;
    }

    std::string& operator()( unsigned int nCol, unsigned int nRow )
    {
        m_nCols = std::max( m_nCols, nCol+1 );
        m_nRows = std::max( m_nRows, nRow+1 );
        return m_oData[std::make_pair(nCol, nRow)];
    }

    inline unsigned int GetRows() { return m_nRows; }
    inline unsigned int GetCols() { return m_nCols; }

private:
    // trim string for empty spaces in begining and at the end
    inline std::string &trim(std::string &s)
    {

        s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
        s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
        return s;
    }

private:
    std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData;

    unsigned int    m_nCols;
    unsigned int    m_nRows;
};

int main()
{
    CSV oCSV;

    oCSV.open( "test_in.csv" );
    oCSV( 0, 0 ) = "Column0";
    oCSV( 1, 1 ) = "100";
    oCSV( 2, 2 ) = "200";
    oCSV( 3, 3 ) = "300";
    oCSV( 4, 4 ) = "400";
    oCSV.save( "test_out.csv" );
    return 0;
}


CSV to HTML translation

Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.

No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be   ''escaped''   when converted to HTML

;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.

Use the following  data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!

;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via  preferably; CSS if you must).

Solution:
#include <string>
#include <boost/regex.hpp>
#include <iostream>

std::string csvToHTML( const std::string & ) ;

int main( ) {
   std::string text = "Character,Speech\n"
                            "The multitude,The messiah! Show us the messiah!\n"
			    "Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>\n"
	                    "The multitude,Who are you?\n"
		            "Brians mother,I'm his mother; that's who!\n"
		            "The multitude,Behold his mother! Behold his mother!\n" ;
  std::cout << csvToHTML( text ) ;
  return 0 ;
}

std::string csvToHTML( const std::string & csvtext ) {
   //the order of the regexes and the replacements is decisive!
   std::string regexes[ 5 ] = { "<" , ">" , "^(.+?)\\b" , "," , "\n" } ;
   const char* replacements [ 5 ] = { "<" , ">" , "
$1" , "	", "
\n"  } ;
   boost::regex e1( regexes[ 0 ] ) ;
   std::string tabletext = boost::regex_replace( csvtext , e1 ,
     replacements[ 0 ] , boost::match_default | boost::format_all ) ;
   for ( int i = 1 ; i < 5 ; i++ ) {
      e1.assign( regexes[ i ] ) ;
      tabletext = boost::regex_replace( tabletext , e1 , replacements[ i ] , boost::match_default | boost::format_all ) ;
   }
   tabletext = std::string( "
\n" ) + tabletext ;
   tabletext.append( "
\n" ) ;
   return tabletext ;
}


Calculating the value of e

Calculate the value of   ''e''.

(''e''   is also known as   ''Euler's number''   and   ''Napier's constant''.)

See details: Calculating the value of e

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

using namespace std;

int main() {
    const double EPSILON = 1.0e-15;
    unsigned long long fact = 1;
    double e = 2.0, e0;
    int n = 2;
    do {
        e0 = e;
        fact *= n++;
        e += 1.0 / fact;
    }
    while (fabs(e - e0) >= EPSILON);
    cout << "e = " << setprecision(16) << e << endl;
    return 0;
}


Call a function

Demonstrate the different syntax and semantics provided for calling a function.

This may include:
:*   Calling a function that requires no arguments
:*   Calling a function with a fixed number of arguments
:*   Calling a function with optional arguments
:*   Calling a function with a variable number of arguments
:*   Calling a function with named arguments
:*   Using a function in statement context
:*   Using a function in first-class context within an expression
:*   Obtaining the return value of a function
:*   Distinguishing built-in functions and user-defined functions
:*   Distinguishing subroutines and functions
;*   Stating whether arguments are passed by value or by reference
;*   Is partial application possible and how

This task is ''not'' about defining functions.

Solution:
#include <iostream>
using namespace std;
/* passing arguments by reference */
void f(int &y) /* variable is now passed by reference */
{
y++;
}
int main()
{
int x = 0;
cout<<"x = "<<x<<endl; /* should produce result "x = 0" */
f(x);                  /* call function f */
cout<<"x = "<<x<<endl; /* should produce result "x = 1" */
}


Canonicalize CIDR

Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.

That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.

;Example:
Given   '''87.70.141.1/22''',    your code should output    '''87.70.140.0/22'''

;Explanation:
An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 digit is given in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the network portion of the address, while the rightmost (least-significant) bits determine the host portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion.

In general, CIDR blocks stand in for the entire set of IP addresses sharing the same network component, so it's common to see access control lists that specify individual IP addresses using /32 to indicate that only the one address is included. Software accepting this notation as input often expects it to be entered in canonical form, in which the host bits are all zeroes. But network admins sometimes skip this step and just enter the address of a specific host on the subnet with the network size, resulting in a non-canonical entry.

The example address, 87.70.141.1/22, represents binary 0101011101000110100011 / 0100000001, with the / indicating the network/host division. To canonicalize, clear all the bits to the right of the / and convert back to dotted decimal: 0101011101000110100011 / 0000000000 - 87.70.140.0.

;More examples for testing

        36.18.154.103/12    -  36.16.0.0/12
        62.62.197.11/29     -  62.62.197.8/29
        67.137.119.181/4    -  64.0.0.0/4
        161.214.74.21/24    -  161.214.74.0/24
        184.232.176.184/18  -  184.232.128.0/18

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

// Class representing an IPv4 address + netmask length
class ipv4_cidr {
public:
    ipv4_cidr() {}
    ipv4_cidr(std::uint32_t address, unsigned int mask_length)
        : address_(address), mask_length_(mask_length) {}
    std::uint32_t address() const {
        return address_;
    }
    unsigned int mask_length() const {
        return mask_length_;
    }
    friend std::istream& operator>>(std::istream&, ipv4_cidr&);
private:
    std::uint32_t address_ = 0;
    unsigned int mask_length_ = 0;
};

// Stream extraction operator, also performs canonicalization
std::istream& operator>>(std::istream& in, ipv4_cidr& cidr) {
    int a, b, c, d, m;
    char ch;
    if (!(in >> a >> ch) || a < 0 || a > UINT8_MAX || ch != '.'
        || !(in >> b >> ch) || b < 0 || b > UINT8_MAX || ch != '.'
        || !(in >> c >> ch) || c < 0 || c > UINT8_MAX || ch != '.'
        || !(in >> d >> ch) || d < 0 || d > UINT8_MAX || ch != '/'
        || !(in >> m) || m < 1 || m > 32) {
        in.setstate(std::ios_base::failbit);
        return in;
    }
    uint32_t mask = ~((1 << (32 - m)) - 1);
    uint32_t address = (a << 24) + (b << 16) + (c << 8) + d;
    address &= mask;
    cidr.address_ = address;
    cidr.mask_length_ = m;
    return in;
}

// Stream insertion operator
std::ostream& operator<<(std::ostream& out, const ipv4_cidr& cidr) {
    uint32_t address = cidr.address();
    unsigned int d = address & UINT8_MAX;
    address >>= 8;
    unsigned int c = address & UINT8_MAX;
    address >>= 8;
    unsigned int b = address & UINT8_MAX;
    address >>= 8;
    unsigned int a = address & UINT8_MAX;
    out << a << '.' << b << '.' << c << '.' << d << '/'
        << cidr.mask_length();
    return out;
}

int main(int argc, char** argv) {
    const char* tests[] = {
        "87.70.141.1/22",
        "36.18.154.103/12",
        "62.62.197.11/29",
        "67.137.119.181/4",
        "161.214.74.21/24",
        "184.232.176.184/18"
    };
    for (auto test : tests) {
        std::istringstream in(test);
        ipv4_cidr cidr;
        if (in >> cidr)
            std::cout << std::setw(18) << std::left << test << " -> "
                << cidr << '\n';
        else
            std::cerr << test << ": invalid CIDR\n";
    }
    return 0;
}


Cantor set

Draw a Cantor set.

See details at this Wikipedia webpage:   Cantor set

Solution:
#include <iostream>

const int WIDTH = 81;
const int HEIGHT = 5;

char lines[WIDTH*HEIGHT];

void cantor(int start, int len, int index) {
	int seg = len / 3;
	if (seg == 0) return;
	for (int i = index; i < HEIGHT; i++) {
		for (int j = start + seg; j < start + seg * 2; j++) {
			int pos = i * WIDTH + j;
			lines[pos] = ' ';
		}
	}
	cantor(start,           seg, index + 1);
	cantor(start + 2 * seg, seg, index + 1);
}

int main() {
	// init
	for (int i = 0; i < WIDTH*HEIGHT; i++) {
		lines[i] = '*';
	}

	// calculate
	cantor(0, WIDTH, 1);

	// print
	for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) {
		printf("%.*s\n", WIDTH, lines + i);
	}

	return 0;
}


Cartesian product of two or more lists

Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.

Demonstrate that your function/method correctly returns:
::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}

and, in contrast:
::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}

Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
:: {1, 2} x {} = {}
:: {} x {1, 2} = {}

For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.

Use your n-ary Cartesian product function to show the following products:
:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}
:: {1, 2, 3} x {30} x {500, 100}
:: {1, 2, 3} x {} x {500, 100}

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

void print(const std::vector<std::vector<int>>& v) {
  std::cout << "{ ";
  for (const auto& p : v) {
    std::cout << "(";
    for (const auto& e : p) {
      std::cout << e << " ";
    }
    std::cout << ") ";
  }
  std::cout << "}" << std::endl;
}

auto product(const std::vector<std::vector<int>>& lists) {
  std::vector<std::vector<int>> result;
  if (std::find_if(std::begin(lists), std::end(lists),
    [](auto e) -> bool { return e.size() == 0; }) != std::end(lists)) {
    return result;
  }
  for (auto& e : lists[0]) {
    result.push_back({ e });
  }
  for (size_t i = 1; i < lists.size(); ++i) {
    std::vector<std::vector<int>> temp;
    for (auto& e : result) {
      for (auto f : lists[i]) {
        auto e_tmp = e;
        e_tmp.push_back(f);
        temp.push_back(e_tmp);
      }
    }
    result = temp;
  }
  return result;
}

int main() {
  std::vector<std::vector<int>> prods[] = {
    { { 1, 2 }, { 3, 4 } },
    { { 3, 4 }, { 1, 2} },
    { { 1, 2 }, { } },
    { { }, { 1, 2 } },
    { { 1776, 1789 }, { 7, 12 }, { 4, 14, 23 }, { 0, 1 } },
    { { 1, 2, 3 }, { 30 }, { 500, 100 } },
    { { 1, 2, 3 }, { }, { 500, 100 } }
  };
  for (const auto& p : prods) {
    print(product(p));
  }
  std::cin.ignore();
  std::cin.get();
  return 0;
}


Casting out nines

Task   (in three parts):

;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.

Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.

With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.

;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.

Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.

Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]

Solution:
// Casting Out Nines
//
// Nigel Galloway. June 24th., 2012
//
#include <iostream>
int main() {
	int Base = 10;
	const int N = 2;
	int c1 = 0;
	int c2 = 0;
	for (int k=1; k<pow((double)Base,N); k++){
		c1++;
		if (k%(Base-1) == (k*k)%(Base-1)){
			c2++;
			std::cout << k << " ";
		}
	}
	std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 - ((double)c2/c1)*100 << "%" <<std::endl;
	return 0;
}


Catalan numbers/Pascal's triangle

Print out the first   '''15'''   Catalan numbers by extracting them from Pascal's triangle.

;See:
*   Catalan Numbers and the Pascal Triangle.      This method enables calculation of Catalan Numbers using only addition and subtraction.

*   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
*   Sequence A000108 on OEIS has a lot of information on Catalan Numbers.

;Related Tasks:
[[Pascal's triangle]]

Solution:
// Generate Catalan Numbers
//
// Nigel Galloway: June 9th., 2012
//
#include <iostream>
int main() {
  const int N = 15;
  int t[N+2] = {0,1};
  for(int i = 1; i<=N; i++){
    for(int j = i; j>1; j--) t[j] = t[j] + t[j-1];
    t[i+1] = t[i];
    for(int j = i+1; j>1; j--) t[j] = t[j] + t[j-1];
    std::cout << t[i+1] - t[i] << " ";
  }
  return 0;
}


Catamorphism

''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.

;Task:
Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.

;See also:
* Wikipedia article:   Fold
* Wikipedia article:   Catamorphism

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

int main() {
	std::vector<int> nums = { 1, 2, 3, 4, 5 };
	auto nums_added = std::accumulate(std::begin(nums), std::end(nums), 0, std::plus<int>());
	auto nums_other = std::accumulate(std::begin(nums), std::end(nums), 0, [](const int& a, const int& b) {
		return a + 2 * b;
	});
	std::cout << "nums_added: " << nums_added << std::endl;
	std::cout << "nums_other: " << nums_other << std::endl;
}


Chaocipher

Description:
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.

The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.

;Task:
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.

Solution:
#include <iostream>

enum class Mode {
    ENCRYPT,
    DECRYPT,
};

const std::string L_ALPHABET = "HXUCZVAMDSLKPEFJRIGTWOBNYQ";
const std::string R_ALPHABET = "PTLNBQDEOYSFAVZKGJRIHWXUMC";

std::string exec(std::string text, Mode mode, bool showSteps = false) {
    auto left = L_ALPHABET;
    auto right = R_ALPHABET;
    auto eText = new char[text.size() + 1];
    auto temp = new char[27];

    memset(eText, 0, text.size() + 1);
    memset(temp, 0, 27);

    for (size_t i = 0; i < text.size(); i++) {
        if (showSteps) std::cout << left << ' ' << right << '\n';
        size_t index;
        if (mode == Mode::ENCRYPT) {
            index = right.find(text[i]);
            eText[i] = left[index];
        } else {
            index = left.find(text[i]);
            eText[i] = right[index];
        }
        if (i == text.size() - 1) break;

        // permute left

        for (int j = index; j < 26; ++j) temp[j - index] = left[j];
        for (int j = 0; j < index; ++j) temp[26 - index + j] = left[j];
        auto store = temp[1];
        for (int j = 2; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        left = temp;

        // permurte right

        for (int j = index; j < 26; ++j) temp[j - index] = right[j];
        for (int j = 0; j < index; ++j) temp[26 - index + j] = right[j];
        store = temp[0];
        for (int j = 1; j < 26; ++j) temp[j - 1] = temp[j];
        temp[25] = store;
        store = temp[2];
        for (int j = 3; j < 14; ++j) temp[j - 1] = temp[j];
        temp[13] = store;
        right = temp;
    }

    return eText;
}

int main() {
    auto plainText = "WELLDONEISBETTERTHANWELLSAID";
    std::cout << "The original plaintext is : " << plainText << "\n\n";
    std::cout << "The left and right alphabets after each permutation during encryption are :\n";
    auto cipherText = exec(plainText, Mode::ENCRYPT, true);
    std::cout << "\nThe ciphertext is : " << cipherText << '\n';
    auto plainText2 = exec(cipherText, Mode::DECRYPT);
    std::cout << "\nThe recovered plaintext is : " << plainText2 << '\n';

    return 0;
}


Chaos game

The Chaos Game is a method of generating the attractor of an iterated function system (IFS).

One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.

;Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random.

After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.

;See also
* The Game of Chaos

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

const int BMP_SIZE = 600;

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;
};
class chaos {
public:
    void start() {
        POINT org;
        fillPts(); initialPoint( org ); initColors();
        int cnt = 0, i;
        bmp.create( BMP_SIZE, BMP_SIZE );
        bmp.clear( 255 );

        while( cnt++ < 1000000 ) {
            switch( rand() % 6 ) {
                case 0: case 3: i = 0; break;
                case 1: case 5: i = 1; break;
                case 2: case 4: i = 2;
            }
            setPoint( org, myPoints[i], i );
        }
        // --- edit this path --- //
        bmp.saveBitmap( "F:/st.bmp" );
    }
private:
    void setPoint( POINT &o, POINT v, int i ) {
        POINT z;
        o.x = ( o.x + v.x ) >> 1; o.y = ( o.y + v.y ) >> 1;
        SetPixel( bmp.getDC(), o.x, o.y, colors[i] );
    }
    void fillPts() {
        int a = BMP_SIZE - 1;
        myPoints[0].x = BMP_SIZE >> 1; myPoints[0].y = 0;
        myPoints[1].x = 0; myPoints[1].y = myPoints[2].x = myPoints[2].y = a;
    }
    void initialPoint( POINT& p ) {
        p.x = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );
        p.y = ( BMP_SIZE >> 1 ) + rand() % 2 ? rand() % 30 + 10 : -( rand() % 30 + 10 );
    }
    void initColors() {
        colors[0] = RGB( 255, 0, 0 );
        colors[1] = RGB( 0, 255, 0 );
        colors[2] = RGB( 0, 0, 255 );
    }

    myBitmap bmp;
    POINT myPoints[3];
    COLORREF colors[3];
};
int main( int argc, char* argv[] ) {
    srand( ( unsigned )time( 0 ) );
    chaos c; c.start();
    return 0;
}


Check output device is a terminal

Demonstrate how to check whether the output device is a terminal or not.

;Related task:
*   [[Check input device is a terminal]]

Solution:
#if _WIN32
#include <io.h>
#define ISATTY _isatty
#define FILENO _fileno
#else
#include <unistd.h>
#define ISATTY isatty
#define FILENO fileno
#endif

#include <iostream>

int main() {
    if (ISATTY(FILENO(stdout))) {
        std::cout << "stdout is a tty\n";
    } else {
        std::cout << "stdout is not a tty\n";
    }

    return 0;
}