SlideShare a Scribd company logo
1C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
/*
* monkey_puzzle.cpp
*
* Created on: 29 Jun 2014
* Author: Russell John Childs
*/
//=======================================================================================================
// COPYRIGHT NOTICE
// This code sample and ideas embodied remain the property of Dr Russell John Childs, PhD, and have been
// distributed as a representative example of my use of C++11 features,
//==========================================================================================================
============
#include <iostream>
#include <iomanip>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <functional>
//The answer to the riddle is 102485.
//General "point" class that accepts a metric defining the "distance" associatated with the interval between
two points.
// It is debatable whether it is good design practice to tie a metric to a point, but it provides for type-
safety in
// not allowing two points with different metrics to be used to calculate the interval.
template<typename Metric>
class Point
{
public:
//Simple ctor that sepcifies coords
explicit Point(int x, int y) :
m_x(x),
m_y(y),
m_is_accessible(true)
{
}
//NOP dtor
~Point(void)
{
}
//Function to calculate vector difference
friend Point operator-(const Point& lhs, const Point& rhs)
{
return Point(lhs.m_x - rhs.m_x, lhs.m_y - rhs.m_y);
}
//Function that calculates radial distance from origin according to the specified metric.
unsigned radius(void) const
{
return Metric()(*this);
}
//Binary predicate to be used by a sorted container to sort points by radial distance from origin
friend bool operator<(const Point& lhs, const Point& rhs)
{
//Sort by radial distance from origin, then by x, then by y.
return lhs.radius() < rhs.radius() ||
(lhs.radius() == rhs.radius() && lhs.m_x < rhs.m_x) ||
(lhs.radius() == rhs.radius() && lhs.m_x == rhs.m_x && lhs.m_y < rhs.m_y);
}
private:
friend Metric;
friend class SolveMonkeyPuzzle;
int m_x;
int m_y;
bool m_is_accessible;
};
2C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
//==================
//Monkey's Metric = sum(abs(digit(x))) + sum(abs(digit(y)))
//==========
class MonkeyMetric
{
public:
//Default Ctor
MonkeyMetric(void)
{
}
//NOP Dtor
~MonkeyMetric(void)
{
}
//operator()
// returns the distance between points using the monkey metric. By default, it resturns distance of
point from origin.
unsigned operator()(const Point<MonkeyMetric>& lhs, const Point<MonkeyMetric>& rhs = Point<MonkeyMetric>
(0,0))
{
//Lmabda computes sum(abs(digit(value)))
auto sum_digits = [](unsigned value)
{
unsigned sum = 0;
for (auto digit : std::to_string(value))
{
sum += std::stoul(std::string(1,digit));
}
return sum;
};
return sum_digits(std::abs((lhs - rhs).m_x)) + sum_digits(std::abs((lhs - rhs).m_y));
}
};
//==================
//The solver class. Uses a counting method and a sorting method to compute number of points
// accessible to the monkey for a given value for the maximum radius from the origin.
//==========
class SolveMonkeyPuzzle
{
public:
//Ctor - takes as argument the maximum radial distance from origin the monkey may travel.
explicit SolveMonkeyPuzzle(unsigned bounds) :
m_bounds(bounds),
m_dmax(0),
m_parent_level{ 1, Point<MonkeyMetric>(0,0) }
{
//Compute the number of points that can be visited along X without exceeding
//the maximum radial distacne from the origin
while (Point<MonkeyMetric>(m_dmax, 0).radius() <= bounds)
{
++m_dmax;
}
--m_dmax; //correction for overshoot.
}
//NOP Dtor
~SolveMonkeyPuzzle(void)
{
}
//Accessor function for maximum number of points along X
unsigned get_dmax(void) const
{
return m_dmax;
}
//This function simply creates a grid quadrant (0, d_max) by (0, d_max)
// iterates over all points in this quadrant, adding them to a sorted set.
// Finally it returns the number of sorted points whose radial distance from
3C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
// the origin is <= maximum.
unsigned get_sorted_count(void)
{
std::set<Point<MonkeyMetric>> points;
for (unsigned x = 0; x <= m_dmax; ++x)
{
for (unsigned y = 0; y <= m_dmax; ++y)
{
points.insert(Point<MonkeyMetric>(x, y));
}
}
/*if (m_bounds == 1)
{
for (auto& point : points)
{
std::cout << "Point(" << point.m_x << "," << point.m_y << ")" << std::endl;
}
}*/
return std::count_if(points.begin(), points.end(),
[this](const Point<MonkeyMetric>& point)
{return point.radius() <= this->m_bounds;} );
}
// Key function - this is the function that solves the monkey puzzle for one quadrant.
//
//This function simply creates a grid quadrant (0, d_max) by (0, d_max)
// iterates over all points in this quadrant, incrementing a counter if the maximum
// radial distance is not exceeded and at least one parent tree node is accessible.
unsigned get_accessible_quad_count(std::function<bool(const Point<MonkeyMetric>&)> constraints, bool
display = false)
{
unsigned count = 0;
for (unsigned level = 1; level <= 2*m_dmax; ++level) //loop over levels
{
std::vector<Point<MonkeyMetric>> current_level;
//current_level.reserve(level+1);
unsigned i = 0;
for (unsigned y = std::max(level,m_dmax)-m_dmax; y <= std::min(level, m_dmax); ++y) //loop over
nodes, left to right
{
current_level.push_back( Point<MonkeyMetric>(level-y, y) ); //assign point to node
current_level[i].m_is_accessible = constraints(current_level[i]);//Apply constraints
count += (current_level[i].m_is_accessible ? 1 : 0); //Update quadrant count
++i;
}
m_parent_level = std::move(current_level);
}
return count+1; //include point at origin
}
//This function simply creates a grid quadrant (0, d_max) by (0, d_max)
// iterates over all points in this quadrant, incrementing a counter if the maximum
// radial distance is not exceeded.
unsigned get_radial_count(bool display = false)
{
auto constraints = [this](const Point<MonkeyMetric>& point){ return (point.radius() <= this->
m_bounds); };
return get_accessible_quad_count(constraints);
}
//This function converts from quadrant count to full count over all four quadrants
unsigned get_total_from_quad_count( unsigned quad_count )
{
// Multiplying quad by 4 gives overcounting of the X and Y axis points
//so subtract 4*(d_max+1), then need to add origin point
return 4 * quad_count - 4 * (m_dmax + 1) + 1;
}
//This function simply creates a grid quadrant (0, d_max) by (0, d_max)
// iterates over all points in this quadrant, incrementing a counter if the maximum
4C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
// radial distance is not exceeded.
unsigned get_full_constraint_count(bool display = false)
{
auto constraints = [this](const Point<MonkeyMetric>& point)
{
int level = point.m_x + point.m_y;
int index = point.m_y - (level <= static_cast<int>(m_dmax) ? 0 : (level-m_dmax));
unsigned left_parent = std::max(0, index - 1);
unsigned right_parent = std::min(index, static_cast<int>(this->m_parent_level.size()) - 1);
return (point.radius() <= this->m_bounds &&
(this->m_parent_level[left_parent].m_is_accessible ||
this->m_parent_level[right_parent].m_is_accessible));
};
return get_total_from_quad_count(get_accessible_quad_count(constraints));
}
//This function simply creates a grid quadrant (0, d_max) by (0, d_max)
// iterates over all points in this quadrant, incrementing a counter to give total
// point count
unsigned get_no_constraint_count(bool display = false)
{
auto constraints = [this](const Point<MonkeyMetric>& point)
{
return true;
};
return get_total_from_quad_count(get_accessible_quad_count(constraints));
}
//This function displays the grid of points for a given bounds.
// "." are accessible points
// "X" are inaccessible points
// "-" are points that lie within bounds but are inaccessible because
// the monkey cannot find a path to them
void display(void)
{
//Get the fully constrained points
std::set<Point<MonkeyMetric>> accessible_points;
accessible_points.insert(Point<MonkeyMetric>(0, 0));
std::set<Point<MonkeyMetric>> partially_constrained_points;
auto constraints = [this, &accessible_points, &partially_constrained_points](const Point
<MonkeyMetric>& point)
{
int level = point.m_x + point.m_y;
int index = point.m_y - (level <= static_cast<int>(m_dmax) ? 0 : (level - m_dmax));
unsigned left_parent = std::max(0, index - 1);
unsigned right_parent = std::min(index, static_cast<int>(this->m_parent_level.size()) - 1);
bool is_accessible = (point.radius() <= this->m_bounds &&
(this->m_parent_level[left_parent].m_is_accessible ||
this->m_parent_level[right_parent].m_is_accessible));
if( is_accessible) accessible_points.insert(point);
bool is_partial = (point.radius() <= this->m_bounds &&
!(this->m_parent_level[left_parent].m_is_accessible ||
this->m_parent_level[right_parent].m_is_accessible));
if (is_accessible) accessible_points.insert(point);
if( is_partial )partially_constrained_points.insert(point);
return is_accessible;
};
get_accessible_quad_count(constraints);
for (int x = -static_cast<int>(m_dmax); x <= static_cast<int>(m_dmax); ++x)
{
std::cout << std::endl;
for (int y = -static_cast<int>(m_dmax); y <= static_cast<int>(m_dmax); ++y)
{
//Convert to quadrant coord by simply taking |x|, |y|
std::string s;
auto f = accessible_points.find(
Point<MonkeyMetric>(std::abs(x), std::abs(y)));
5C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
s = (f != accessible_points.end() ? "." : "X");
f = partially_constrained_points.find(
Point<MonkeyMetric>(std::abs(x), std::abs(y)));
if (f != partially_constrained_points.end()) s = "+";
std::cout << s;
}
}
}
private:
unsigned m_bounds;
unsigned m_dmax;
std::vector<Point<MonkeyMetric>> m_parent_level;
};
//=======================================
//Very simple and non-exhaustive test harness
//======================================
struct TestSuite
{
//Call from main()
void run(void)
{
//Begin with the solution to the puzzle
std::cout << "==============================================================" << std::endl;
std::cout << "Calculating result please wait ..." << std::endl;
std::cout << std::endl << "The answer to the riddle is: " << SolveMonkeyPuzzle(19).
get_full_constraint_count() << std::endl;
std::cout << "==============================================================" << std::endl;
//Now run tests
std::cout << "==============================================================" << std::endl;
std::cout << std::endl << "Executing tests" << std::endl;
std::cout << "==============================================================" << std::endl;
//Run global test allowing visual inspection of accessible points found by algorithm
unsigned bounds = 10;
std::cout << std::endl << "Global test of code: Accessibility map for n=: " << bounds <<
". 'X'=inaccessible, '+'=within bounds, but no path connecting with origin, '.'=accessible
." << std::endl;
SolveMonkeyPuzzle(bounds).display();
std::cout << std::endl << std::endl << "Hit any key except Q to continue with tests. Hit Q to quit
and keep results in console" << std::endl;
char c;
std::cin >> c;
if (c == 'Q')
{
std::cout << "Display is paused. Hit any key to quit application";
std::cin >> c;
return;
}
//Pre-calculated radius values
std::pair<int, unsigned> radius[] =
{
std::make_pair(1, 1),
std::make_pair(-2, 2),
std::make_pair(3, 3),
std::make_pair(-4, 4),
std::make_pair(5, 5),
std::make_pair(-6, 6),
std::make_pair(7, 7),
std::make_pair(-8, 8),
std::make_pair(9, 9),
std::make_pair(-10, 1),
std::make_pair(11, 2),
std::make_pair(-12, 3),
std::make_pair(13, 4),
std::make_pair(-14, 5),
std::make_pair(15, 6),
std::make_pair(-16, 7),
std::make_pair(17, 8),
std::make_pair(-18, 9),
6C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
std::make_pair(19, 10)
};
//Pre-calculated d_max values
std::pair<unsigned, unsigned> d_max[]=
{
std::make_pair(1, 1),
std::make_pair(2, 2),
std::make_pair(3, 3),
std::make_pair(4, 4),
std::make_pair(5, 5),
std::make_pair(6, 6),
std::make_pair(7, 7),
std::make_pair(8, 8),
std::make_pair(9, 18),
std::make_pair(10, 28),
std::make_pair(11, 38),
std::make_pair(12, 48),
std::make_pair(13, 58),
std::make_pair(14, 68),
std::make_pair(15, 78),
std::make_pair(16, 88),
std::make_pair(17, 98),
std::make_pair(18, 198),
std::make_pair(19, 298)
};
//Keep count of passes and fails
unsigned passes = 0;
unsigned fails = 0;
//Verify Metric::operator()
std::cout << "=====Testing Metric::operator() =========== " << std::endl;
for (auto& lookup : radius)
{
MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0)) == lookup.second ? ++passes : ++fails;
std::cout << "MonkeyMetric()(Point<MonkeyMetric>(" << lookup.first << ", 0))="
<< MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0))
<< " == " << lookup.second << ":- ";
std::cout << std::boolalpha << (MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0)) == lookup.
second) << std::endl;
MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first)) == lookup.second ? ++passes : ++fails;
std::cout << "MonkeyMetric()(Point<MonkeyMetric>(0," << lookup.first << "))="
<< MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first))
<< " == " << lookup.second << ":- ";
std::cout << std::boolalpha << (MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first)) == lookup.
second) << std::endl;
}
//Verify SolveMonkeyPuzzle::get_dmax()
std::cout << std::endl << "=====Testing SolveMonkeyPuzzle::get_dmax() =========== " << std::endl;
for (auto& lookup : d_max)
{
SolveMonkeyPuzzle(lookup.first).get_dmax() == lookup.second ? ++passes : ++fails;
std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_dmax()="
<< SolveMonkeyPuzzle(lookup.first).get_dmax()
<< " == " << lookup.second << ":- ";
std::cout << std::boolalpha << (SolveMonkeyPuzzle(lookup.first).get_dmax() == lookup.second) <<
std::endl;
}
//Verify count of sorted == count of quadrant
std::cout << std::endl << "=====Testing count by sorting == quadrant count =========== " << std::
endl;
unsigned by_sorting;
unsigned by_counting;
for (auto& lookup : d_max)
{
7C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp
by_counting = SolveMonkeyPuzzle(lookup.first).get_radial_count();
if (lookup.first <= 10)
{
by_sorting = SolveMonkeyPuzzle(lookup.first).get_sorted_count();
by_sorting == by_counting ? ++passes : ++fails;
std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_sorted_count()="
<< by_sorting
<< " == "
<< "SolveMonkeyPuzzle(" << lookup.first << ").get_radial_count()="
<< by_counting
<< ":- ";
std::cout << std::boolalpha
<< (by_sorting == by_counting) << std::endl;
}
}
//Verify total point counting
std::cout << std::endl << "=====Testing total point counter with no accessibility constraints =====
====== " << std::endl;
for (auto& lookup : d_max)
{
unsigned count = SolveMonkeyPuzzle(lookup.first).get_no_constraint_count();
std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_no_constraint_count()="
<< count
<< " == "
<< "(2*" << lookup.second << "+1)^2 =" << (2 * lookup.second + 1)*(2 * lookup.second + 1)
<< ":- ";
std::cout << std::boolalpha
<< (count == (2 * lookup.second + 1)*(2 * lookup.second + 1)) << std::endl;
}
std::cout << "===================== " << std::endl
<< "Results:" << std::endl
<< "===================== " << std::endl
<< "Passes = " << passes << ", fails=" << fails << ", number of points accessible to
monkey = "
<< SolveMonkeyPuzzle(19).get_full_constraint_count()
<< std::endl;
}
};
int main(void)
{
TestSuite tests;
tests.run();
return 0;
}

