Library: LibXML
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>

#ifndef LIBXML_TREE_ENABLED
#   error libxml was not configured with DOM tree support
#endif

#ifndef LIBXML_OUTPUT_ENABLED
#   error libxml was not configured with serialization support
#endif

// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
//   1) a ScopeGuard-like type to handle cleanup functions; and
//   2) an exception type that transforms the library's errors.

// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
    // C++20: Constructor can (and should) be [[nodiscard]].
    /*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
        f_{std::move(f)}
    {}

    ~scope_exit()
    {
        f_();
    }

    // Non-copyable, non-movable.
    scope_exit(scope_exit const&) = delete;
    scope_exit(scope_exit&&) = delete;
    auto operator=(scope_exit const&) -> scope_exit& = delete;
    auto operator=(scope_exit&&) -> scope_exit& = delete;

private:
    F f_;
};

// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
    libxml_error() : libxml_error(std::string{}) {}

    explicit libxml_error(std::string message) :
        std::runtime_error{make_message_(std::move(message))}
    {}

private:
    static auto make_message_(std::string message) -> std::string
    {
        if (auto const last_error = ::xmlGetLastError(); last_error)
        {
            if (not message.empty())
                message += ": ";
            message += last_error->message;
        }

        return message;
    }
};

auto add_text(::xmlNode* node, ::xmlChar const* content)
{
    // Create a new text node with the desired content.
    auto const text_node = ::xmlNewText(content);
    if (not text_node)
        throw libxml_error{"failed to create text node"};

    // Try to add it to the node. If it succeeds, that node will take
    // ownership of the text node. If it fails, we have to clean up the text
    // node ourselves first, then we can throw.
    if (auto const res = ::xmlAddChild(node, text_node); not res)
    {
        ::xmlFreeNode(text_node);
        throw libxml_error{"failed to add text node"};
    }

    return text_node;
}

auto main() -> int
{
    // Set this to true if you don't want the XML declaration.
    constexpr auto no_xml_declaration = false;

    try
    {
        // Initialize libxml.
        ::xmlInitParser();
        LIBXML_TEST_VERSION
        auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};

        // Create a new document.
        auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
        if (not doc)
            throw libxml_error{"failed to create document"};
        auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};

        // Create the root element.
        auto root = ::xmlNewNode(nullptr,
            reinterpret_cast<::xmlChar const*>(u8"root"));
        if (not root)
            throw libxml_error{"failed to create root element"};
        ::xmlDocSetRootElement(doc, root); // doc now owns root

        // Add whitespace. Unless you know the whitespace is not significant,
        // you should do this manually, rather than relying on automatic
        // indenting.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n    "));

        // Add the child element.
        if (auto const res = ::xmlNewTextChild(root, nullptr,
                reinterpret_cast<::xmlChar const*>(u8"element"),
                reinterpret_cast<::xmlChar const*>(
                    u8"\n        Some text here\n    "));
                not res)
            throw libxml_error{"failed to create child text element"};

        // Add whitespace.
        add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));

        // Output tree. Note that the output is UTF-8 in all cases. If you
        // want something different, use xmlSaveFileEnc() or the second
        // argument of xmlSaveDoc().
        if constexpr (no_xml_declaration)
        {
            auto const save_context = ::xmlSaveToFilename("-", nullptr,
                XML_SAVE_NO_DECL);
            auto const save_context_cleanup = scope_exit{[save_context] {
                ::xmlSaveClose(save_context); }};

            if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
        else
        {
            if (auto const res = ::xmlSaveFile("-", doc); res == -1)
                throw libxml_error{"failed to write tree to stdout"};
        }
    }
    catch (std::exception const& x)
    {
        std::cerr << "ERROR: " << x.what() << '\n';
        return EXIT_FAILURE;
    }
}

Create a simple DOM and serialize it into the specified XML format.


#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main( ) {
   boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
   std::cout << to_simple_string( t ) << std::endl ;
   return 0 ;
}

#include <chrono>
#include <ctime> //for conversion std::ctime()
#include <iostream>

int main() {
    auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    std::cout << std::ctime(&timenow) << std::endl;
}

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The code is related to the task of date formatting and is compiled under Linux using g++ with the boost_date_time library.


#include <numeric>
#include <cctype>
#include <iostream>
#include <string>

template<typename result_sink_t>
auto sedol_checksum(std::string const& sedol, result_sink_t result_sink)
{
    if(sedol.size() != 6)
        return result_sink(0, "length of sedol string != 6");

    const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789";
    if(sedol.find_first_not_of(valid_chars) != std::string::npos)
        return result_sink(0, "sedol string contains disallowed characters");

    const int weights[] = {1,3,1,7,3,9};
    auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0
                                           , [](int acc, int prod){ return acc + prod; }
                                           , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; }
                                             );
    return result_sink((10 - (weighted_sum % 10)) % 10, nullptr);
}

int main()
{
    using namespace std;
    string inputs[] = {
       "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
       "557910", "B0YBKR", "585284", "B0YBKT", "B00030"
   };
   for(auto const & sedol : inputs)
   {
        sedol_checksum(sedol, [&](auto sum, char const * errorMessage)
        {
            if(errorMessage)
                cout << "error for sedol: " << sedol << " message: " <<  errorMessage << "\n";
            else
                cout << sedol << sum << "\n";
        });
   }
   return 0;
}

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


Library: Qt
// Based on https://www.cairographics.org/samples/gradient/

#include <QImage>
#include <QPainter>

int main() {
    const QColor black(0, 0, 0);
    const QColor white(255, 255, 255);

    const int size = 300;
    const double diameter = 0.6 * size;

    QImage image(size, size, QImage::Format_RGB32);
    QPainter painter(&image);
    painter.setRenderHint(QPainter::Antialiasing);

    QLinearGradient linearGradient(0, 0, 0, size);
    linearGradient.setColorAt(0, white);
    linearGradient.setColorAt(1, black);

    QBrush brush(linearGradient);
    painter.fillRect(QRect(0, 0, size, size), brush);

    QPointF point1(0.4 * size, 0.4 * size);
    QPointF point2(0.45 * size, 0.4 * size);
    QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);
    radialGradient.setColorAt(0, white);
    radialGradient.setColorAt(1, black);

    QBrush brush2(radialGradient);
    painter.setPen(Qt::NoPen);
    painter.setBrush(brush2);
    painter.drawEllipse(QRectF((size - diameter)/2, (size - diameter)/2, diameter, diameter));

    image.save("sphere.png");
    return 0;
}

represent the functionality to draw a sphere either graphically or in ASCII art, with the option for static or rotational projection, depending on the language capabilities.


#include <string>
#include <iostream>

using namespace std;

string Suffix(int num)
{
    switch (num % 10)
    {
        case 1 : if(num % 100 != 11) return "st";
           break;
        case 2 : if(num % 100 != 12) return "nd";
           break;
        case 3 : if(num % 100 != 13) return "rd";
    }

    return "th";
}

int main()
{
    cout << "Set [0,25]:" << endl;
    for (int i = 0; i < 26; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    cout << "Set [250,265]:" << endl;
    for (int i = 250; i < 266; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    cout << "Set [1000,1025]:" << endl;
    for (int i = 1000; i < 1026; i++)
        cout << i << Suffix(i) << " ";

    cout << endl;

    return 0;
}

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


Works with: C++11
#include <algorithm>
#include <iostream>
#include <string>

std::string stripchars(std::string str, const std::string &chars)
{
    str.erase(
        std::remove_if(str.begin(), str.end(), [&](char c){
            return chars.find(c) != std::string::npos;
        }),
        str.end()
    );
    return str;
}

int main()
{
    std::cout << stripchars("She was a soul stripper. She took my heart!", "aei") << '\n';
    return 0;
}

"Function to remove specific characters from a given string"


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

class pair  {
public:
    pair( int s, std::string z )            { p = std::make_pair( s, z ); }
    bool operator < ( const pair& o ) const { return i() < o.i(); }
    int i() const                           { return p.first; }
    std::string s() const                   { return p.second; }
private:
    std::pair<int, std::string> p;
};
void gFizzBuzz( int c, std::vector<pair>& v ) {
    bool output;
    for( int x = 1; x <= c; x++ ) {
        output = false;
        for( std::vector<pair>::iterator i = v.begin(); i != v.end(); i++ ) {
            if( !( x % ( *i ).i() ) ) {
                std::cout << ( *i ).s();
                output = true;
            }
        }
        if( !output ) std::cout << x;
        std::cout << "\n";
    }
}
int main( int argc, char* argv[] ) {
    std::vector<pair> v;
    v.push_back( pair( 7, "Baxx" ) );
    v.push_back( pair( 3, "Fizz" ) );
    v.push_back( pair( 5, "Buzz" ) );
    std::sort( v.begin(), v.end() );
    gFizzBuzz( 20, v );
    return 0;
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


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

int main( ) {
   std::vector<std::string> myStrings { "prepended to" , "my string" } ;
   std::string prepended = std::accumulate( myStrings.begin( ) ,
	 myStrings.end( ) , std::string( "" ) , []( std::string a ,
	    std::string b ) { return a + b ; } ) ;
   std::cout << prepended << std::endl ;
   return 0 ;
}

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


#include <windows.h>
#include <iostream>

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

//-----------------------------------------------------------------------------------------
const int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;

//-----------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}
    ~myBitmap()
    {
	DeleteObject( pen ); DeleteObject( brush );
	DeleteDC( hdc ); DeleteObject( bmp );
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	delete [] dwpBits;
    }

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

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

    HBITMAP bmp;
    HDC     hdc;
    HPEN    pen;
    HBRUSH  brush;
    void    *pBits;
    int     width, height, wid;
    DWORD   clr;
};
//-----------------------------------------------------------------------------------------
class dragonC
{
public:
    dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }
    void draw( int iterations ) { generate( iterations ); draw(); }

private:
    void generate( int it )
    {
	generator.push_back( 1 );
	string temp;

	for( int y = 0; y < it - 1; y++ )
	{
	    temp = generator; temp.push_back( 1 );
	    for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )
		temp.push_back( !( *x ) );

	    generator = temp;
	}
    }

    void draw()
    {
	HDC dc = bmp.getDC();
	unsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };
	int mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;

	for( int t = 0; t < 4; t++ )
	{
	    int a = BMP_SIZE / 2, b = a; a += mov[i++]; b += mov[i++];
	    MoveToEx( dc, a, b, NULL );

	    bmp.setPenColor( clr[t] );
	    for( string::iterator x = generator.begin(); x < generator.end(); x++ )
	    {
		switch( dir )
		{
		    case NORTH:
			if( *x ) { a += LEN; dir = EAST; }
			else { a -= LEN; dir = WEST; }
		    break;
		    case EAST:
			if( *x ) { b += LEN; dir = SOUTH; }
			else { b -= LEN; dir = NORTH; }
		    break;
		    case SOUTH:
			if( *x ) { a -= LEN; dir = WEST; }
			else { a += LEN; dir = EAST; }
		    break;
		    case WEST:
			if( *x ) { b -= LEN; dir = NORTH; }
			else { b += LEN; dir = SOUTH; }
		}
	        LineTo( dc, a, b );
	    }
	}
	// !!! change this path !!!
	bmp.saveBitmap( "f:/rc/dragonCpp.bmp" );
    }

    int dir;
    myBitmap bmp;
    string generator;
};
//-----------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    dragonC d; d.draw( 17 );
    return system( "pause" );
}
//-----------------------------------------------------------------------------------------

The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms including recursive, successive approximation, iterative, and absolute direction methods. The code also includes functionality for calculating absolute X,Y coordinates of a point, testing whether a given X,Y point or segment is on the curve, and generating the curve as a Lindenmayer system of expansions. The generated curve is then saved to the hard drive.


#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    srand(time(0));
    int n = 1 + (rand() % 10);
    int g;
    std::cout << "I'm thinking of a number between 1 and 10.\nTry to guess it! ";
    while(true)
    {
        std::cin >> g;
        if (g == n)
            break;
        else
            std::cout << "That's not my number.\nTry another guess! ";
    }
    std::cout << "You've guessed my number!";
    return 0;
}

"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing."


Works with: C++11
#include <string>
#include <numeric>

int main() {
    std::string lower(26,' ');

    std::iota(lower.begin(), lower.end(), 'a');
}

generate an array, list, or string of all lower case ASCII characters from 'a' to 'z' using a reliable coding style and strong typing. The codes also demonstrate how to access a similar sequence from the standard library if it exists. The approach avoids manually enumerating all lowercase characters to prevent bugs. The functionality can be implemented identically in C and C++ or using a STL function in C++.


#include <bitset>
#include <iostream>
#include <limits>
#include <string>

void print_bin(unsigned int n) {
  std::string str = "0";

  if (n > 0) {
    str = std::bitset<std::numeric_limits<unsigned int>::digits>(n).to_string();
    str = str.substr(str.find('1')); // remove leading zeros
  }

  std::cout << str << '\n';
}

int main() {
  print_bin(0);
  print_bin(5);
  print_bin(50);
  print_bin(9000);
}

The code takes a non-negative integer as input and generates a sequence of binary digits corresponding to the input integer. It can use built-in radix functions or a user-defined function for this conversion. The output is a string of binary digits followed by a newline, without any leading zeros, whitespace, radix, or sign markers. The code also includes a shorter version using a bitset and the '>>' operator, and another version using bitwise operations with recursion.


#include <iostream>
#include <optional>
#include <ranges>
#include <string>
#include <vector>

using namespace std;

struct Patient
{
    string ID;
    string LastName;
};

struct Visit
{
    string PatientID;
    string Date;
    optional<float> Score;
};

int main(void)
{
    auto patients = vector<Patient> {
        {"1001", "Hopper"},
        {"4004", "Wirth"},
        {"3003", "Kemeny"},
        {"2002", "Gosling"},
        {"5005", "Kurtz"}};

    auto visits = vector<Visit> {
        {"2002", "2020-09-10", 6.8},
        {"1001", "2020-09-17", 5.5},
        {"4004", "2020-09-24", 8.4},
        {"2002", "2020-10-08", },
        {"1001", ""          , 6.6},
        {"3003", "2020-11-12", },
        {"4004", "2020-11-05", 7.0},
        {"1001", "2020-11-19", 5.3}};

    // sort the patients by ID
    sort(patients.begin(), patients.end(),
         [](const auto& a, const auto&b){ return a.ID < b.ID;});

    cout << "| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\n";
    for(const auto& patient : patients)
    {
        // loop over all of the patients and determine the fields
        string lastVisit;
        float sum = 0;
        int numScores = 0;

        // use C++20 ranges to filter the visits by patients
        auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};
        for(const auto& visit : visits | views::filter( patientFilter ))
        {
            if(visit.Score)
            {
                sum += *visit.Score;
                numScores++;
            }
            lastVisit = max(lastVisit, visit.Date);
        }

        // format the output
        cout << "|       " << patient.ID << " | ";
        cout.width(8); cout << patient.LastName << " | ";
        cout.width(10); cout << lastVisit << " | ";
        if(numScores > 0)
        {
            cout.width(9); cout << sum << " | ";
            cout.width(9); cout << (sum / float(numScores));
        }
        else cout << "          |          ";
        cout << " |\n";
    }
}

"Merge and aggregate two provided .csv datasets into a new dataset. The data is grouped by patient id and last name, with calculations for the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in-memory or written to a file. The code is particularly suitable for data science and data processing programming languages like F#, Python, R, SPSS, MATLAB etc. and utilizes C++20."


Library: Boost
Works with: Visual Studio version  2005

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/case_conv.hpp>
using namespace std;
using namespace boost;

typedef boost::tokenizer<boost::char_separator<char> > Tokenizer;
static const char_separator<char> sep(" ","#;,");

//Assume that the config file represent a struct containing all the parameters to load
struct configs{
	string fullname;
	string favoritefruit;
	bool needspelling;
	bool seedsremoved;
	vector<string> otherfamily;
} conf;

void parseLine(const string &line, configs &conf)
{
	if (line[0] == '#' || line.empty())
		return;
	Tokenizer tokenizer(line, sep);
	vector<string> tokens;
	for (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)
		tokens.push_back(*iter);
	if (tokens[0] == ";"){
		algorithm::to_lower(tokens[1]);
		if (tokens[1] == "needspeeling")
			conf.needspelling = false;
		if (tokens[1] == "seedsremoved")
			conf.seedsremoved = false;
	}
	algorithm::to_lower(tokens[0]);
	if (tokens[0] == "needspeeling")
		conf.needspelling = true;
	if (tokens[0] == "seedsremoved")
		conf.seedsremoved = true;
	if (tokens[0] == "fullname"){
		for (unsigned int i=1; i<tokens.size(); i++)
			conf.fullname += tokens[i] + " ";
		conf.fullname.erase(conf.fullname.size() -1, 1);
	}
	if (tokens[0] == "favouritefruit")
		for (unsigned int i=1; i<tokens.size(); i++)
			conf.favoritefruit += tokens[i];
	if (tokens[0] == "otherfamily"){
		unsigned int i=1;
		string tmp;
		while (i<=tokens.size()){
			if ( i == tokens.size() || tokens[i] ==","){
				tmp.erase(tmp.size()-1, 1);
				conf.otherfamily.push_back(tmp);
				tmp = "";
				i++;
			}
			else{
				tmp += tokens[i];
				tmp += " ";
				i++;
			}
		}
	}
}

int _tmain(int argc, TCHAR* argv[])
{
	if (argc != 2)
	{
		wstring tmp = argv[0];
		wcout << L"Usage: " << tmp << L" <configfile.ini>" << endl;
		return -1;
	}
	ifstream file (argv[1]);

	if (file.is_open())
		while(file.good())
		{
			char line[255];
			file.getline(line, 255);
			string linestring(line);
			parseLine(linestring, conf);
		}
	else
	{
		cout << "Unable to open the file" << endl;
		return -2;
	}

	cout << "Fullname= " << conf.fullname << endl;
	cout << "Favorite Fruit= " << conf.favoritefruit << endl;
	cout << "Need Spelling= " << (conf.needspelling?"True":"False") << endl;
	cout << "Seed Removed= " << (conf.seedsremoved?"True":"False") << endl;
	string otherFamily;
	for (unsigned int i = 0; i < conf.otherfamily.size(); i++)
		otherFamily += conf.otherfamily[i] + ", ";
	otherFamily.erase(otherFamily.size()-2, 2);
	cout << "Other Family= " << otherFamily << endl;

	return 0;
}

The code reads a standard configuration file, ignoring lines starting with a hash or semicolon and blank lines. It sets variables based on the configuration entries, treating configuration option names as case insensitive and configuration parameter data as case sensitive. It supports optional equal signs to separate configuration parameter data from the option name and allows multiple parameters separated by commas for a configuration option. The code sets four variables: fullname, favouritefruit, needspeeling, and seedsremoved, and stores multiple parameters in an array. The solution doesn't use Boost libraries and is not optimized.


#define _USE_MATH_DEFINES

#include <math.h>
#include <iostream>

const static double EarthRadiusKm = 6372.8;

inline double DegreeToRadian(double angle)
{
	return M_PI * angle / 180.0;
}

class Coordinate
{
public:
	Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude)
	{}

	double Latitude() const
	{
		return myLatitude;
	}

	double Longitude() const
	{
		return myLongitude;
	}

private:

	double myLatitude;
	double myLongitude;
};

double HaversineDistance(const Coordinate& p1, const Coordinate& p2)
{
	double latRad1 = DegreeToRadian(p1.Latitude());
	double latRad2 = DegreeToRadian(p2.Latitude());
	double lonRad1 = DegreeToRadian(p1.Longitude());
	double lonRad2 = DegreeToRadian(p2.Longitude());

	double diffLa = latRad2 - latRad1;
	double doffLo = lonRad2 - lonRad1;

	double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2)));
	return 2 * EarthRadiusKm * computation;
}

int main()
{
	Coordinate c1(36.12, -86.67);
	Coordinate c2(33.94, -118.4);

	std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl;
	return 0;
}

Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.


#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>

int main() {
	WSADATA wsaData;
	WSAStartup( MAKEWORD( 2, 2 ), &wsaData );

	addrinfo *result = NULL;
	addrinfo hints;

	ZeroMemory( &hints, sizeof( hints ) );
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	getaddrinfo( "74.125.45.100", "80", &hints, &result ); // http://www.google.com

	SOCKET s = socket( result->ai_family, result->ai_socktype, result->ai_protocol );

	connect( s, result->ai_addr, (int)result->ai_addrlen );

	freeaddrinfo( result );

	send( s, "GET / HTTP/1.0\n\n", 16, 0 );

	char buffer[512];
	int bytes;

	do {
		bytes = recv( s, buffer, 512, 0 );

		if ( bytes > 0 )
			std::cout.write(buffer, bytes);
	} while ( bytes > 0 );

	return 0;
}

Library: U++
#include <Web/Web.h>

using namespace Upp;

CONSOLE_APP_MAIN
{
	Cout() << HttpClient("www.rosettacode.org").ExecuteRedirect();
}

Print the content of a specified URL to the console using HTTP request.


#include <iostream>
using namespace std;

int toInt(const char c)
{
    return c-'0';
}

int confirm( const char *id)
{
    bool is_odd_dgt = true;
    int s = 0;
    const char *cp;

    for(cp=id; *cp; cp++);
    while(cp > id) {
        --cp;
        int k = toInt(*cp);
        if (is_odd_dgt) {
            s += k;
        }
        else {
            s += (k!=9)? (2*k)%9 : 9;
        }
	is_odd_dgt = !is_odd_dgt;
    }
    return 0 == s%10;
}

int main( )
{
    const char * t_cases[] = {
        "49927398716",
        "49927398717",
        "1234567812345678",
        "1234567812345670",
        NULL,
    };
    for ( const char **cp = t_cases; *cp; cp++) {
        cout << *cp << ": " << confirm(*cp) << endl;
    }
    return 0;
}

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool luhn( const string& id)
{
  static const int m[10]  = {0,2,4,6,8,1,3,5,7,9}; // mapping for rule 3
  bool is_odd_dgt = false;
  auto lambda = [&](int a, char c) {return a + ((is_odd_dgt = !is_odd_dgt) ? c-'0' : m[c-'0']);};
  int s = std::accumulate(id.rbegin(), id.rend(), 0, lambda);
  return 0 == s%10;
}

int main( )
{
  auto t_cases = {"49927398716", "49927398717", "1234567812345678", "1234567812345670"};
  auto print = [](const string & s) {cout << s << ": " << luhn(s) << endl;};
  for_each(t_cases.begin(), t_cases.end(), print);
  return 0;
}

#include <iostream>
#include <type_traits>

template<size_t I, int... Args>
struct find_impl;

template<int A, int... Args>
struct find_impl<0, A, Args...> {
    using type = std::integral_constant<int, A>;
};

template<int A, int B, int... Args>
struct find_impl<0, A, B, Args...> {
    using type = std::integral_constant<int, A>;
};

template<size_t I, int A, int B, int... Args>
struct find_impl<I, A, B, Args...> {
    using type = typename find_impl<I-1, B, Args...>::type;
};

namespace detail {
template<typename, typename>
struct append_sequence
{};

template<typename T, typename... Ts>
struct append_sequence<T, std::tuple<Ts...>> {
    using type = std::tuple<Ts..., T>;
};

template<typename... Ts>
struct reverse_sequence {
    using type = std::tuple<>;
};

template<typename T, typename... Ts>
struct reverse_sequence<T, Ts...> {
    using type = typename append_sequence<
                            T,
                            typename reverse_sequence<Ts...>::type
                        >::type;
};
}

template<size_t I>
using rule3 = typename find_impl<I, 0, 2, 4, 6, 8, 1, 3, 5, 7, 9>::type;

template<int A, char C, bool dgt>
struct calc
    : std::integral_constant<int, A + C - '0'>
{};

template<int A, char C>
struct calc<A, C, false>
    : std::integral_constant<int, A + rule3<C - '0'>::type::value>
{};

template<typename Acc, bool Dgt, char...>
struct luhn_impl;

template<typename Acc, bool Dgt, char A, char... Args>
struct luhn_impl<Acc, Dgt, A, Args...> {
    using type = typename calc<Acc::value, A, Dgt>::type;
};

template<typename Acc, bool Dgt, char A, char B, char... Args>
struct luhn_impl<Acc, Dgt, A, B, Args...> {
    using type =
        typename luhn_impl<typename calc<Acc::value, A, Dgt>::type, !Dgt, B, Args...>::type;
};

template<typename>
struct luhn;

template<typename... Args>
struct luhn<std::tuple<Args...>> {
    using type = typename luhn_impl<std::integral_constant<int, 0>, true, Args::value...>::type;
    constexpr static bool result = (type::value % 10) == 0;
};

template<char... Args>
bool operator "" _luhn() {
    return luhn<typename detail::reverse_sequence<std::integral_constant<char, Args>...>::type>::result;
}

int main() {
    std::cout << std::boolalpha;
    std::cout << 49927398716_luhn << std::endl;
    std::cout << 49927398717_luhn << std::endl;
    std::cout << 1234567812345678_luhn << std::endl;
    std::cout << 1234567812345670_luhn << std::endl;
    return 0;
}

true
false
false
true

The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number. Then, it forms a partial sum (s1) by summing the first, third, and every other odd digit in the reversed digits. For the even digits in the reversed number, it multiplies each digit by two and sums the digits if the result is greater than nine to form partial sums. It then sums these partial sums to form another sum (s2). If the total sum of s1 and s2 ends in zero, the original number is a valid credit card number. The code performs this validation for the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670. It can also be implemented at compile-time using metaprogramming.


#include <iostream>
#include <vector>

//--------------------------------------------------------------------------------------------------
using namespace std;
typedef unsigned long long bigint;

//--------------------------------------------------------------------------------------------------
class josephus
{
public:
    bigint findSurvivors( bigint n, bigint k, bigint s = 0 )
    {
	bigint i = s + 1;
	for( bigint x = i; x <= n; x++, i++ )
	    s = ( s + k ) % i;

	return s;
    }

    void getExecutionList( bigint n, bigint k, bigint s = 1 )
    {
	cout << endl << endl << "Execution list: " << endl;

	prisoners.clear();
	for( bigint x = 0; x < n; x++ )
	    prisoners.push_back( x );

	bigint index = 0;
	while( prisoners.size() > s )
	{
	    index += k - 1;
	    if( index >= prisoners.size() ) index %= prisoners.size();
	    cout << prisoners[static_cast<unsigned int>( index )] << ", ";

	    vector<bigint>::iterator it = prisoners.begin() + static_cast<unsigned int>( index );
	    prisoners.erase( it );
	}
    }

private:
    vector<bigint> prisoners;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
    josephus jo;
    bigint n, k, s;
    while( true )
    {
	system( "cls" );
	cout << "Number of prisoners( 0 to QUIT ): "; cin >> n;
	if( !n ) return 0;
	cout << "Execution step: "; cin >> k;
	cout << "How many survivors: "; cin >> s;

	cout << endl << "Survivor";
	if( s == 1 )
	{
	    cout << ": " << jo.findSurvivors( n, k );
	    jo.getExecutionList( n, k );
	}
	else
	{
	    cout << "s: ";
	    for( bigint x = 0; x < s; x++ )
		cout << jo.findSurvivors( n, k, x ) << ", ";

	    jo.getExecutionList( n, k, s );
	}

	cout << endl << endl;
	system( "pause" );
    }
    return 0;
}
//--------------------------------------------------------------------------------------------------

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


#include <string>
#include <iostream>

std::string repeat( const std::string &word, int times ) {
   std::string result ;
   result.reserve(times*word.length()); // avoid repeated reallocation
   for ( int a = 0 ; a < times ; a++ )
      result += word ;
   return result ;
}

int main( ) {
   std::cout << repeat( "Ha" , 5 ) << std::endl ;
   return 0 ;
}

#include <string>
#include <iostream>

int main( ) {
   std::cout << std::string( 5, '*' ) << std::endl ;
   return 0 ;
}

#include <string>
#include <iostream>

std::string repeat( const std::string &word, uint times ) {
  return
    times == 0 ? "" :
    times == 1 ? word :
    times == 2 ? word + word :
    repeat(repeat(word, times / 2), 2) +
    repeat(word, times % 2);
}

int main( ) {
   std::cout << repeat( "Ha" , 5 ) << std::endl ;
   return 0 ;
}

"Implements a function to repeat a given string or a single character a specified number of times."


Works with: g++ version 4.0.2 (may need to be retested?)

#include <iostream>
#include <string>
#include <iterator>
#include <regex>

int main()
{
  std::regex re(".* string$");
  std::string s = "Hi, I am a string";

  // match the complete string
  if (std::regex_match(s, re))
    std::cout << "The string matches.\n";
  else
    std::cout << "Oops - not found?\n";

  // match a substring
  std::regex re2(" a.*a");
  std::smatch match;
  if (std::regex_search(s, match, re2))
  {
    std::cout << "Matched " << match.length()
              << " characters starting at " << match.position() << ".\n";
    std::cout << "Matched character sequence: \""
              << match.str() << "\"\n";
  }
  else
  {
    std::cout << "Oops - not found?\n";
  }

  // replace a substring
  std::string dest_string;
  std::regex_replace(std::back_inserter(dest_string),
                       s.begin(), s.end(),
                       re2,
                       "'m now a changed");
  std::cout << dest_string << std::endl;
}

utilize Boost's Regex library to match a string against a regular expression and substitute part of the string using a regular expression in standards earlier than C++11.


#include <iostream>

int main()
{
  int a, b;
  std::cin >> a >> b;
  std::cout << "a+b = " << a+b << "\n";
  std::cout << "a-b = " << a-b << "\n";
  std::cout << "a*b = " << a*b << "\n";
  std::cout << "a/b = " << a/b << ", remainder " << a%b << "\n";
  return 0;
}

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


#include <iostream>
#include <string>

// returns count of non-overlapping occurrences of 'sub' in 'str'
int countSubstring(const std::string& str, const std::string& sub)
{
    if (sub.length() == 0) return 0;
    int count = 0;
    for (size_t offset = str.find(sub); offset != std::string::npos;
	 offset = str.find(sub, offset + sub.length()))
    {
        ++count;
    }
    return count;
}

int main()
{
    std::cout << countSubstring("the three truths", "th")    << '\n';
    std::cout << countSubstring("ababababab", "abab")        << '\n';
    std::cout << countSubstring("abaabba*bbaba*bbab", "a*b") << '\n';

    return 0;
}

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


Works with: g++
void move(int n, int from, int to, int via) {
  if (n == 1) {
    std::cout << "Move disk from pole " << from << " to pole " << to << std::endl;
  } else {
    move(n - 1, from, via, to);
    move(1, from, to, via);
    move(n - 1, via, to, from);
  }
}

Works with: Chipmunk Basic version 3.6.4100 cls
110 print "Three disks" : print
120 hanoi(3,1,2,3)
130 print chr$(10)"Four disks" chr$(10)
140 hanoi(4,1,2,3)
150 print : print "Towers of Hanoi puzzle completed!"
160 end
170 sub hanoi(n,desde,hasta,via)
180   if n > 0 then
190     hanoi(n-1,desde,via,hasta)
200     print "Move disk " n "from pole " desde "to pole " hasta
210     hanoi(n-1,via,hasta,desde)
220   endif
230 end sub

"Implement a recursive solution to solve the Towers of Hanoi problem."


double Factorial(double nValue)
   {
       double result = nValue;
       double result_next;
       double pc = nValue;
       do
       {
           result_next = result*(pc-1);
           result = result_next;
           pc--;
       }while(pc>2);
       nValue = result;
       return nValue;
   }

double binomialCoefficient(double n, double k)
   {
       if (abs(n - k) < 1e-7 || k  < 1e-7) return 1.0;
       if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;
       return Factorial(n) /(Factorial(k)*Factorial((n - k)));
   }

int main()
{
    cout<<"The Binomial Coefficient of 5, and 3, is equal to: "<< binomialCoefficient(5,3);
    cin.get();
}

The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of 5 choose 3, which equals 10. It also includes tasks related to combinations and permutations, both with and without replacement.


implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


Library: Qt

#include "animationwidget.h"

#include <QLabel>
#include <QTimer>
#include <QVBoxLayout>

#include <algorithm>

AnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {
    setWindowTitle(tr("Animation"));
    QFont font("Courier", 24);
    QLabel* label = new QLabel("Hello World! ");
    label->setFont(font);
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addWidget(label);
    QTimer* timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [label,this]() {
        QString text = label->text();
        std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());
        label->setText(text);
    });
    timer->start(200);
}

void AnimationWidget::mousePressEvent(QMouseEvent*) {
    right_ = !right_;
}

#ifndef ANIMATIONWIDGET_H
#define ANIMATIONWIDGET_H

#include <QWidget>

class AnimationWidget : public QWidget {
    Q_OBJECT
public:
    AnimationWidget(QWidget *parent = nullptr);
protected:
    void mousePressEvent(QMouseEvent *event) override;
private:
    bool right_ = true;
};

#endif // ANIMATIONWIDGET_H

#include "animationwidget.h"

#include <QApplication>

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    AnimationWidget w;
    w.show();
    return a.exec();
}

create an animated window displaying the string "Hello World!". The animation gives the illusion of the text rotating to the right by periodically moving the last letter to the beginning of the string. The direction of rotation reverses when the user clicks on the text in the window.


int val = 0;
do{
   val++;
   std::cout << val << std::endl;
}while(val % 6 != 0);

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


Works with: ISO C++
Works with: g++ version 4.0.2
#include <string> // (not <string.h>!)
using std::string;

int main()
{
  string s = "Hello, world!";
  string::size_type length = s.length(); // option 1: In Characters/Bytes
  string::size_type size = s.size();     // option 2: In Characters/Bytes
  // In bytes same as above since sizeof(char) == 1
  string::size_type bytes = s.length() * sizeof(string::value_type);
}

#include <string>
using std::wstring;

int main()
{
  wstring s = L"\u304A\u306F\u3088\u3046";
  wstring::size_type length = s.length() * sizeof(wstring::value_type); // in bytes
}

Works with: C++98
Works with: g++ version 4.0.2

#include <string>
using std::wstring;

int main()
{
  wstring s = L"\u304A\u306F\u3088\u3046";
  wstring::size_type length = s.length();
}

Works with: C++11
Works with: clang++ version 3.0
#include <iostream>
#include <codecvt>
int main()
{
    std::string utf8 = "\x7a\xc3\x9f\xe6\xb0\xb4\xf0\x9d\x84\x8b"; // U+007a, U+00df, U+6c34, U+1d10b
    std::cout << "Byte length: " << utf8.size() << '\n';
    std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> conv;
    std::cout << "Character length: " << conv.from_bytes(utf8).size() << '\n';
}

Works with: C++98
Works with: g++ version 4.1.2 20061115 (prerelease) (SUSE Linux)
#include <cwchar>  // for mbstate_t
#include <locale>

// give the character length for a given named locale
std::size_t char_length(std::string const& text, char const* locale_name)
{
  // locales work on pointers; get length and data from string and
  // then don't touch the original string any more, to avoid
  // invalidating the data pointer
  std::size_t len = text.length();
  char const* input = text.data();

  // get the named locale
  std::locale loc(locale_name);

  // get the conversion facet of the locale
  typedef std::codecvt<wchar_t, char, std::mbstate_t> cvt_type;
  cvt_type const& cvt = std::use_facet<cvt_type>(loc);

  // allocate buffer for conversion destination
  std::size_t bufsize = cvt.max_length()*len;
  wchar_t* destbuf = new wchar_t[bufsize];
  wchar_t* dest_end;

  // do the conversion
  mbstate_t state = mbstate_t();
  cvt.in(state, input, input+len, input, destbuf, destbuf+bufsize, dest_end);

  // determine the length of the converted sequence
  std::size_t length = dest_end - destbuf;

  // get rid of the buffer
  delete[] destbuf;

  // return the result
  return length;
}

#include <iostream>

int main()
{
  // Tür (German for door) in UTF8
  std::cout << char_length("\x54\xc3\xbc\x72", "de_DE.utf8") << "\n"; // outputs 3

  // Tür in ISO-8859-1
  std::cout << char_length("\x54\xfc\x72", "de_DE") << "\n"; // outputs 3
}

The code calculates the character and byte length of a string, correctly handling encodings like UTF-8 and UTF-16. It counts individual Unicode code points as characters, not user-visible graphemes or code unit counts. It also correctly handles non-BMP code points. The code can provide the string length in graphemes if the language supports it. It works with both wide and narrow character strings and is not affected by the encoding used for the source code.


Works with: C++11
#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::uniform_int_distribution<long> dist; // long is guaranteed to be 32 bits

    std::cout << "Random Number: " << dist(rd) << std::endl;
}

demonstrate how to generate a non-deterministic, uniformly-distributed 32-bit random number using std::random_device, provided a hardware device is available for generating random numbers. If such a device is not available, a pseudo-random number engine is used instead.


#include <string>
#include <iostream>

int main( ) {
   std::string word( "Premier League" ) ;
   std::cout << "Without first letter: " << word.substr( 1 ) << " !\n" ;
   std::cout << "Without last letter: " << word.substr( 0 , word.length( ) - 1 ) << " !\n" ;
   std::cout << "Without first and last letter: " << word.substr( 1 , word.length( ) - 2 ) << " !\n" ;
   return 0 ;
}

Without first letter: remier League !
Without last letter: Premier Leagu !
Without first and last letter: remier Leagu !

demonstrate how to remove the first, last, or both first and last characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The program does not support other encodings like 8-bit ASCII or EUC-JP.


Works with: Windows version 2000 or later

#include <afx.h>

HANDLE mutex;

mutex = CreateMutex( NULL, TRUE, "MyApp" );
if ( GetLastError() == ERROR_ALREADY_EXISTS )
{
     // There's another instance running.  What do you do?
}

CloseHandle( mutex );

The code checks if an instance of an application is already running. If so, it displays a message and exits. A HANDLE type variable is initialized at the start of the program to perform this check. Finally, the mutex is closed at the end of the program.


#include <iostream>
using namespace std;

class SudokuSolver {
private:
    int grid[81];

public:

    SudokuSolver(string s) {
        for (unsigned int i = 0; i < s.length(); i++) {
            grid[i] = (int) (s[i] - '0');
        }
    }

    void solve() {
        try {
            placeNumber(0);
            cout << "Unsolvable!" << endl;
        } catch (char* ex) {
            cout << ex << endl;
            cout << this->toString() << endl;
        }
    }

    void placeNumber(int pos) {
        if (pos == 81) {
            throw (char*) "Finished!";
        }
        if (grid[pos] > 0) {
            placeNumber(pos + 1);
            return;
        }
        for (int n = 1; n <= 9; n++) {
            if (checkValidity(n, pos % 9, pos / 9)) {
                grid[pos] = n;
                placeNumber(pos + 1);
                grid[pos] = 0;
            }
        }
    }

    bool checkValidity(int val, int x, int y) {
        for (int i = 0; i < 9; i++) {
            if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
                return false;
        }
        int startX = (x / 3) * 3;
        int startY = (y / 3) * 3;
        for (int i = startY; i < startY + 3; i++) {
            for (int j = startX; j < startX + 3; j++) {
                if (grid[i * 9 + j] == val)
                    return false;
            }
        }
        return true;
    }

    string toString() {
        string sb;
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                char c[2];
                c[0] = grid[i * 9 + j] + '0';
                c[1] = '\0';
                sb.append(c);
                sb.append(" ");
                if (j == 2 || j == 5)
                    sb.append("| ");
            }
            sb.append("\n");
            if (i == 2 || i == 5)
                sb.append("------+-------+------\n");
        }
        return sb;
    }

};

int main() {
    SudokuSolver ss("850002400"
                    "720000009"
                    "004000000"
                    "000107002"
                    "305000900"
                    "040000000"
                    "000080070"
                    "017000000"
                    "000036040");
    ss.solve();
    return EXIT_SUCCESS;
}

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


#include <cstdlib>
#include <algorithm>
#include <iterator>

template<typename RandomAccessIterator>
void knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) {
  for(unsigned int n = end - begin - 1; n >= 1; --n) {
    unsigned int k = rand() % (n + 1);
    if(k != n) {
      std::iter_swap(begin + k, begin + n);
    }
  }
}

#include <algorithm>
#include <vector>

int main()
{
    int array[] = { 1,2,3,4,5,6,7,8,9 }; // C-style array of integers
    std::vector<int> vec(array, array + 9); // build STL container from int array

    std::random_shuffle(array, array + 9); // shuffle C-style array
    std::random_shuffle(vec.begin(), vec.end()); // shuffle STL container
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array in-place. The shuffling process involves iterating over the array from the last index down to 1, and for each iteration, swapping the current element with a randomly selected element from the range of 0 to the current index. If in-place modification is not possible, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


Library: Boost

#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <cstdlib>

int main( int argc , char* argv[ ] ) {
   using namespace boost::gregorian ;

   greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul ,
      Aug , Sep , Oct , Nov , Dec } ;
   greg_year gy = atoi( argv[ 1 ] ) ;
   for ( int i = 0 ; i < 12 ; i++ ) {
      last_day_of_the_week_in_month lwdm ( Friday , months[ i ] ) ;
      date d = lwdm.get_date( gy ) ;
      std::cout << d << std::endl ;
   }
   return 0 ;
}

The code takes a year as input and outputs the dates of the last Friday of each month for that given year. The input is provided through a simple method such as command line or standard input. The code is written in C++20 and does not require external libraries.


#include <iostream>

int main() {
  std::cout << "Goodbye, World!";
  return 0;
}

"Display the string 'Goodbye, World!' without appending a newline at the end."


task.h

#ifndef TASK_H
#define TASK_H

#include <QWidget>

class QLabel ;
class QLineEdit ;
class QVBoxLayout ;
class QHBoxLayout ;

class EntryWidget : public QWidget {

   Q_OBJECT
public :
   EntryWidget( QWidget *parent = 0 ) ;
private :
   QHBoxLayout *upperpart , *lowerpart ;
   QVBoxLayout *entryLayout ;
   QLineEdit *stringinput ;
   QLineEdit *numberinput ;
   QLabel *stringlabel ;
   QLabel *numberlabel ;
} ;

#endif

task.cpp

#include <QLineEdit>
#include <QLabel>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QString>
#include "task.h"

EntryWidget::EntryWidget ( QWidget *parent )
   : QWidget( parent ) {
      entryLayout = new QVBoxLayout( this ) ;
      stringlabel = new QLabel( "Enter a string!" ) ;
      stringinput = new QLineEdit( "" ) ;
      stringinput->setMaxLength( 20 ) ;
      stringinput->setInputMask( QString( "AAAAAAAAAAAAAAAAAAA" ) ) ;
      upperpart = new QHBoxLayout ;
      upperpart->addWidget( stringlabel ) ;
      upperpart->addWidget( stringinput ) ;
      numberlabel = new QLabel( "Enter a number!" ) ;
      numberinput = new QLineEdit( "0" ) ;
      numberinput->setMaxLength( 5 ) ;
      numberinput->setInputMask( QString( "99999" ) ) ;
      lowerpart = new QHBoxLayout ;
      lowerpart->addWidget( numberlabel ) ;
      lowerpart->addWidget( numberinput ) ;
      entryLayout->addLayout( upperpart ) ;
      entryLayout->addLayout( lowerpart ) ;
      setLayout( entryLayout ) ;
}

main.cpp

#include <QApplication>
#include "task.h"

int main( int argc , char *argv[ ] ) {
   QApplication app( argc , argv ) ;
   EntryWidget theWidget ;
   theWidget.show( ) ;
   return app.exec( ) ;
}

"Code uses Qt 4.4 library to create a graphical user interface that accepts a string and the integer 75000 as inputs from the user."


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

class MyTransform {
private :
   int shift ;
public :
   MyTransform( int s ) : shift( s ) { }

  char operator( )( char c ) {
      if ( isspace( c ) )
	 return ' ' ;
      else {
	 static std::string letters( "abcdefghijklmnopqrstuvwxyz" ) ;
	 std::string::size_type found = letters.find(tolower( c )) ;
	 int shiftedpos = ( static_cast<int>( found ) + shift ) % 26 ;
	 if ( shiftedpos < 0 ) //in case of decryption possibly
	    shiftedpos = 26 + shiftedpos ;
	 char shifted = letters[shiftedpos] ;
	 return shifted ;
      }
  }
} ;

int main( ) {
   std::string input ;
   std::cout << "Which text is to be encrypted ?\n" ;
   getline( std::cin , input ) ;
   std::cout << "shift ?\n" ;
   int myshift = 0 ;
   std::cin >> myshift ;
   std::cout << "Before encryption:\n" << input << std::endl ;
   std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
	 MyTransform( myshift ) ) ;
   std::cout << "encrypted:\n" ;
   std::cout << input << std::endl ;
   myshift *= -1 ; //decrypting again
   std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
	 MyTransform( myshift ) ) ;
   std::cout << "Decrypted again:\n" ;
   std::cout << input << std::endl ;
   return 0 ;
}

implement a Caesar cipher for both encoding and decoding. It uses an integer key from 1 to 25 to rotate the letters of the alphabet. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z to A. The code also includes an alternative version using lambda functions, auto, and iterators. The Caesar cipher is identical to the Vigenère cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.


Library: Boost
#include <boost/math/common_factor.hpp>
#include <iostream>

int main( ) {
   std::cout << "The least common multiple of 12 and 18 is " <<
      boost::math::lcm( 12 , 18 ) << " ,\n"
      << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
   return 0 ;
}

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


#include <iostream>
#include <vector>

bool isCusip(const std::string& s) {
    if (s.size() != 9) return false;

    int sum = 0;
    for (int i = 0; i <= 7; ++i) {
        char c = s[i];

        int v;
        if ('0' <= c && c <= '9') {
            v = c - '0';
        } else if ('A' <= c && c <= 'Z') {
            v = c - '@';
        } else if (c = '*') {
            v = 36;
        } else if (c = '#') {
            v = 38;
        } else {
            return false;
        }
        if (i % 2 == 1) {
            v *= 2;
        }
        sum += v / 10 + v % 10;
    }
    return s[8] - '0' == (10 - (sum % 10)) % 10;
}

int main() {
    using namespace std;

    vector<string> candidates{
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105"
    };

    for (auto str : candidates) {
        auto res = isCusip(str) ? "correct" : "incorrect";
        cout << str.c_str() << " -> " << res << "\n";
    }

    return 0;
}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


#include <bit>
#include <iostream>

int main()
{
    std::cout << "int is " << sizeof(int) << " bytes\n";
    std::cout << "a pointer is " << sizeof(int*) << " bytes\n\n";

    if (std::endian::native == std::endian::big)
    {
        std::cout << "platform is big-endian\n";
    }
    else
    {
        std::cout << "host is little-endian\n";
    }
}

"Outputs the word size and endianness of the host machine."


Library: Boost

#include <string>
#include <boost/regex.hpp>
#include <boost/asio.hpp>
#include <vector>
#include <utility>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <iomanip>

struct Sort { //sorting programming languages according to frequency
   bool operator( ) ( const std::pair<std::string,int> & a , const std::pair<std::string,int> & b )
      const {
	 return a.second > b.second ;
      }
} ;

int main( ) {
   try {
      //setting up an io service , with templated subelements for resolver and query
      boost::asio::io_service io_service ;
      boost::asio::ip::tcp::resolver resolver ( io_service ) ;
      boost::asio::ip::tcp::resolver::query query ( "rosettacode.org" , "http" ) ;
      boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;
      boost::asio::ip::tcp::resolver::iterator end ;
      boost::asio::ip::tcp::socket socket( io_service ) ;
      boost::system::error_code error = boost::asio::error::host_not_found ;
      //looking for an endpoint the socket will be able to connect to
      while ( error && endpoint_iterator != end ) {
	 socket.close( ) ;
	 socket.connect( *endpoint_iterator++ , error ) ;
      }
      if ( error )
	 throw boost::system::system_error ( error ) ;
      //we send a request
      boost::asio::streambuf request ;
      std::ostream request_stream( &request ) ;
      request_stream << "GET " << "/mw/index.php?title=Special:Categories&limit=5000" << " HTTP/1.0\r\n" ;
      request_stream << "Host: " << "rosettacode.org" << "\r\n" ;
      request_stream << "Accept: */*\r\n" ;
      request_stream << "Connection: close\r\n\r\n" ;
      //send the request
      boost::asio::write( socket , request ) ;
      //we receive the response analyzing every line and storing the programming language
      boost::asio::streambuf response ;
      std::istream response_stream ( &response ) ;
      boost::asio::read_until( socket , response , "\r\n\r\n" ) ;
      boost::regex e( "
<a href=\"[^<>]+?\">([a-zA-Z\\+#1-9]+?)\\s?\\((\\d+) members\\)
" ) ;
      //using the wrong regex produces incorrect sorting!!
      std::ostringstream line ;
      std::vector<std::pair<std::string , int> > languages ; //holds language and number of examples
      boost::smatch matches ;
      while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {
	 line << &response ;
	 if ( boost::regex_search( line.str( ) , matches , e ) ) {
	    std::string lang( matches[2].first , matches[2].second ) ;
	    int zahl = atoi ( lang.c_str( ) ) ;
	    languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;
	 }
	 line.str( "") ;//we have to erase the string buffer for the next read
      }
      if ( error != boost::asio::error::eof )
	 throw boost::system::system_error( error ) ;
      //we sort the vector entries , see the struct above
      std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;
      int n = 1 ;
      for ( std::vector<std::pair<std::string , int> >::const_iterator spi = languages.begin( ) ;
	    spi != languages.end( ) ; ++spi ) {
	 std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right <<
	 spi->second   << " - " << spi->first << '\n' ;
	 n++ ;
      }
   } catch ( std::exception &ex ) {
      std::cout << "Exception: " << ex.what( ) << '\n' ;
   }
   return 0 ;
}

