Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.
Computer graphics lab report with code in cppAlamgir Hossain
This is the lab report for computer graphics in cpp language. Basically this course is only for the computer science and engineering students.
Problem list:
1.Program for the generation of Bresenham Line Drawing.
2. Program for the generation of Digital Differential Analyzer (DDA) Line Drawing.
3. Program for the generation of Midpoint Circle Drawing.
4. Program for the generation of Midpoint Ellipse Drawing.
5. Program for the generation of Translating an object.
6. Program for the generation of Rotating an Object.
7. Program for the generation of scaling an object.
All programs are coaded in cpp language .
En esta charla veremos con detalle algunas de las construcciones más pythonicas y las posibilidades de expresar de forma clara, concisa y elegante cosas que en otros lenguajes nos obligarían a dar muchos rodeos.
A veces es fácil olvidar algunos recursos como que una función puede devolver varios valores, cómo manipular listas y diccionarios de forma sencilla, contextos, generadores... En esta charla veremos de forma entretenida y práctica cómo mejorar nuestro nivel de Python "nativo".
Computer graphics lab report with code in cppAlamgir Hossain
This is the lab report for computer graphics in cpp language. Basically this course is only for the computer science and engineering students.
Problem list:
1.Program for the generation of Bresenham Line Drawing.
2. Program for the generation of Digital Differential Analyzer (DDA) Line Drawing.
3. Program for the generation of Midpoint Circle Drawing.
4. Program for the generation of Midpoint Ellipse Drawing.
5. Program for the generation of Translating an object.
6. Program for the generation of Rotating an Object.
7. Program for the generation of scaling an object.
All programs are coaded in cpp language .
En esta charla veremos con detalle algunas de las construcciones más pythonicas y las posibilidades de expresar de forma clara, concisa y elegante cosas que en otros lenguajes nos obligarían a dar muchos rodeos.
A veces es fácil olvidar algunos recursos como que una función puede devolver varios valores, cómo manipular listas y diccionarios de forma sencilla, contextos, generadores... En esta charla veremos de forma entretenida y práctica cómo mejorar nuestro nivel de Python "nativo".
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
Being a slow interpreter, Python may drive a system to deliver utmost speed if some guidelines are followed. The key is to treat programming languages as syntactic sugar to the machine code. It expedites the workflow of timing, iterative design, automatic testing, optimization, and realize an HPC system balancing the time to market and quality of code.
Speed is the king. 10x productive developers change business. So does 10x faster code. Python is 100x slower than C++ but it only matters when you really use Python to implement number-crunching algorithms. We should not do that, and instead go directly with C++ for speed. It calls for strict disciplines of software engineering and code quality, but it should be noted that here the quality is defined by the runtime and the time to market.
The presentation focuses on the Python side of the development workflow. It is made possible by confining C++ in architecture defined by the Python code, which realizes most of the software engineering. The room for writing fast C++ code is provided by pybind11 and careful design of typed data objects. The data objects hold memory buffers exposed to Python as numpy ndarrays for direct access for speed.
#ifndef RATIONAL_H if this compiler macro is not defined #def.pdfexxonzone
#ifndef RATIONAL_H // if this compiler macro is not defined
#define RATIONAL_H // then define it so this file will not be processed again
#include \"stdafx.h\" // use only for Microsoft Visual Studio C++
#include
using namespace std;
class Rational
{
// Friend functions are actually declared outside the scope of the
// class but have the right to access public and private data and
// member function members that belong to the class. The friend
// function below gives the << operator for ostreams (including cout)
// the ability to output a Rational object by accessing its member data.
friend ostream &operator<< (ostream &out, Rational const &r);
public:
Rational(int num = 0, int denom = 1); // also provides default constructor
Rational add(Rational right);
Rational operator+ (Rational right); // + addition operator
Rational operator+= (Rational right); // += addition assignment operator
Rational operator- (Rational right); // + addition operator
Rational operator-= (Rational right); // += addition assignment operator
void display();
operator double() const; // convert Rational to double
private:
int numerator;
int denominator;
// helper functions are private and not accessible by the main program
int LCD(int v1, int v2);
Rational setRational(int n, int d);
};
#endif
#include \"stdafx.h\"
#include
#include \"Rational.h\"
using namespace std;
// By using the default parameter settings in Rational.h, this
// constructor also provides the default constructor Rational()
Rational::Rational(int num, int denom)
{
setRational(num, denom); // set numerator and denominator, reduce fraction, fix the sign
}
// Helper function to fix a zero denominator and fix the sign if denominator is negative
Rational Rational::setRational(int n, int d) // helper function
{
numerator = n;
denominator = d;
// if denominator == 0 then set it = 1
if (denominator == 0)
denominator = 1;
if (denominator < 0) // if denominator is neg, multiply num and denom by -1
{
numerator = -numerator; // fix sign of numerator +/-
denominator = -denominator; // denominator always +
}
int lcd = LCD(numerator, denominator);
if (denominator != 0)
{
numerator /= lcd;
denominator /= lcd;
}
return *this; // return the current object
}
// find the lowest common divisor using a recursive function
int Rational::LCD(int v1, int v2)
{
if (v2 == 0) return v1;
else return LCD(v2, v1%v2);
}
Rational Rational::add(Rational right)
{
int newNumerator;
int newDenominator;
newNumerator = numerator*right.denominator + right.numerator*denominator;
newDenominator = denominator * right.denominator;
// create a new Rational object and return it
return setRational(newNumerator, newDenominator);
}
// the operator+ method does the same thing as the add method
Rational Rational::operator+ (Rational right)
{
int newNumerator;
int newDenominator;
newNumerator = numerator*right.denominator + right.numerator*denominator;
newDenominator = denominator * right.denominator;
// create a new Rational object and return it
return .
This is a C# project . I am expected to create as this image shows. .pdfindiaartz
This is a C# project . I am expected to create as this image shows. If the image isnot clearly
showing , it\'s the Chegg\'s system. Please , if you see it quit long, assist me with the starting and
hinting bulltes point or functions that may simplify. Thannks...
The design of the Calculator form
Operation
· To clear the contents of memory, the user clicks the MC button. To save the value that’s
currently displayed in memory, the user clicks the MS button. To recall the value that’s currently
in memory and display it in the calculator, the user clicks the MR button. And to add the value
that’s currently displayed to the value in memory, the user clicks the M+ button.
· An M is displayed in the box above the MC button whenever the memory contains a value.
· See project 12-1 for additional details.
Specifications
· Create a class named MemoryCalculator that inherits the Calculator class described in
project 12-1. The MemoryCalculator class should add properties and methods as needed to
implement the memory function.
Note:
· MemoryCalculator class design:
Method Description
MemoryStore Stores the calculator’s current value in memory.
MemoryRecall Sets the calculator’s current value to the value stored in memory.
MemoryAdd Adds the calculator’s current value to the value currently stored in
memory.
MemoryClear Clears the current memory value.
Solution
Calculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public class Calculator
{
public decimal currentValue;
private decimal operand1;
public decimal operand2;
private Operator op;
public enum Operator { Addd, Subtract, Multiply, Divide, None };
//Needed to be changed from private to public
public Calculator()
{
this.currentValue = 0;
this.operand1 = 0;
this.operand2 = 0;
this.op = Operator.None;
}
public decimal CurrentValue
{
get { return this.currentValue; }
}
public void Clear()
{
this.currentValue = 0;
this.operand1 = 0;
this.operand2 = 0;
this.op = Operator.None;
}
public void Add(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Addd;
}
public void Subtract(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Subtract;
}
public void Multiply(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Multiply;
}
public void Divide(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Divide;
}
public void Equals(decimal val)
{
operand2 = val;
switch (this.op)
{
case Operator.Addd:
currentValue = operand1 + operand2;
break;
case Operator.Subtract:
currentValue = operand1 - operand2;
break;
case Operator.Multiply:
currentValue = operand1 * operand2;
break;
case Operator.Divide:
//Try catch to prevent dividing by zero
try
{
currentValue = operand1 / operand2;
}
catch (DivideByZeroException)
{
MessageBox.Show(\"You cannot divide by zero\", \"Error!\");
}
break;
case Opera.
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-course-plus/?couponCode=SLIDESHARE
Useful methods and JavaScript code snippets power up your code and make even more happen with it.
This course is perfect for anyone who has fundamental JavaScript experience and wants to move to the next level. Use and apply more advanced code, and do more with JavaScript.
Everything you need to learn more about JavaScript
Source code is included
60+ page Downloadable PDF guide with resources and code snippets
3 Challenges to get you coding try the code
demonstrating useful JavaScript methods that can power up your code and make even more happen with it.
Course lessons will cover
JavaScript Number Methods
JavaScript String Methods
JavaScript Math - including math random
DOMContentLoaded - DOM ready when the document has loaded.
JavaScript Date - Date methods and how to get set and use date.
JavaScript parse and stringify - strings to objects back to strings
JavaScript LocalStorage - store variables in the user browser
JavaScript getBoundingClientRect() - get the dimensions of an element
JavaScript Timers setTimeout() setInterval() requestAnimationFrame() - Run code when you want too
encodeURIComponent - encoding made easy
Regex - so powerful use it to get values from your string
prototype - extend JavaScript objects with customized powers
Try and catch - perfect for error and testing
Fetch xHR requests - bring content in from servers
and more
No libraries, no shortcuts just learning JavaScript making it DYNAMIC and INTERACTIVE web application.
Step by step learning with all steps included.
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
error 2.pdf
10/13/16, 6(46 PM01_error
Page 1 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sys
Error Definitions
Following is an example for the concept of absolute error, relative error and decimal precision:
We shall test the approximation to common mathematical constant, . Compute the absolute and relative
errors along with the decimal precision if we take the approximate value of .
In [ ]: # We can use the formulas you derieved above to calculate the actual n
umbers
absolute_error = np.abs(np.exp(1) - 2.718)
relative_error = absolute_error/np.exp(1)
print "The absolute error is "+str(absolute_error)
print "The relative error is "+str(relative_error)
Machine epsilon is a very important concept in floating point error. The value, even though miniscule, can
easily compund over a period to cause huge problems.
Below we see a problem demonstating how easily machine error can creep into a simple piece of code:
In [ ]: a = 4.0/3.0
b = a - 1.0
c = 3*b
eps = 1 - c
print 'Value of a is ' +str(a)
print 'Value of b is ' +str(b)
print 'Value of c is ' +str(c)
print 'Value of epsilon is ' +str(eps)
Ideally eps should be 0, but instead we see the machine epsilon and while the value is small it can lead to
issues.
e
e = 2.718
10/13/16, 6(46 PM01_error
Page 2 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: print "The progression of error:"
for i in range(1,20):
print str(abs((10**i)*c - (10**i)))
The largest floating point number
The formula for obtaining the number is shown below, instead of calculating the value we can use the
system library to find this value.
In [ ]: maximum = (2.0-eps)*2.0**1023
print sys.float_info.max
print 'Value of maximum is ' +str(maximum)
The smallest floating point number
The formula for obtaining the number is shown below. Similarly the value can be found using the system
library to find this value.
In [ ]: minimum = eps*2.0**(-1022)
print sys.float_info.min
print sys.float_info.min*sys.float_info.epsilon
print 'Value of minimum is ' +str(minimum)
As we try to compute a number bigger than the aforementioned, largest floating point number we see weird
errors. The computer assigns infinity to these values.
In [ ]: overflow = maximum*10.0
print 'Value of overflow is ' +str(overflow)
As we try to compute a number smaller than the aforementioned smallest floating point number we see that
the computer assigns it the value 0. We actually lose precision in this case.
10/13/16, 6(46 PM01_error
Page 3 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [1]: underflow = minimum/2.0
print 'Value of underflow is ' +str(underflow)
Truncation error is a very common form of error you will keep seing in the area of Numerical
Analysis/Computing.
Here we will look at the classic Calculus example of the approximation near 0. We c ...
In this article you will learn hot to use tensorflow Softmax Classifier estimator to classify MNIST dataset in one script.
This paper introduces also the basic idea of a artificial neural network.
This is the user guide for the quantum simulator I have developed. It includes tutorials on advanced quantum mechanics, quantum algorithms and geometric algebra, together with examples of using the simulator do quantum mechanics, Special Relativity, geometric algebra and quantum computing.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
An O(n+m) in time and O(1) in space search-algorithm for substr, length m, in target string, length n. Simpler than trie or Knuth-Morris-Pratt. Can be reduced to O(n) using Group Theoretic O(1)-updatable hash that replaces the cumulative sum, which requires an O(m) verification step because "+" is commutative and cannot distinguish between anagrams: a+b+c = a+c+b = c+a+b etc. I am not uploading the hash, because it means giving away R&D I do in quantum simulations.
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element
array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Russell Childs
Simple demo of a framework I wrote for doing quantum mechanics in C++. It uses Dirac bras, kets, inner & tensor products, operators and so forth for the linear algebra of QM.
UML design for C++11 written to solve a problem at interview, please also see "Interview C++11 code". The UML design can be zoomed to render it more legible.
Example of Dynamic Programming to achieve O(n).
Interview question: N houses, each with weighting on value of goods. How can a burglar maximise profit if they are not allowed to visit neighbouring houses?
Solution: optimum(i) = max( optimum(i-1)-w(i-1)+w(i) , optimum(i-2)+w(i) )
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
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),