More Related Content

What's hot

L10
L10L10
L10
lksoo
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
Sayed Ahmed
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cpp
Alamgir Hossain
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
Francis Johny
 
Los dskn
Los dsknLos dskn
Los dskn
Brenda Jazmin
 
PyData NYC 2019
PyData NYC 2019PyData NYC 2019
PyData NYC 2019
Li Jin
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
Rahul Kolluri
 
Spark AI 2020
Spark AI 2020Spark AI 2020
Spark AI 2020
Li Jin
 
Swiftとメソッドのアレコレ
SwiftとメソッドのアレコレSwiftとメソッドのアレコレ
Swiftとメソッドのアレコレ
Nobuo Saito
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
جامعة القدس المفتوحة
 
C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
kasaragadda srinivasrao
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfilesmrecedu
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v PythonuJirka Vejrazka
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignment
Abdullah Al Shiam
 
Import java
Import javaImport java
Import java
heni2121
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Uma mohan
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
Alicia Pérez
 

What's hot (20)

L10
L10L10
L10
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cpp
 
Lecture09
Lecture09Lecture09
Lecture09
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
Los dskn
Los dsknLos dskn
Los dskn
 
PyData NYC 2019
PyData NYC 2019PyData NYC 2019
PyData NYC 2019
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame work
 