Sample output (just the "top ten"):
 1. 367 - Tcl
 2. 334 - Python
 3. 319 - Ruby
 4. 286 - C
 5. 277 - Perl
 6. 272 - OCaml
 7. 264 - Ada
 8. 241 - E
 9. 239 - AutoHotkey
10. 193 - Forth

The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It can access data through web scraping or using the API method. The code also has the option to filter incorrect results. It generates a complete ranked list of all languages, which can be checked against a periodically updated list of all programming languages. The code is designed to run on Linux using g++.


for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}

std::copy(container.begin(), container.end(),
          std::ostream_iterator<container_type::value_type>(std::cout, "\n"));

void print_element(container_type::value_type const& v)
{
  std::cout << v << "\n";
}

...
  std::for_each(container.begin(), container.end(), print_element);

Works with: C++11
for (auto element: container)
{
  std::cout << element << "\n";
}

for (auto const& element: container)
{
  std::cout << element << "\n";
}

for (auto&& element: container) //use a 'universal reference'
{
  element += 42;
}

iterate through each element in a given collection in a sequential manner. The code uses a "for each" loop if available in the language, otherwise, it uses another type of loop. In the case of C++03, a generic loop is used as it doesn't support a "for each" loop. The code also allows for the modification of container elements using a non-const reference, unless the container is constant.


