SlideShare a Scribd company logo
1 of 7
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

Introduction to c
Introduction to cIntroduction to c
Introduction to cSayed 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 cppAlamgir Hossain
 
ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 
PyData NYC 2019
PyData NYC 2019PyData NYC 2019
PyData NYC 2019Li Jin
 
Collection frame work
Collection  frame workCollection  frame work
Collection frame workRahul Kolluri
 
Spark AI 2020
Spark AI 2020Spark AI 2020
Spark AI 2020Li Jin
 
Swiftとメソッドのアレコレ
SwiftとメソッドのアレコレSwiftとメソッドのアレコレ
SwiftとメソッドのアレコレNobuo Saito
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعةجامعة القدس المفتوحة
 
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 assignmentAbdullah Al Shiam
 
Import java
Import javaImport java
Import javaheni2121
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
Beautiful python - PyLadies
Beautiful python - PyLadiesBeautiful python - PyLadies
Beautiful python - PyLadiesAlicia 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 interviewRussell Childs
 
Simple shared mutex UML
Simple shared mutex UMLSimple shared mutex UML
Simple shared mutex UMLRussell 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 dateFrayosh Wadia
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for SpeedYung-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.pdfexxonzone
 
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. .pdfindiaartz
 
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 RyuJITEgor Bogatov
 
The Canvas API for Rubyists
The Canvas API for RubyistsThe Canvas API for Rubyists
The Canvas API for Rubyistsdeanhudson
 
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 JasmineRaimonds Simanovskis
 
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 cBUBT
 
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 codeLaurence 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.docxSALU18
 
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 ApplicationFacultad de Informática UCM
 
Ch02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsCh02 primitive-data-definite-loops
Ch02 primitive-data-definite-loopsJames Brotsos
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2suitzero
 

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
 
3장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_23장 자동적으로 움직이는 게임 에이전트 생성법_2
3장 자동적으로 움직이는 게임 에이전트 생성법_2
 

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_.pdfRussell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theoremRussell Childs
 
Feature extraction using adiabatic theorem
Feature extraction using adiabatic theoremFeature extraction using adiabatic theorem
Feature extraction using adiabatic theoremRussell Childs
 
Wavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesWavelets_and_multiresolution_in_two_pages
Wavelets_and_multiresolution_in_two_pagesRussell 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_tableRussell 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_2016Russell Childs
 
Design pattern to avoid downcasting
Design pattern to avoid downcastingDesign pattern to avoid downcasting
Design pattern to avoid downcastingRussell Childs
 
Full_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsFull_resume_Dr_Russell_John_Childs
Full_resume_Dr_Russell_John_ChildsRussell Childs
 
Dynamic programming burglar_problem
Dynamic programming burglar_problemDynamic programming burglar_problem
Dynamic programming burglar_problemRussell 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

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Recently uploaded (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

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; }