Spark AI 2020
Spark AI 2020Spark AI 2020
Spark AI 2020
 
Swiftとメソッドのアレコレ
SwiftとメソッドのアレコレSwiftとメソッドのアレコレ
Swiftとメソッドのアレコレ
 
Array
ArrayArray
Array
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
 
C Language Unit-3
C Language Unit-3C Language Unit-3
C Language Unit-3
 
Unit3 jwfiles
Unit3 jwfilesUnit3 jwfiles
Unit3 jwfiles
 
Magicke metody v Pythonu
Magicke metody v PythonuMagicke metody v Pythonu
Magicke metody v Pythonu
 
Computer graphics lab assignment
Computer graphics lab assignmentComputer graphics lab assignment
Computer graphics lab assignment
 
Import java
Import javaImport java
Import java
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadies
 
My favorite slides
My favorite slidesMy favorite slides
My favorite slides
 

Viewers also liked

Anacin Trends & Landscape
Anacin Trends & LandscapeAnacin Trends & Landscape
Anacin Trends & LandscapeJennie
 
Anacin Competitive Analysis
Anacin Competitive AnalysisAnacin Competitive Analysis
Anacin Competitive AnalysisJennie
 
1 mathematical challenge_problem
1 mathematical challenge_problem1 mathematical challenge_problem
1 mathematical challenge_problemRussell Childs
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
Russell Childs
 
Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UML
Russell Childs
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
Russell Childs
 