Works with: C++98

#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
int main()
{
    std::string s = "Hello,How,Are,You,Today";
    std::vector<std::string> v;
    std::istringstream buf(s);
    for(std::string token; getline(buf, token, ','); )
        v.push_back(token);
    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "."));
    std::cout << '\n';
}

Works with: C++98

#include <string>
#include <locale>
#include <sstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
struct comma_ws : std::ctype<char> {
    static const mask* make_table() {
    static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v[','] |= space;  // comma will be classified as whitespace
        return &v[0];
    }
    comma_ws(std::size_t refs = 0) : ctype<char>(make_table(), false, refs) {}
};
int main()
{
    std::string s = "Hello,How,Are,You,Today";
    std::istringstream buf(s);
    buf.imbue(std::locale(buf.getloc(), new comma_ws));
    std::istream_iterator<std::string> beg(buf), end;
    std::vector<std::string> v(beg, end);
    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "."));
    std::cout << '\n';
}

Works with: C++98
Library: boost

#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>
#include <boost/tokenizer.hpp>
int main()
{
    std::string s = "Hello,How,Are,You,Today";
    boost::tokenizer<> tok(s);
    std::vector<std::string> v(tok.begin(), tok.end());
    copy(v.begin(), v.end(), std::ostream_iterator<std::string>(std::cout, "."))
    std::cout << '\n';
}