Viewers also liked (7)

Anacin Trends & Landscape
Anacin Trends & LandscapeAnacin Trends & Landscape
Anacin Trends & Landscape
 
Anacin Competitive Analysis
Anacin Competitive AnalysisAnacin Competitive Analysis
Anacin Competitive Analysis
 
1 mathematical challenge_problem
1 mathematical challenge_problem1 mathematical challenge_problem
1 mathematical challenge_problem
 
Algorithms devised for a google interview
Algorithms devised for a google interviewAlgorithms devised for a google interview
Algorithms devised for a google interview
 
Cpp11 sample linux
Cpp11 sample linuxCpp11 sample linux
Cpp11 sample linux
 
Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UML
 
Interview C++11 code
Interview C++11 codeInterview C++11 code
Interview C++11 code
 

Similar to 3 mathematical challenge_code

Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
Akira Maruoka
 
Javascript math boolean string date
Javascript math boolean string dateJavascript math boolean string date
Javascript math boolean string date
Frayosh Wadia
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
Yung-Yu Chen
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
exxonzone
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdf
indiaartz
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
Egor Bogatov
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
Thesis Scientist Private Limited
 
Cpl
CplCpl
The Canvas API for Rubyists
The Canvas API for RubyistsThe Canvas API for Rubyists
The Canvas API for Rubyists
deanhudson
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
HARSHSHARMA840
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
Mohammad Shaker
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in c
BUBT
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
Laurence Svekis ✔
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
SALU18
 