Works with: C++23

#include <string>
#include <ranges>
#include <iostream>
int main() {
    std::string s = "Hello,How,Are,You,Today";
    s = s                               // Assign the final string back to the string variable
      | std::views::split(',')          // Produce a range of the comma separated words
      | std::views::join_with('.')      // Concatenate the words into a single range of characters
      | std::ranges::to<std::string>(); // Convert the range of characters into a regular string
    std::cout << s;
}

"Tokenizes a given string by commas into an array, and displays the words separated by a period using std::getline() function in C++. It takes advantage of C++'s ability to redefine whitespace and the boost library's tokenization options. The code is optimized for C++20 and C++23 for better range manipulation."


#include <iostream>
#include <numeric>

int main() {
    std::cout << "The greatest common divisor of 12 and 18 is " << std::gcd(12, 18) << " !\n";
}

Library: Boost
#include <boost/math/common_factor.hpp>
#include <iostream>

int main() {
   std::cout << "The greatest common divisor of 12 and 18 is " << boost::math::gcd(12, 18) << "!\n";
}

calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.


#include <sstream> // for istringstream

using namespace std;

bool isNumeric( const char* pszInput, int nNumberBase )
{
	istringstream iss( pszInput );

	if ( nNumberBase == 10 )
	{
		double dTestSink;
		iss >> dTestSink;
	}
	else if ( nNumberBase == 8 || nNumberBase == 16 )
	{
		int nTestSink;
		iss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;
	}
	else
		return false;

	// was any input successfully consumed/converted?
	if ( ! iss )
		return false;

	// was all the input successfully consumed/converted?
	return ( iss.rdbuf()->in_avail() == 0 );
}