Task based Programming with OmpSs and its Application
Task based Programming with OmpSs and its ApplicationTask based Programming with OmpSs and its Application
Task based Programming with OmpSs and its Application
Facultad de Informática UCM
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
James Brotsos
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
Max Kleiner
 
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
Sonu880062
 

Similar to 3 mathematical challenge_code (20)

Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
Javascript math boolean string date
Javascript math boolean string dateJavascript math boolean string date
Javascript math boolean string date
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 
This is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdfThis is a C# project . I am expected to create as this image shows. .pdf
This is a C# project . I am expected to create as this image shows. .pdf
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Cpl
CplCpl
Cpl
 
The Canvas API for Rubyists
The Canvas API for RubyistsThe Canvas API for Rubyists
The Canvas API for Rubyists
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
Operators1.pptx
Operators1.pptxOperators1.pptx
Operators1.pptx
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Chapter 5 exercises Balagurusamy Programming ANSI in c
Chapter 5 exercises Balagurusamy Programming ANSI  in cChapter 5 exercises Balagurusamy Programming ANSI  in c
Chapter 5 exercises Balagurusamy Programming ANSI in c
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
JavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your codeJavaScript Advanced - Useful methods to power up your code
JavaScript Advanced - Useful methods to power up your code
 
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxerror 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docx
 
Task based Programming with OmpSs and its Application
Task based Programming with OmpSs and its ApplicationTask based Programming with OmpSs and its Application
Task based Programming with OmpSs and its Application
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loops
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...AI Lab menu for ptu students and easy to use and best quality and help for 6t...
AI Lab menu for ptu students and easy to use and best quality and help for 6t...
 

More from Russell Childs

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdf
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
Russell Childs
 
String searching
String searchingString searching
String searching
Russell Childs
 
Permute
PermutePermute
Permute
PermutePermute
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
Russell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
Russell Childs
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pages
Russell Childs
 
Relativity 2
Relativity 2Relativity 2
Relativity 2
Russell Childs
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
Russell Childs
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Russell Childs
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_table
Russell Childs
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016
Russell Childs
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcasting
Russell Childs
 
Interview uml design
Interview uml designInterview uml design
Interview uml design
Russell Childs
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_Childs
Russell Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
Russell Childs
 
K d tree_cpp
K d tree_cppK d tree_cpp
K d tree_cpp
Russell Childs
 

More from Russell Childs (20)

spinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdfspinor_quantum_simulator_user_guide_.pdf
spinor_quantum_simulator_user_guide_.pdf
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching o_n
String searching o_nString searching o_n
String searching o_n
 
String searching
String searchingString searching
String searching
 
Permute
PermutePermute
Permute
 
Permute
PermutePermute
Permute
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theorem
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pages
 
Relativity 2
Relativity 2Relativity 2
Relativity 2
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...
 
Shared_memory_hash_table
Shared_memory_hash_tableShared_memory_hash_table
Shared_memory_hash_table
 
Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016Full resume dr_russell_john_childs_2016
Full resume dr_russell_john_childs_2016
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcasting
 
Interview uml design
Interview uml designInterview uml design
Interview uml design
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problem
 
K d tree_cpp
K d tree_cppK d tree_cpp
K d tree_cpp
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 