bool isNumeric( const char* pszInput, int nNumberBase )
{
	string base = "0123456789ABCDEF";
	string input = pszInput;

	return (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);
}

bool isNumeric(const std::string& input) {
    return std::all_of(input.begin(), input.end(), ::isdigit);
}

"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, using the syntax of numeric literals or numbers converted from strings. This is achieved using stringstream, find, and all_of (C++11 required)."


#include <iostream>
#include <span>
#include <vector>

struct vec2 {
    float x = 0.0f, y = 0.0f;

    constexpr vec2 operator+(vec2 other) const {
        return vec2{x + other.x, y + other.y};
    }

    constexpr vec2 operator-(vec2 other) const {
        return vec2{x - other.x, y - other.y};
    }
};

constexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }

constexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }

constexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }

// check if a point is on the LEFT side of an edge
constexpr bool is_inside(vec2 point, vec2 a, vec2 b) {
    return (cross(a - b, point) + cross(b, a)) < 0.0f;
}

// calculate intersection point
constexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {
    return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *
           (1.0f / cross(a1 - a2, b1 - b2));
}

// Sutherland-Hodgman clipping
std::vector<vec2> suther_land_hodgman(
    std::span<vec2 const> subject_polygon, std::span<vec2 const> clip_polygon) {
    if (clip_polygon.empty() || subject_polygon.empty()) {
        return {};
    }

    std::vector<vec2> ring{subject_polygon.begin(), subject_polygon.end()};

    vec2 p1 = clip_polygon[clip_polygon.size() - 1];

    std::vector<vec2> input;

    for (vec2 p2 : clip_polygon) {
        input.clear();
        input.insert(input.end(), ring.begin(), ring.end());
        vec2 s = input[input.size() - 1];

        ring.clear();

        for (vec2 e : input) {
            if (is_inside(e, p1, p2)) {
                if (!is_inside(s, p1, p2)) {
                    ring.push_back(intersection(p1, p2, s, e));
                }

                ring.push_back(e);
            } else if (is_inside(s, p1, p2)) {
                ring.push_back(intersection(p1, p2, s, e));
            }

            s = e;
        }

        p1 = p2;
    }

    return ring;
}

int main(int argc, char **argv) {
    // subject polygon
    vec2 subject_polygon[] = {{50, 150},  {200, 50},  {350, 150},
                              {350, 300}, {250, 300}, {200, 250},
                              {150, 350}, {100, 250}, {100, 200}};

    // clipping polygon
    vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};

    // apply clipping
    std::vector<vec2> clipped_polygon =
        suther_land_hodgman(subject_polygon, clip_polygon);

    // print clipped polygon points
    std::cout << "Clipped polygon points:" << std::endl;
    for (vec2 p : clipped_polygon) {
        std::cout << "(" << p.x << ", " << p.y << ")" << std::endl;
    }

    return EXIT_SUCCESS;
}

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <ostream>
#include <set>
#include <vector>

template<typename T>
std::ostream& print(std::ostream& os, const T& src) {
    auto it = src.cbegin();
    auto end = src.cend();

    os << "[";
    if (it != end) {
        os << *it;
        it = std::next(it);
    }
    while (it != end) {
        os << ", " << *it;
        it = std::next(it);
    }

    return os << "]";
}

typedef std::map<std::string, int> Map;
typedef Map::value_type MapEntry;

void standardRank(const Map& scores) {
    std::cout << "Standard Rank" << std::endl;

    std::vector<int> list;
    for (auto& elem : scores) {
        list.push_back(elem.second);
    }
    std::sort(list.begin(), list.end(), std::greater<int>{});
    list.erase(std::unique(list.begin(), list.end()), list.end());

    int rank = 1;
    for (auto value : list) {
        int temp = rank;
        for (auto& e : scores) {
            if (e.second == value) {
                std::cout << temp << " " << value << " " << e.first.c_str() << std::endl;
                rank++;
            }
        }
    }

    std::cout << std::endl;
}