3 mathematical challenge_code

  • 1. 1C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp /* * monkey_puzzle.cpp * * Created on: 29 Jun 2014 * Author: Russell John Childs */ //======================================================================================================= // COPYRIGHT NOTICE // This code sample and ideas embodied remain the property of Dr Russell John Childs, PhD, and have been // distributed as a representative example of my use of C++11 features, //========================================================================================================== ============ #include <iostream> #include <iomanip> #include <string> #include <set> #include <vector> #include <algorithm> #include <functional> //The answer to the riddle is 102485. //General "point" class that accepts a metric defining the "distance" associatated with the interval between two points. // It is debatable whether it is good design practice to tie a metric to a point, but it provides for type- safety in // not allowing two points with different metrics to be used to calculate the interval. template<typename Metric> class Point { public: //Simple ctor that sepcifies coords explicit Point(int x, int y) : m_x(x), m_y(y), m_is_accessible(true) { } //NOP dtor ~Point(void) { } //Function to calculate vector difference friend Point operator-(const Point& lhs, const Point& rhs) { return Point(lhs.m_x - rhs.m_x, lhs.m_y - rhs.m_y); } //Function that calculates radial distance from origin according to the specified metric. unsigned radius(void) const { return Metric()(*this); } //Binary predicate to be used by a sorted container to sort points by radial distance from origin friend bool operator<(const Point& lhs, const Point& rhs) { //Sort by radial distance from origin, then by x, then by y. return lhs.radius() < rhs.radius() || (lhs.radius() == rhs.radius() && lhs.m_x < rhs.m_x) || (lhs.radius() == rhs.radius() && lhs.m_x == rhs.m_x && lhs.m_y < rhs.m_y); } private: friend Metric; friend class SolveMonkeyPuzzle; int m_x; int m_y; bool m_is_accessible; };
  • 2. 2C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp //================== //Monkey's Metric = sum(abs(digit(x))) + sum(abs(digit(y))) //========== class MonkeyMetric { public: //Default Ctor MonkeyMetric(void) { } //NOP Dtor ~MonkeyMetric(void) { } //operator() // returns the distance between points using the monkey metric. By default, it resturns distance of point from origin. unsigned operator()(const Point<MonkeyMetric>& lhs, const Point<MonkeyMetric>& rhs = Point<MonkeyMetric> (0,0)) { //Lmabda computes sum(abs(digit(value))) auto sum_digits = [](unsigned value) { unsigned sum = 0; for (auto digit : std::to_string(value)) { sum += std::stoul(std::string(1,digit)); } return sum; }; return sum_digits(std::abs((lhs - rhs).m_x)) + sum_digits(std::abs((lhs - rhs).m_y)); } }; //================== //The solver class. Uses a counting method and a sorting method to compute number of points // accessible to the monkey for a given value for the maximum radius from the origin. //========== class SolveMonkeyPuzzle { public: //Ctor - takes as argument the maximum radial distance from origin the monkey may travel. explicit SolveMonkeyPuzzle(unsigned bounds) : m_bounds(bounds), m_dmax(0), m_parent_level{ 1, Point<MonkeyMetric>(0,0) } { //Compute the number of points that can be visited along X without exceeding //the maximum radial distacne from the origin while (Point<MonkeyMetric>(m_dmax, 0).radius() <= bounds) { ++m_dmax; } --m_dmax; //correction for overshoot. } //NOP Dtor ~SolveMonkeyPuzzle(void) { } //Accessor function for maximum number of points along X unsigned get_dmax(void) const { return m_dmax; } //This function simply creates a grid quadrant (0, d_max) by (0, d_max) // iterates over all points in this quadrant, adding them to a sorted set. // Finally it returns the number of sorted points whose radial distance from
  • 3. 3C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp // the origin is <= maximum. unsigned get_sorted_count(void) { std::set<Point<MonkeyMetric>> points; for (unsigned x = 0; x <= m_dmax; ++x) { for (unsigned y = 0; y <= m_dmax; ++y) { points.insert(Point<MonkeyMetric>(x, y)); } } /*if (m_bounds == 1) { for (auto& point : points) { std::cout << "Point(" << point.m_x << "," << point.m_y << ")" << std::endl; } }*/ return std::count_if(points.begin(), points.end(), [this](const Point<MonkeyMetric>& point) {return point.radius() <= this->m_bounds;} ); } // Key function - this is the function that solves the monkey puzzle for one quadrant. // //This function simply creates a grid quadrant (0, d_max) by (0, d_max) // iterates over all points in this quadrant, incrementing a counter if the maximum // radial distance is not exceeded and at least one parent tree node is accessible. unsigned get_accessible_quad_count(std::function<bool(const Point<MonkeyMetric>&)> constraints, bool display = false) { unsigned count = 0; for (unsigned level = 1; level <= 2*m_dmax; ++level) //loop over levels { std::vector<Point<MonkeyMetric>> current_level; //current_level.reserve(level+1); unsigned i = 0; for (unsigned y = std::max(level,m_dmax)-m_dmax; y <= std::min(level, m_dmax); ++y) //loop over nodes, left to right { current_level.push_back( Point<MonkeyMetric>(level-y, y) ); //assign point to node current_level[i].m_is_accessible = constraints(current_level[i]);//Apply constraints count += (current_level[i].m_is_accessible ? 1 : 0); //Update quadrant count ++i; } m_parent_level = std::move(current_level); } return count+1; //include point at origin } //This function simply creates a grid quadrant (0, d_max) by (0, d_max) // iterates over all points in this quadrant, incrementing a counter if the maximum // radial distance is not exceeded. unsigned get_radial_count(bool display = false) { auto constraints = [this](const Point<MonkeyMetric>& point){ return (point.radius() <= this-> m_bounds); }; return get_accessible_quad_count(constraints); } //This function converts from quadrant count to full count over all four quadrants unsigned get_total_from_quad_count( unsigned quad_count ) { // Multiplying quad by 4 gives overcounting of the X and Y axis points //so subtract 4*(d_max+1), then need to add origin point return 4 * quad_count - 4 * (m_dmax + 1) + 1; } //This function simply creates a grid quadrant (0, d_max) by (0, d_max) // iterates over all points in this quadrant, incrementing a counter if the maximum
  • 4. 4C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp // radial distance is not exceeded. unsigned get_full_constraint_count(bool display = false) { auto constraints = [this](const Point<MonkeyMetric>& point) { int level = point.m_x + point.m_y; int index = point.m_y - (level <= static_cast<int>(m_dmax) ? 0 : (level-m_dmax)); unsigned left_parent = std::max(0, index - 1); unsigned right_parent = std::min(index, static_cast<int>(this->m_parent_level.size()) - 1); return (point.radius() <= this->m_bounds && (this->m_parent_level[left_parent].m_is_accessible || this->m_parent_level[right_parent].m_is_accessible)); }; return get_total_from_quad_count(get_accessible_quad_count(constraints)); } //This function simply creates a grid quadrant (0, d_max) by (0, d_max) // iterates over all points in this quadrant, incrementing a counter to give total // point count unsigned get_no_constraint_count(bool display = false) { auto constraints = [this](const Point<MonkeyMetric>& point) { return true; }; return get_total_from_quad_count(get_accessible_quad_count(constraints)); } //This function displays the grid of points for a given bounds. // "." are accessible points // "X" are inaccessible points // "-" are points that lie within bounds but are inaccessible because // the monkey cannot find a path to them void display(void) { //Get the fully constrained points std::set<Point<MonkeyMetric>> accessible_points; accessible_points.insert(Point<MonkeyMetric>(0, 0)); std::set<Point<MonkeyMetric>> partially_constrained_points; auto constraints = [this, &accessible_points, &partially_constrained_points](const Point <MonkeyMetric>& point) { int level = point.m_x + point.m_y; int index = point.m_y - (level <= static_cast<int>(m_dmax) ? 0 : (level - m_dmax)); unsigned left_parent = std::max(0, index - 1); unsigned right_parent = std::min(index, static_cast<int>(this->m_parent_level.size()) - 1); bool is_accessible = (point.radius() <= this->m_bounds && (this->m_parent_level[left_parent].m_is_accessible || this->m_parent_level[right_parent].m_is_accessible)); if( is_accessible) accessible_points.insert(point); bool is_partial = (point.radius() <= this->m_bounds && !(this->m_parent_level[left_parent].m_is_accessible || this->m_parent_level[right_parent].m_is_accessible)); if (is_accessible) accessible_points.insert(point); if( is_partial )partially_constrained_points.insert(point); return is_accessible; }; get_accessible_quad_count(constraints); for (int x = -static_cast<int>(m_dmax); x <= static_cast<int>(m_dmax); ++x) { std::cout << std::endl; for (int y = -static_cast<int>(m_dmax); y <= static_cast<int>(m_dmax); ++y) { //Convert to quadrant coord by simply taking |x|, |y| std::string s; auto f = accessible_points.find( Point<MonkeyMetric>(std::abs(x), std::abs(y)));
  • 5. 5C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp s = (f != accessible_points.end() ? "." : "X"); f = partially_constrained_points.find( Point<MonkeyMetric>(std::abs(x), std::abs(y))); if (f != partially_constrained_points.end()) s = "+"; std::cout << s; } } } private: unsigned m_bounds; unsigned m_dmax; std::vector<Point<MonkeyMetric>> m_parent_level; }; //======================================= //Very simple and non-exhaustive test harness //====================================== struct TestSuite { //Call from main() void run(void) { //Begin with the solution to the puzzle std::cout << "==============================================================" << std::endl; std::cout << "Calculating result please wait ..." << std::endl; std::cout << std::endl << "The answer to the riddle is: " << SolveMonkeyPuzzle(19). get_full_constraint_count() << std::endl; std::cout << "==============================================================" << std::endl; //Now run tests std::cout << "==============================================================" << std::endl; std::cout << std::endl << "Executing tests" << std::endl; std::cout << "==============================================================" << std::endl; //Run global test allowing visual inspection of accessible points found by algorithm unsigned bounds = 10; std::cout << std::endl << "Global test of code: Accessibility map for n=: " << bounds << ". 'X'=inaccessible, '+'=within bounds, but no path connecting with origin, '.'=accessible ." << std::endl; SolveMonkeyPuzzle(bounds).display(); std::cout << std::endl << std::endl << "Hit any key except Q to continue with tests. Hit Q to quit and keep results in console" << std::endl; char c; std::cin >> c; if (c == 'Q') { std::cout << "Display is paused. Hit any key to quit application"; std::cin >> c; return; } //Pre-calculated radius values std::pair<int, unsigned> radius[] = { std::make_pair(1, 1), std::make_pair(-2, 2), std::make_pair(3, 3), std::make_pair(-4, 4), std::make_pair(5, 5), std::make_pair(-6, 6), std::make_pair(7, 7), std::make_pair(-8, 8), std::make_pair(9, 9), std::make_pair(-10, 1), std::make_pair(11, 2), std::make_pair(-12, 3), std::make_pair(13, 4), std::make_pair(-14, 5), std::make_pair(15, 6), std::make_pair(-16, 7), std::make_pair(17, 8), std::make_pair(-18, 9),
  • 6. 6C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp std::make_pair(19, 10) }; //Pre-calculated d_max values std::pair<unsigned, unsigned> d_max[]= { std::make_pair(1, 1), std::make_pair(2, 2), std::make_pair(3, 3), std::make_pair(4, 4), std::make_pair(5, 5), std::make_pair(6, 6), std::make_pair(7, 7), std::make_pair(8, 8), std::make_pair(9, 18), std::make_pair(10, 28), std::make_pair(11, 38), std::make_pair(12, 48), std::make_pair(13, 58), std::make_pair(14, 68), std::make_pair(15, 78), std::make_pair(16, 88), std::make_pair(17, 98), std::make_pair(18, 198), std::make_pair(19, 298) }; //Keep count of passes and fails unsigned passes = 0; unsigned fails = 0; //Verify Metric::operator() std::cout << "=====Testing Metric::operator() =========== " << std::endl; for (auto& lookup : radius) { MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0)) == lookup.second ? ++passes : ++fails; std::cout << "MonkeyMetric()(Point<MonkeyMetric>(" << lookup.first << ", 0))=" << MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0)) << " == " << lookup.second << ":- "; std::cout << std::boolalpha << (MonkeyMetric()(Point<MonkeyMetric>(lookup.first, 0)) == lookup. second) << std::endl; MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first)) == lookup.second ? ++passes : ++fails; std::cout << "MonkeyMetric()(Point<MonkeyMetric>(0," << lookup.first << "))=" << MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first)) << " == " << lookup.second << ":- "; std::cout << std::boolalpha << (MonkeyMetric()(Point<MonkeyMetric>(0, lookup.first)) == lookup. second) << std::endl; } //Verify SolveMonkeyPuzzle::get_dmax() std::cout << std::endl << "=====Testing SolveMonkeyPuzzle::get_dmax() =========== " << std::endl; for (auto& lookup : d_max) { SolveMonkeyPuzzle(lookup.first).get_dmax() == lookup.second ? ++passes : ++fails; std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_dmax()=" << SolveMonkeyPuzzle(lookup.first).get_dmax() << " == " << lookup.second << ":- "; std::cout << std::boolalpha << (SolveMonkeyPuzzle(lookup.first).get_dmax() == lookup.second) << std::endl; } //Verify count of sorted == count of quadrant std::cout << std::endl << "=====Testing count by sorting == quadrant count =========== " << std:: endl; unsigned by_sorting; unsigned by_counting; for (auto& lookup : d_max) {
  • 7. 7C:my_docsvirtual_machinesvmware_playershared_foldergeneral3_mathematical_challenge_code.cpp by_counting = SolveMonkeyPuzzle(lookup.first).get_radial_count(); if (lookup.first <= 10) { by_sorting = SolveMonkeyPuzzle(lookup.first).get_sorted_count(); by_sorting == by_counting ? ++passes : ++fails; std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_sorted_count()=" << by_sorting << " == " << "SolveMonkeyPuzzle(" << lookup.first << ").get_radial_count()=" << by_counting << ":- "; std::cout << std::boolalpha << (by_sorting == by_counting) << std::endl; } } //Verify total point counting std::cout << std::endl << "=====Testing total point counter with no accessibility constraints ===== ====== " << std::endl; for (auto& lookup : d_max) { unsigned count = SolveMonkeyPuzzle(lookup.first).get_no_constraint_count(); std::cout << "SolveMonkeyPuzzle(" << lookup.first << ").get_no_constraint_count()=" << count << " == " << "(2*" << lookup.second << "+1)^2 =" << (2 * lookup.second + 1)*(2 * lookup.second + 1) << ":- "; std::cout << std::boolalpha << (count == (2 * lookup.second + 1)*(2 * lookup.second + 1)) << std::endl; } std::cout << "===================== " << std::endl << "Results:" << std::endl << "===================== " << std::endl << "Passes = " << passes << ", fails=" << fails << ", number of points accessible to monkey = " << SolveMonkeyPuzzle(19).get_full_constraint_count() << std::endl; } }; int main(void) { TestSuite tests; tests.run(); return 0; }