void modifiedRank(const Map& scores) {
    std::cout << "Modified Rank" << std::endl;

    std::vector<int> list;
    for (auto& elem : scores) {
        list.push_back(elem.second);
    }
    std::sort(list.begin(), list.end(), std::greater<int>{});
    list.erase(std::unique(list.begin(), list.end()), list.end());

    int rank = 0;
    for (auto value : list) {
        rank += std::count_if(scores.begin(), scores.end(), [value](const MapEntry& e) { return e.second == value; });
        for (auto& e : scores) {
            if (e.second == value) {
                std::cout << rank << " " << value << " " << e.first.c_str() << std::endl;
            }
        }
    }

    std::cout << std::endl;
}

void denseRank(const Map& scores) {
    std::cout << "Dense Rank" << std::endl;

    std::vector<int> list;
    for (auto& elem : scores) {
        list.push_back(elem.second);
    }
    std::sort(list.begin(), list.end(), std::greater<int>{});
    list.erase(std::unique(list.begin(), list.end()), list.end());

    int rank = 1;
    for (auto value : list) {
        for (auto& e : scores) {
            if (e.second == value) {
                std::cout << rank << " " << value << " " << e.first.c_str() << std::endl;
            }
        }
        rank++;
    }

    std::cout << std::endl;
}

void ordinalRank(const Map& scores) {
    std::cout << "Ordinal Rank" << std::endl;

    std::vector<int> list;
    for (auto& elem : scores) {
        list.push_back(elem.second);
    }
    std::sort(list.begin(), list.end(), std::greater<int>{});
    list.erase(std::unique(list.begin(), list.end()), list.end());

    int rank = 1;
    for (auto value : list) {
        for (auto& e : scores) {
            if (e.second == value) {
                std::cout << rank++ << " " << value << " " << e.first.c_str() << std::endl;
            }
        }
    }

    std::cout << std::endl;
}

void fractionalRank(const Map& scores) {
    std::cout << "Ordinal Rank" << std::endl;

    std::vector<int> list;
    for (auto& elem : scores) {
        list.push_back(elem.second);
    }
    std::sort(list.begin(), list.end(), std::greater<int>{});
    list.erase(std::unique(list.begin(), list.end()), list.end());

    int rank = 0;
    for (auto value : list) {
        double avg = 0.0;
        int cnt = 0;

        for (auto& e : scores) {
            if (e.second == value) {
                rank++;
                cnt++;
                avg += rank;
            }
        }
        avg /= cnt;

        for (auto& e : scores) {
            if (e.second == value) {
                std::cout << std::setprecision(1) << std::fixed << avg << " " << value << " " << e.first.c_str() << std::endl;
            }
        }
    }

    std::cout << std::endl;
}

int main() {
    using namespace std;

    map<string, int> scores{
        {"Solomon", 44},
        {"Jason", 42},
        {"Errol", 42},
        {"Gary", 41},
        {"Bernard", 41},
        {"Barry", 41},
        {"Stephen", 39}
    };

    standardRank(scores);
    modifiedRank(scores);
    denseRank(scores);
    ordinalRank(scores);
    fractionalRank(scores);

    return 0;
}

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


#include <iostream>
#include <cmath>

#ifdef M_PI // defined by all POSIX systems and some non-POSIX ones
double const pi = M_PI;
#else
double const pi = 4*std::atan(1);
#endif

double const degree = pi/180;

int main()
{
  std::cout << "=== radians ===\n";
  std::cout << "sin(pi/3) = " << std::sin(pi/3) << "\n";
  std::cout << "cos(pi/3) = " << std::cos(pi/3) << "\n";
  std::cout << "tan(pi/3) = " << std::tan(pi/3) << "\n";
  std::cout << "arcsin(1/2) = " << std::asin(0.5) << "\n";
  std::cout << "arccos(1/2) = " << std::acos(0.5) << "\n";
  std::cout << "arctan(1/2) = " << std::atan(0.5) << "\n";

  std::cout << "\n=== degrees ===\n";
  std::cout << "sin(60°) = " << std::sin(60*degree) << "\n";
  std::cout << "cos(60°) = " << std::cos(60*degree) << "\n";
  std::cout << "tan(60°) = " << std::tan(60*degree) << "\n";
  std::cout << "arcsin(1/2) = " << std::asin(0.5)/degree << "°\n";
  std::cout << "arccos(1/2) = " << std::acos(0.5)/degree << "°\n";
  std::cout << "arctan(1/2) = " << std::atan(0.5)/degree << "°\n";

  return 0;
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <memory>
#include <sys/time.h>

using std::cout;
using std::endl;

class StopTimer
{
public:
    StopTimer(): begin_(getUsec()) {}
    unsigned long long getTime() const { return getUsec() - begin_; }
private:
    static unsigned long long getUsec()
    {//...you might want to use something else under Windows
        timeval tv;
        const int res = ::gettimeofday(&tv, 0);
        if(res)
            return 0;
        return tv.tv_usec + 1000000 * tv.tv_sec;
    }
    unsigned long long begin_;
};

struct KnapsackTask
{
    struct Item
    {
        std::string name;
        unsigned w, v, qty;
        Item(): w(), v(), qty() {}
        Item(const std::string& iname, unsigned iw, unsigned iv, unsigned iqty):
            name(iname), w(iw), v(iv), qty(iqty)
        {}
    };
    typedef std::vector<Item> Items;
    struct Solution
    {
        unsigned v, w;
        unsigned long long iterations, usec;
        std::vector<unsigned> n;
        Solution(): v(), w(), iterations(), usec() {}
    };
    //...
    KnapsackTask(): maxWeight_(), totalWeight_() {}
    void add(const Item& item)
    {
        const unsigned totalItemWeight = item.w * item.qty;
        if(const bool invalidItem = !totalItemWeight)
            throw std::logic_error("Invalid item: " + item.name);
        totalWeight_ += totalItemWeight;
        items_.push_back(item);
    }
    const Items& getItems() const { return items_; }
    void setMaxWeight(unsigned maxWeight) { maxWeight_ = maxWeight; }
    unsigned getMaxWeight() const { return std::min(totalWeight_, maxWeight_); }

private:
    unsigned maxWeight_, totalWeight_;
    Items items_;
};

class BoundedKnapsackRecursiveSolver
{
public:
    typedef KnapsackTask Task;
    typedef Task::Item Item;
    typedef Task::Items Items;
    typedef Task::Solution Solution;

    void solve(const Task& task)
    {
        Impl(task, solution_).solve();
    }
    const Solution& getSolution() const { return solution_; }
private:
    class Impl
    {
        struct Candidate
        {
            unsigned v, n;
            bool visited;
            Candidate(): v(), n(), visited(false) {}
        };
        typedef std::vector<Candidate> Cache;
    public:
        Impl(const Task& task, Solution& solution):
            items_(task.getItems()),
            maxWeight_(task.getMaxWeight()),
            maxColumnIndex_(task.getItems().size() - 1),
            solution_(solution),
            cache_(task.getMaxWeight() * task.getItems().size()),
            iterations_(0)
        {}
        void solve()
        {
            if(const bool nothingToSolve = !maxWeight_ || items_.empty())
                return;
            StopTimer timer;
            Candidate candidate;
            solve(candidate, maxWeight_, items_.size() - 1);
            convertToSolution(candidate);
            solution_.usec = timer.getTime();
        }
    private:
        void solve(Candidate& current, unsigned reminderWeight, const unsigned itemIndex)
        {
            ++iterations_;

            const Item& item(items_[itemIndex]);

            if(const bool firstColumn = !itemIndex)
            {
                const unsigned maxQty = std::min(item.qty, reminderWeight/item.w);
                current.v = item.v * maxQty;
                current.n = maxQty;
                current.visited = true;
            }
            else
            {
                const unsigned nextItemIndex = itemIndex - 1;
                {
                    Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex);
                    if(!nextItem.visited)
                        solve(nextItem, reminderWeight, nextItemIndex);
                    current.visited = true;
                    current.v = nextItem.v;
                    current.n = 0;
                }
                if(reminderWeight >= item.w)
                {
                    for (unsigned numberOfItems = 1; numberOfItems <= item.qty; ++numberOfItems)
                    {
                        reminderWeight -= item.w;
                        Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex);
                        if(!nextItem.visited)
                            solve(nextItem, reminderWeight, nextItemIndex);

                        const unsigned checkValue = nextItem.v + numberOfItems * item.v;
                        if ( checkValue > current.v)
                        {
                            current.v = checkValue;
                            current.n = numberOfItems;
                        }
                        if(!(reminderWeight >= item.w))
                            break;
                    }
                }
            }
        }
        void convertToSolution(const Candidate& candidate)
        {
            solution_.iterations = iterations_;
            solution_.v = candidate.v;
            solution_.n.resize(items_.size());

            const Candidate* iter = &candidate;
            unsigned weight = maxWeight_, itemIndex = items_.size() - 1;
            while(true)
            {
                const unsigned currentWeight = iter->n * items_[itemIndex].w;
                solution_.n[itemIndex] = iter->n;
                weight -= currentWeight;
                if(!itemIndex--)
                    break;
                iter = &cachedItem(weight, itemIndex);
            }
            solution_.w = maxWeight_ - weight;
        }
        Candidate& cachedItem(unsigned weight, unsigned itemIndex)
        {
            return cache_[weight * maxColumnIndex_ + itemIndex];
        }
        const Items& items_;
        const unsigned maxWeight_;
        const unsigned maxColumnIndex_;
        Solution& solution_;
        Cache cache_;
        unsigned long long iterations_;
    };
    Solution solution_;
};

void populateDataset(KnapsackTask& task)
{
    typedef KnapsackTask::Item Item;
    task.setMaxWeight( 400 );
    task.add(Item("map",9,150,1));
    task.add(Item("compass",13,35,1));
    task.add(Item("water",153,200,2));
    task.add(Item("sandwich",50,60,2));
    task.add(Item("glucose",15,60,2));
    task.add(Item("tin",68,45,3));
    task.add(Item("banana",27,60,3));
    task.add(Item("apple",39,40,3));
    task.add(Item("cheese",23,30,1));
    task.add(Item("beer",52,10,3));
    task.add(Item("suntancream",11,70,1));
    task.add(Item("camera",32,30,1));
    task.add(Item("T-shirt",24,15,2));
    task.add(Item("trousers",48,10,2));
    task.add(Item("umbrella",73,40,1));
    task.add(Item("w-trousers",42,70,1));
    task.add(Item("w-overclothes",43,75,1));
    task.add(Item("note-case",22,80,1));
    task.add(Item("sunglasses",7,20,1));
    task.add(Item("towel",18,12,2));
    task.add(Item("socks",4,50,1));
    task.add(Item("book",30,10,2));
}

int main()
{
    KnapsackTask task;
    populateDataset(task);

    BoundedKnapsackRecursiveSolver solver;
    solver.solve(task);
    const KnapsackTask::Solution& solution = solver.getSolution();

    cout << "Iterations to solve: " << solution.iterations << endl;
    cout << "Time to solve: " << solution.usec << " usec" << endl;
    cout << "Solution:" << endl;
    for (unsigned i = 0; i < solution.n.size(); ++i)
    {
        if (const bool itemIsNotInKnapsack = !solution.n[i])
            continue;
        cout << "  " << solution.n[i] << ' ' << task.getItems()[i].name << " ( item weight = " << task.getItems()[i].w << " )" << endl;
    }

    cout << "Weight: " << solution.w << " Value: " << solution.v << endl;
    return 0;
}

"Implement a solution for the Bounded Knapsack problem, where a tourist needs to decide which items to carry on a trip to maximize the total value without exceeding a weight limit of 4 kg. The items, their weights, values, and available quantities are given in a list. The solution uses dynamic programming and is a refactored and bug-fixed version of an initial C++ implementation."


#include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>

volatile sig_atomic_t gotint = 0;

void handler(int signum) {
	// Set a flag for handling the signal, as other methods like printf are not safe here
	gotint = 1;
}

int main() {
	using namespace std;

	signal(SIGINT, handler);

	int i = 0;
	clock_t startTime = clock();
	while (true) {
		if (gotint) break;
		std::this_thread::sleep_for(std::chrono::milliseconds(500));
		if (gotint) break;
		cout << ++i << endl;
	}
	clock_t endTime = clock();

	double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
	cout << "Program has run for " << dt << " seconds" << endl;

	return 0;
}

an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.


// standard C++ string stream operators
#include <cstdlib>
#include <string>
#include <sstream>

// inside a function or method...
std::string s = "12345";

int i;
std::istringstream(s) >> i;
i++;
//or:
//int i = std::atoi(s.c_str()) + 1;

std::ostringstream oss;
if (oss << i) s = oss.str();

Works with: C++11
#include <string>

std::string s = "12345";
s = std::to_string(1+std::stoi(s));

Library: Boost
// Boost
#include <cstdlib>
#include <string>
#include <boost/lexical_cast.hpp>

// inside a function or method...
std::string s = "12345";
int i = boost::lexical_cast<int>(s) + 1;
s = boost::lexical_cast<std::string>(i);

Library: Qt
Uses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/Qt/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
// Qt
QString num1 = "12345";
QString num2 = QString("%1").arg(v1.toInt()+1);

Library: MFC
Uses: Microsoft Foundation Classes (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/Microsoft Foundation Classes/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
Uses: C Runtime (Components:{{#foreach: component$n$|{{{component$n$}}}Property "Uses Library" (as page type) with input value "Library/C Runtime/{{{component$n$}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})
// MFC
CString s = "12345";
int i = _ttoi(s) + 1;
int i = _tcstoul(s, NULL, 10) + 1;
s.Format("%d", i);

Works with: g++ version 4.0.2
#include <string>
#include <iostream>
#include <ostream>

void increment_numerical_string(std::string& s)
{
    std::string::reverse_iterator iter = s.rbegin(), end = s.rend();
    int carry = 1;
    while (carry && iter != end)
    {
        int value = (*iter - '0') + carry;
        carry = (value / 10);
        *iter = '0' + (value % 10);
        ++iter;
    }
    if (carry)
        s.insert(0, "1");
}

int main()
{
    std::string big_number = "123456789012345678901234567899";
    std::cout << "before increment: " << big_number << "\n";
    increment_numerical_string(big_number);
    std::cout << "after increment:  " << big_number << "\n";
}

"Increments an almost arbitrarily large numerical string, going beyond the INT_MAX limit."


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

std::string longestPath( const std::vector<std::string> & , char ) ;

int main( ) {
   std::string dirs[ ] = {
      "/home/user1/tmp/coverage/test" ,
      "/home/user1/tmp/covert/operator" ,
      "/home/user1/tmp/coven/members" } ;
   std::vector<std::string> myDirs ( dirs , dirs + 3 ) ;
   std::cout << "The longest common path of the given directories is "
             << longestPath( myDirs , '/' ) << "!\n" ;
   return 0 ;
}

std::string longestPath( const std::vector<std::string> & dirs , char separator ) {
   std::vector<std::string>::const_iterator vsi = dirs.begin( ) ;
   int maxCharactersCommon = vsi->length( ) ;
   std::string compareString = *vsi ;
   for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {
      std::pair<std::string::const_iterator , std::string::const_iterator> p =
	 std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;
      if (( p.first - compareString.begin( ) ) < maxCharactersCommon )
	 maxCharactersCommon = p.first - compareString.begin( ) ;
   }
   std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;
   return compareString.substr( 0 , found ) ;
}

The longest common path of the given directories is /home/user1/tmp!

"Code identifies the common directory path from a given set of directory paths using a specified directory separator character."


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

class cycle{
public:
    template <class T>
    void cy( T* a, int len ) {
        int i, j;
        show( "original: ", a, len );
        std::srand( unsigned( time( 0 ) ) );

        for( int i = len - 1; i > 0; i-- ) {
            do {
                j = std::rand() % i;
            } while( j >= i );
            std::swap( a[i], a[j] );
        }

        show( "  cycled: ", a, len ); std::cout << "\n";
    }
private:
    template <class T>
    void show( std::string s, T* a, int len ) {
        std::cout << s;
        for( int i = 0; i < len; i++ ) {
            std::cout << a[i] << " ";
        }
        std::cout << "\n";
    }
};
int main( int argc, char* argv[] ) {
    std::string d0[] = { "" },
                d1[] = { "10" },
                d2[] = { "10", "20" };
    int         d3[] = { 10, 20, 30 },
                d4[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 };
    cycle c;
    c.cy( d0, sizeof( d0 ) / sizeof( d0[0] ) );
    c.cy( d1, sizeof( d1 ) / sizeof( d1[0] ) );
    c.cy( d2, sizeof( d2 ) / sizeof( d2[0] ) );
    c.cy( d3, sizeof( d3 ) / sizeof( d3[0] ) );
    c.cy( d4, sizeof( d4 ) / sizeof( d4[0] ) );

    return 0;
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.


#include <algorithm>

// inputs must be random-access iterators of doubles
// Note: this function modifies the input range
template <typename Iterator>
double median(Iterator begin, Iterator end) {
  // this is middle for odd-length, and "upper-middle" for even length
  Iterator middle = begin + (end - begin) / 2;

  // This function runs in O(n) on average, according to the standard
  std::nth_element(begin, middle, end);

  if ((end - begin) % 2 != 0) { // odd length
    return *middle;
  } else { // even length
    // the "lower middle" is the max of the lower half
    Iterator lower_middle = std::max_element(begin, middle);
    return (*middle + *lower_middle) / 2.0;
  }
}

#include <iostream>

int main() {
  double a[] = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2};
  double b[] = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2};

  std::cout << median(a+0, a + sizeof(a)/sizeof(a[0])) << std::endl; // 4.4
  std::cout << median(b+0, b + sizeof(b)/sizeof(b[0])) << std::endl; // 4.25

  return 0;
}

Library: gnu_pbds
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

// the std::less_equal<> comparator allows the tree to support duplicates
typedef __gnu_pbds::tree<double, __gnu_pbds::null_type, std::less_equal<double>, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ost_t;

// The lookup method, find_by_order (aka Select), is O(log n) for this data structure, much faster than std::nth_element()
double median(ost_t &OST)
{
    int n = OST.size();
    int m = n/2;
    if (n == 1)
        return *OST.find_by_order(0);
    if (n == 2)
        return (*OST.find_by_order(0) + *OST.find_by_order(1)) / 2;

    if (n & 1) // odd number of elements
        return *OST.find_by_order(m);
    else // even number of elements
        return (*OST.find_by_order(m) + *OST.find_by_order(m-1)) / 2;
}

int main(int argc, char* argv[])
{
    ost_t ostree;

    // insertion is also O(log n) for OSTs
    ostree.insert(4.1);
    ostree.insert(7.2);
    ostree.insert(1.7);
    ostree.insert(9.3);
    ostree.insert(4.4);
    ostree.insert(3.2);

    printf("%.3f\n", median(ostree)); // 4.250

    return 0;
}

"Calculates the median value of a vector of floating-point numbers using the selection algorithm. Handles even number of elements by returning the average of the two middle values. Runs in linear time on average and uses a GNU C++ policy-based data structure to compute median in O(log n) time. Also includes tasks for calculating various statistical measures like mean, mode, and standard deviation."