<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "WrapHelper.h"

#include "../player/KeyEvent.h"
#include "../player/MouseEvent.h"
#include "../player/TouchEvent.h"
#include "../player/VisibleNode.h"
#include "../player/TrackerEventSource.h"

#include <boost/shared_ptr.hpp>
#include <string>

using namespace boost::python;
using namespace avg;
using namespace std;

class IEventSourceWrapper : public IEventSource, public wrapper<IEventSource> {
    public:
        IEventSourceWrapper(const std::string& name)
            : IEventSource(name)
        {
        }

        IEventSourceWrapper(const IEventSource& eventSource)
            : IEventSource(eventSource)
        {
        }

        IEventSourceWrapper(const IEventSourceWrapper& eventSourceWrapper)
            : IEventSource(eventSourceWrapper)
        {
        }

        virtual void start() {
            if (override startMethod = this->get_override("start")) {
                startMethod();
            }
            IEventSource::start();
        }

        void default_start() {
            return this->IEventSource::start();
        }

        virtual std::vector<EventPtr> pollEvents() {
            return this->get_override("pollEvents")();
        }

};

void export_event()
{
    boost::python::to_python_converter<vector<TouchEventPtr>,
        to_tuple<vector<TouchEventPtr> > >();

    boost::python::to_python_converter<ContourSeq, to_list<ContourSeq> >();

    from_python_sequence<ContourSeq, variable_capacity_policy>();
    from_python_sequence<vector<EventPtr>, variable_capacity_policy>();

    class_<Event, boost::noncopyable>("Event", init<Event::Type, Event::Source, optional<int> >())
        .add_property("type", &Event::getType)
        .add_property("when", &Event::getWhen)
        .add_property("eventsource",
                      make_function(&Event::getEventSource,
                                    return_value_policy<copy_const_reference>()))
        .add_property("eventsourcename",
                      make_function(&Event::getEventSourceName,
                                    return_value_policy<copy_const_reference>()))
    ;

    class_<CursorEvent, bases<Event> >("CursorEvent",
                                       init<int, Event::Type, const IntPoint&, Event::Source>())
        .add_property("source", &CursorEvent::getSource)
        .add_property("pos", &CursorEvent::getPos)
        .add_property("x", &CursorEvent::getXPosition)
        .add_property("y", &CursorEvent::getYPosition)
        .add_property("cursorid", &CursorEvent::getCursorID, &CursorEvent::setCursorID)
        .add_property("node", &CursorEvent::getElement)
    ;

    enum_<Event::Type>("Type")
        .value("KEYUP", Event::KEYUP)
        .value("KEYDOWN", Event::KEYDOWN)
        .value("CURSORMOTION", Event::CURSORMOTION)
        .value("CURSORUP", Event::CURSORUP)
        .value("CURSORDOWN", Event::CURSORDOWN)
        .value("CURSOROVER", Event::CURSOROVER)
        .value("CURSOROUT", Event::CURSOROUT)
        .value("CUSTOMEVENT", Event::CUSTOMEVENT)
        .value("RESIZE", Event::RESIZE)
        .value("QUIT", Event::QUIT)
        .export_values()
    ;

    enum_<CursorEvent::Source>("Source")
        .value("MOUSE", CursorEvent::MOUSE)
        .value("TOUCH", CursorEvent::TOUCH)
        .value("TRACK", CursorEvent::TRACK)
        .value("CUSTOM", Event::CUSTOM)
        .value("NONE", Event::NONE)
        .export_values()
    ;

    enum_<int>("KeyModifier")
        .value("KEYMOD_NONE", key::KEYMOD_NONE)
        .value("KEYMOD_LSHIFT", key::KEYMOD_LSHIFT)
        .value("KEYMOD_RSHIFT", key::KEYMOD_RSHIFT)
        .value("KEYMOD_LCTRL", key::KEYMOD_LCTRL)
        .value("KEYMOD_RCTRL", key::KEYMOD_RCTRL)
        .value("KEYMOD_LALT", key::KEYMOD_LALT)
        .value("KEYMOD_RALT", key::KEYMOD_RALT)
        .value("KEYMOD_LMETA", key::KEYMOD_LMETA)
        .value("KEYMOD_RMETA", key::KEYMOD_RMETA)
        .value("KEYMOD_NUM", key::KEYMOD_NUM)
        .value("KEYMOD_CAPS", key::KEYMOD_CAPS)
        .value("KEYMOD_MODE", key::KEYMOD_MODE)
        .value("KEYMOD_RESERVED", key::KEYMOD_RESERVED)
        .value("KEYMOD_CTRL", key::KEYMOD_CTRL)
        .value("KEYMOD_SHIFT", key::KEYMOD_SHIFT)
        .value("KEYMOD_ALT", key::KEYMOD_ALT)
        .value("KEYMOD_META", key::KEYMOD_META)
        .export_values()
    ;

    class_<KeyEvent, bases<Event> >("KeyEvent", no_init)
        .add_property("scancode", &KeyEvent::getScanCode)
        .add_property("keycode", &KeyEvent::getKeyCode)
        .add_property("keystring", make_function(&KeyEvent::getKeyString,
                return_value_policy<copy_const_reference>()))
        .add_property("unicode", &KeyEvent::getUnicode)
        .add_property("modifiers", &KeyEvent::getModifiers)
    ;

    class_<MouseEvent, bases<Event> >("MouseEvent", no_init)
        .add_property("source", &MouseEvent::getSource)
        .add_property("leftbuttonstate", &MouseEvent::getLeftButtonState)
        .add_property("middlebuttonstate", &MouseEvent::getMiddleButtonState)
        .add_property("rightbuttonstate", &MouseEvent::getRightButtonState)
        .add_property("pos", &MouseEvent::getPos)
        .add_property("x", &MouseEvent::getXPosition)
        .add_property("y", &MouseEvent::getYPosition)
        .add_property("cursorid", &MouseEvent::getCursorID)
        .add_property("button", &MouseEvent::getButton)
        .add_property("node", &MouseEvent::getElement)
        .add_property("speed", make_function(&MouseEvent::getSpeed,
                return_value_policy<copy_const_reference>()))
        .add_property("lastdownpos", &CursorEvent::getLastDownPos)
    ;

    class_<TouchEvent, bases<Event> >("TouchEvent", no_init)
        .add_property("source", &TouchEvent::getSource)
        .add_property("area", &TouchEvent::getArea)
        .add_property("orientation", &TouchEvent::getOrientation)
        .add_property("eccentricity", &TouchEvent::getEccentricity)
        .add_property("pos", &TouchEvent::getPos)
        .add_property("x", &TouchEvent::getXPosition)
        .add_property("y", &TouchEvent::getYPosition)
        .add_property("cursorid", &TouchEvent::getCursorID)
        .add_property("node", &TouchEvent::getElement)
        .add_property("center", make_function(&TouchEvent::getCenter,
                return_value_policy<copy_const_reference>()))
        .add_property("majoraxis", make_function(&TouchEvent::getMajorAxis,
                return_value_policy<copy_const_reference>()))
        .add_property("minoraxis", make_function(&TouchEvent::getMinorAxis,
                return_value_policy<copy_const_reference>()))
        .add_property("speed", make_function(&TouchEvent::getSpeed,
                return_value_policy<copy_const_reference>()))
        .add_property("handorientation", &TouchEvent::getHandOrientation)
        .def("getRelatedEvents", &TouchEvent::getRelatedEvents)
        .def("getContour", &TouchEvent::getContour)
        .add_property("lastdownpos", &CursorEvent::getLastDownPos)
        ;

    enum_<TrackerImageID>("TrackerImageID")
        .value("IMG_CAMERA", TRACKER_IMG_CAMERA)
        .value("IMG_DISTORTED", TRACKER_IMG_DISTORTED)
        .value("IMG_NOHISTORY", TRACKER_IMG_NOHISTORY)
        .value("IMG_HISTOGRAM", TRACKER_IMG_HISTOGRAM)
        .value("IMG_FINGERS", TRACKER_IMG_FINGERS)
        .value("IMG_HIGHPASS", TRACKER_IMG_HIGHPASS)
        .export_values()
    ;

    class_<IEventSourcePtr>("IEventSource")
    ;

    class_<IEventSourceWrapper, boost::shared_ptr<IEventSourceWrapper> >("EventSource", init<const std::string&>())
        .def("start", &IEventSource::start, &IEventSourceWrapper::default_start)
        .def("pollEvents", pure_virtual(&IEventSource::pollEvents))
        .add_property("name",
                      make_function(&IEventSource::getName,
                                    return_value_policy<copy_const_reference>()))
    ;

    class_<TrackerEventSource, boost::noncopyable>("Tracker", no_init)
        .def("getImage", &TrackerEventSource::getImage,
            return_value_policy<manage_new_object>())
        .def("getDisplayROIPos", &TrackerEventSource::getDisplayROIPos)
        .def("getDisplayROISize", &TrackerEventSource::getDisplayROISize)
        .def("saveConfig", &TrackerEventSource::saveConfig)
        .def("resetHistory", &TrackerEventSource::resetHistory)
        .def("setDebugImages", &TrackerEventSource::setDebugImages)
        .def("startCalibration", &TrackerEventSource::startCalibration,
            return_value_policy<reference_existing_object>())
        .def("endCalibration", &TrackerEventSource::endCalibration)
        .def("abortCalibration", &TrackerEventSource::abortCalibration)
        .def("setParam", &TrackerEventSource::setParam)
        .def("getParam", &TrackerEventSource::getParam)
    ;

    class_<TrackerCalibrator, boost::noncopyable>("TrackerCalibrator", no_init)
        .def("nextPoint", &TrackerCalibrator::nextPoint)
        .def("getDisplayPoint", &TrackerCalibrator::getDisplayPoint)
        .def("setCamPoint", &TrackerCalibrator::setCamPoint)
    ;
}
<commit_msg>preliminary python export of Event::setEventSource<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2008 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Current versions can be found at www.libavg.de
//

#include "WrapHelper.h"

#include "../player/KeyEvent.h"
#include "../player/MouseEvent.h"
#include "../player/TouchEvent.h"
#include "../player/VisibleNode.h"
#include "../player/TrackerEventSource.h"

#include <boost/shared_ptr.hpp>
#include <string>

using namespace boost::python;
using namespace avg;
using namespace std;

class IEventSourceWrapper : public IEventSource, public wrapper<IEventSource> {
    public:
        IEventSourceWrapper(const std::string& name)
            : IEventSource(name)
        {
        }

        IEventSourceWrapper(const IEventSource& eventSource)
            : IEventSource(eventSource)
        {
        }

        IEventSourceWrapper(const IEventSourceWrapper& eventSourceWrapper)
            : IEventSource(eventSourceWrapper)
        {
        }

        virtual void start() {
            if (override startMethod = this->get_override("start")) {
                startMethod();
            }
            IEventSource::start();
        }

        void default_start() {
            return this->IEventSource::start();
        }

        virtual std::vector<EventPtr> pollEvents() {
            return this->get_override("pollEvents")();
        }

};

void export_event()
{
    boost::python::to_python_converter<vector<TouchEventPtr>,
        to_tuple<vector<TouchEventPtr> > >();

    boost::python::to_python_converter<ContourSeq, to_list<ContourSeq> >();

    from_python_sequence<ContourSeq, variable_capacity_policy>();
    from_python_sequence<vector<EventPtr>, variable_capacity_policy>();

    class_<Event, boost::noncopyable>("Event", init<Event::Type, Event::Source, optional<int> >())
        .add_property("type", &Event::getType)
        .add_property("when", &Event::getWhen)
        .add_property("eventsource",
                      make_function(&Event::getEventSource,
                                    return_value_policy<copy_const_reference>()),
                      &Event::setEventSource)
        .add_property("eventsourcename",
                      make_function(&Event::getEventSourceName,
                                    return_value_policy<copy_const_reference>()))
    ;

    class_<CursorEvent, bases<Event> >("CursorEvent",
                                       init<int, Event::Type, const IntPoint&, Event::Source>())
        .add_property("source", &CursorEvent::getSource)
        .add_property("pos", &CursorEvent::getPos)
        .add_property("x", &CursorEvent::getXPosition)
        .add_property("y", &CursorEvent::getYPosition)
        .add_property("cursorid", &CursorEvent::getCursorID, &CursorEvent::setCursorID)
        .add_property("node", &CursorEvent::getElement)
    ;

    enum_<Event::Type>("Type")
        .value("KEYUP", Event::KEYUP)
        .value("KEYDOWN", Event::KEYDOWN)
        .value("CURSORMOTION", Event::CURSORMOTION)
        .value("CURSORUP", Event::CURSORUP)
        .value("CURSORDOWN", Event::CURSORDOWN)
        .value("CURSOROVER", Event::CURSOROVER)
        .value("CURSOROUT", Event::CURSOROUT)
        .value("CUSTOMEVENT", Event::CUSTOMEVENT)
        .value("RESIZE", Event::RESIZE)
        .value("QUIT", Event::QUIT)
        .export_values()
    ;

    enum_<CursorEvent::Source>("Source")
        .value("MOUSE", CursorEvent::MOUSE)
        .value("TOUCH", CursorEvent::TOUCH)
        .value("TRACK", CursorEvent::TRACK)
        .value("CUSTOM", Event::CUSTOM)
        .value("NONE", Event::NONE)
        .export_values()
    ;

    enum_<int>("KeyModifier")
        .value("KEYMOD_NONE", key::KEYMOD_NONE)
        .value("KEYMOD_LSHIFT", key::KEYMOD_LSHIFT)
        .value("KEYMOD_RSHIFT", key::KEYMOD_RSHIFT)
        .value("KEYMOD_LCTRL", key::KEYMOD_LCTRL)
        .value("KEYMOD_RCTRL", key::KEYMOD_RCTRL)
        .value("KEYMOD_LALT", key::KEYMOD_LALT)
        .value("KEYMOD_RALT", key::KEYMOD_RALT)
        .value("KEYMOD_LMETA", key::KEYMOD_LMETA)
        .value("KEYMOD_RMETA", key::KEYMOD_RMETA)
        .value("KEYMOD_NUM", key::KEYMOD_NUM)
        .value("KEYMOD_CAPS", key::KEYMOD_CAPS)
        .value("KEYMOD_MODE", key::KEYMOD_MODE)
        .value("KEYMOD_RESERVED", key::KEYMOD_RESERVED)
        .value("KEYMOD_CTRL", key::KEYMOD_CTRL)
        .value("KEYMOD_SHIFT", key::KEYMOD_SHIFT)
        .value("KEYMOD_ALT", key::KEYMOD_ALT)
        .value("KEYMOD_META", key::KEYMOD_META)
        .export_values()
    ;

    class_<KeyEvent, bases<Event> >("KeyEvent", no_init)
        .add_property("scancode", &KeyEvent::getScanCode)
        .add_property("keycode", &KeyEvent::getKeyCode)
        .add_property("keystring", make_function(&KeyEvent::getKeyString,
                return_value_policy<copy_const_reference>()))
        .add_property("unicode", &KeyEvent::getUnicode)
        .add_property("modifiers", &KeyEvent::getModifiers)
    ;

    class_<MouseEvent, bases<Event> >("MouseEvent", no_init)
        .add_property("source", &MouseEvent::getSource)
        .add_property("leftbuttonstate", &MouseEvent::getLeftButtonState)
        .add_property("middlebuttonstate", &MouseEvent::getMiddleButtonState)
        .add_property("rightbuttonstate", &MouseEvent::getRightButtonState)
        .add_property("pos", &MouseEvent::getPos)
        .add_property("x", &MouseEvent::getXPosition)
        .add_property("y", &MouseEvent::getYPosition)
        .add_property("cursorid", &MouseEvent::getCursorID)
        .add_property("button", &MouseEvent::getButton)
        .add_property("node", &MouseEvent::getElement)
        .add_property("speed", make_function(&MouseEvent::getSpeed,
                return_value_policy<copy_const_reference>()))
        .add_property("lastdownpos", &CursorEvent::getLastDownPos)
    ;

    class_<TouchEvent, bases<Event> >("TouchEvent", no_init)
        .add_property("source", &TouchEvent::getSource)
        .add_property("area", &TouchEvent::getArea)
        .add_property("orientation", &TouchEvent::getOrientation)
        .add_property("eccentricity", &TouchEvent::getEccentricity)
        .add_property("pos", &TouchEvent::getPos)
        .add_property("x", &TouchEvent::getXPosition)
        .add_property("y", &TouchEvent::getYPosition)
        .add_property("cursorid", &TouchEvent::getCursorID)
        .add_property("node", &TouchEvent::getElement)
        .add_property("center", make_function(&TouchEvent::getCenter,
                return_value_policy<copy_const_reference>()))
        .add_property("majoraxis", make_function(&TouchEvent::getMajorAxis,
                return_value_policy<copy_const_reference>()))
        .add_property("minoraxis", make_function(&TouchEvent::getMinorAxis,
                return_value_policy<copy_const_reference>()))
        .add_property("speed", make_function(&TouchEvent::getSpeed,
                return_value_policy<copy_const_reference>()))
        .add_property("handorientation", &TouchEvent::getHandOrientation)
        .def("getRelatedEvents", &TouchEvent::getRelatedEvents)
        .def("getContour", &TouchEvent::getContour)
        .add_property("lastdownpos", &CursorEvent::getLastDownPos)
        ;

    enum_<TrackerImageID>("TrackerImageID")
        .value("IMG_CAMERA", TRACKER_IMG_CAMERA)
        .value("IMG_DISTORTED", TRACKER_IMG_DISTORTED)
        .value("IMG_NOHISTORY", TRACKER_IMG_NOHISTORY)
        .value("IMG_HISTOGRAM", TRACKER_IMG_HISTOGRAM)
        .value("IMG_FINGERS", TRACKER_IMG_FINGERS)
        .value("IMG_HIGHPASS", TRACKER_IMG_HIGHPASS)
        .export_values()
    ;

    class_<IEventSourcePtr>("IEventSource")
    ;

    class_<IEventSourceWrapper, boost::shared_ptr<IEventSourceWrapper> >("EventSource", init<const std::string&>())
        .def("start", &IEventSource::start, &IEventSourceWrapper::default_start)
        .def("pollEvents", pure_virtual(&IEventSource::pollEvents))
        .add_property("name",
                      make_function(&IEventSource::getName,
                                    return_value_policy<copy_const_reference>()))
    ;

    class_<TrackerEventSource, boost::noncopyable>("Tracker", no_init)
        .def("getImage", &TrackerEventSource::getImage,
            return_value_policy<manage_new_object>())
        .def("getDisplayROIPos", &TrackerEventSource::getDisplayROIPos)
        .def("getDisplayROISize", &TrackerEventSource::getDisplayROISize)
        .def("saveConfig", &TrackerEventSource::saveConfig)
        .def("resetHistory", &TrackerEventSource::resetHistory)
        .def("setDebugImages", &TrackerEventSource::setDebugImages)
        .def("startCalibration", &TrackerEventSource::startCalibration,
            return_value_policy<reference_existing_object>())
        .def("endCalibration", &TrackerEventSource::endCalibration)
        .def("abortCalibration", &TrackerEventSource::abortCalibration)
        .def("setParam", &TrackerEventSource::setParam)
        .def("getParam", &TrackerEventSource::getParam)
    ;

    class_<TrackerCalibrator, boost::noncopyable>("TrackerCalibrator", no_init)
        .def("nextPoint", &TrackerCalibrator::nextPoint)
        .def("getDisplayPoint", &TrackerCalibrator::getDisplayPoint)
        .def("setCamPoint", &TrackerCalibrator::setCamPoint)
    ;
}
<|endoftext|>


<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-9-30 14:19:12
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

string C = "";

bool que(int q) // (X/q) が奇数なら true
{
  assert(q % 2 == 1);
  cout << "? " << q << endl;
  string s;
  cin >> s;
  return (s != C);
}

int main()
{
  cout << "? 2" << endl;
  cin >> C;
  int lb = 1;
  int ub = 1000000007;
  while (ub - lb > 2)
  {
    int t = (lb + ub) / 2;
    if (t % 2 == 0)
    {
      t++;
    }
    if (que(t))
    {
      lb = t;
    }
    else
    {
      ub = t;
    }
  }
  if (C == "even")
  {
    cout << lb + 1 << endl;
  }
  else
  {
    cout << "! " << lb << endl;
  }
}<commit_msg>submit D.cpp to 'D - ロストテクノロジー' (kupc2018) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-9-30 14:19:12
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

string C = "";

bool que(int q) // (X/q) が奇数なら true
{
  assert(q % 2 == 1);
  cout << "? " << q << endl;
  string s;
  cin >> s;
  return (s != C);
}

int main()
{
  cout << "? 2" << endl;
  cin >> C;
  int lb = 1;
  int ub = 1000000007;
  while (ub - lb > 2)
  {
    int t = (lb + ub) / 2;
    if (t % 2 == 0)
    {
      t++;
    }
    if (que(t))
    {
      lb = t;
    }
    else
    {
      ub = t;
    }
  }
  if (C == "even")
  {
    cout << "! " << lb + 1 << endl;
  }
  else
  {
    cout << "! " << lb << endl;
  }
}<|endoftext|>


<commit_before>/// PrecompData_test.cpp

/** Test the PrecompData class
 */

#include "PrecompData.h"
#include "PrecompData_test.h"
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

float TestFunc(float x) {
	return sin(x);
}

float TestFuncLin(float x) {            //   y = 2x
    return 2*x;
}

float TestFuncNonLin1(float x) {        //   y = |x|
    return fabs(x);
}

float TestFuncNonLin2(float x) {        //   y = 1/(|x-2| + 0.1)
    return 1/(fabs(x - 2.0) + 0.1);
}

namespace Utilities {

PrecompData_test::PrecompData_test()
{
	using namespace Utilities;

    const int nValues = 10;

	{ // Test 1 - Interpolation
        cout << "\n\nTest 1: Zero-degree (nearest-neighbor/point sampling/Voronoi) interpolation:" << endl;
		const string funcName = "TestFunc";
		PrecompData<float> itp(funcName);
		itp.SetComment("TestFunc approximation");
		const float x0 = 0.0f, x1 = 6.28f;
		const float step = 0.5*(x1 - x0)/nValues;
		itp.Set(&TestFunc, x0, x1, nValues);
		float x = x0;
        float err = 0.0;
		for(int i = 0; i < nValues; ++i) {
            const float y = itp(x);
            err += fabs(TestFunc(x) - y);
			cout << i << ":\t" << funcName << "(" << x << ") = " << TestFunc(x) << " ~ " << y << endl;
			x += step;
		}
        cout << "Total error = " << err << endl;
	}

    { // Test 2 - Interpolation
        cout << "\n\nTest 2: Linear interpolation:" << endl;
        const string funcName = "TestFunc";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        const float step = 0.5*(x1 - x0)/nValues;
        itp.Set(&TestFunc, x0, x1, nValues);
        float x = x0;
        float err = 0.0;
        itp.Interpolation(1);
        cout << "Interpolation: " << itp.Interpolation() << endl;
        for(int i = 0; i < nValues; ++i) {
            const float y = itp.Interpolate(x);
            err += fabs(TestFunc(x) - y);
            cout << i << ":\t" << funcName << "(" << x << ") = " << TestFunc(x) << " ~ " << y << endl;
            x += step;
        }
        cout << "Total error = " << err << endl;
    }

    if(0) { // Test 3 - AutoSet:  y = 2x
        cout << "\n\nTest 3: Automatic irregular grid:    y = 2x" << endl;
        const string funcName = "y = 2x";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        itp.AutoSet(&TestFuncLin, x0, x1, nValues);
        cerr << "x0 = " << x0 << "  x1 = " << x1 << "  nValues = " << nValues << endl;  //+T+
        std::vector<float> vx, vy;
        itp.Get(vx, vy);
        cout << "Sizes:  x = " << vx.size() << ";  y = " << vy.size() << endl;
        for(size_t i = 0; i < nValues; ++i) {
            cout << i << ":  " << vx[i] << ", " << vy[i] << endl;
        }
    }

    if(0) { // Test 4 - AutoSet:  y = 1/(|x-2| + 0.1)
        cout << "\n\nTest 4: Automatic irregular grid:    y = 1/(|x-2| + 0.1)" << endl;
        const string funcName = "y = 1/(|x-2| + 0.1)";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);
        cerr << "x0 = " << x0 << "  x1 = " << x1 << "  nValues = " << nValues << endl;  //+T+
        std::vector<float> vx, vy;
        itp.Get(vx, vy);
        cout << "Sizes:  x = " << vx.size() << ";  y = " << vy.size() << endl;
        for(size_t i = 0; i < nValues; ++i) {
            cout << i << ":  " << vx[i] << ", " << vy[i] << endl;
        }
    }

    { // Test 5 - Derivatives
        cout << "\n\nTest 5: Derivatives" << endl;
        int nTests = 0, nFailed = 0;
        const string funcName = "Derivatives";
        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;
        PrecompData<float> test;

        // First derivative
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 1" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 2" << endl;
        }
        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 3" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 4" << endl;
        }
        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 5" << endl;
        }
        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 6" << endl;
        }

        // Second derivative

        cout << "Derivatives:  Number of tests = " << nTests << ";  Number of failures = " << nFailed << endl;
    }
}

} // Utilities

int main()
{
    using namespace Utilities;

    PrecompData_test test;

    return 0;
}
<commit_msg>- Test: second derivatives: failed.<commit_after>/// PrecompData_test.cpp

/** Test the PrecompData class
 */

#include "PrecompData.h"
#include "PrecompData_test.h"
#include <cmath>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

float TestFunc(float x) {
	return sin(x);
}

float TestFuncLin(float x) {            //   y = 2x
    return 2*x;
}

float TestFuncNonLin1(float x) {        //   y = |x|
    return fabs(x);
}

float TestFuncNonLin2(float x) {        //   y = 1/(|x-2| + 0.1)
    return 1/(fabs(x - 2.0) + 0.1);
}

namespace Utilities {

PrecompData_test::PrecompData_test()
{
	using namespace Utilities;

    const int nValues = 10;

	{ // Test 1 - Interpolation
        cout << "\n\nTest 1: Zero-degree (nearest-neighbor/point sampling/Voronoi) interpolation:" << endl;
		const string funcName = "TestFunc";
		PrecompData<float> itp(funcName);
		itp.SetComment("TestFunc approximation");
		const float x0 = 0.0f, x1 = 6.28f;
		const float step = 0.5*(x1 - x0)/nValues;
		itp.Set(&TestFunc, x0, x1, nValues);
		float x = x0;
        float err = 0.0;
		for(int i = 0; i < nValues; ++i) {
            const float y = itp(x);
            err += fabs(TestFunc(x) - y);
			cout << i << ":\t" << funcName << "(" << x << ") = " << TestFunc(x) << " ~ " << y << endl;
			x += step;
		}
        cout << "Total error = " << err << endl;
	}

    { // Test 2 - Interpolation
        cout << "\n\nTest 2: Linear interpolation:" << endl;
        const string funcName = "TestFunc";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        const float step = 0.5*(x1 - x0)/nValues;
        itp.Set(&TestFunc, x0, x1, nValues);
        float x = x0;
        float err = 0.0;
        itp.Interpolation(1);
        cout << "Interpolation: " << itp.Interpolation() << endl;
        for(int i = 0; i < nValues; ++i) {
            const float y = itp.Interpolate(x);
            err += fabs(TestFunc(x) - y);
            cout << i << ":\t" << funcName << "(" << x << ") = " << TestFunc(x) << " ~ " << y << endl;
            x += step;
        }
        cout << "Total error = " << err << endl;
    }

    if(0) { // Test 3 - AutoSet:  y = 2x
        cout << "\n\nTest 3: Automatic irregular grid:    y = 2x" << endl;
        const string funcName = "y = 2x";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        itp.AutoSet(&TestFuncLin, x0, x1, nValues);
        cerr << "x0 = " << x0 << "  x1 = " << x1 << "  nValues = " << nValues << endl;  //+T+
        std::vector<float> vx, vy;
        itp.Get(vx, vy);
        cout << "Sizes:  x = " << vx.size() << ";  y = " << vy.size() << endl;
        for(size_t i = 0; i < nValues; ++i) {
            cout << i << ":  " << vx[i] << ", " << vy[i] << endl;
        }
    }

    if(0) { // Test 4 - AutoSet:  y = 1/(|x-2| + 0.1)
        cout << "\n\nTest 4: Automatic irregular grid:    y = 1/(|x-2| + 0.1)" << endl;
        const string funcName = "y = 1/(|x-2| + 0.1)";
        PrecompData<float> itp(funcName);
        const float x0 = 0.0f, x1 = 6.28f;
        itp.AutoSet(&TestFuncNonLin2, x0, x1, nValues);
        cerr << "x0 = " << x0 << "  x1 = " << x1 << "  nValues = " << nValues << endl;  //+T+
        std::vector<float> vx, vy;
        itp.Get(vx, vy);
        cout << "Sizes:  x = " << vx.size() << ";  y = " << vy.size() << endl;
        for(size_t i = 0; i < nValues; ++i) {
            cout << i << ":  " << vx[i] << ", " << vy[i] << endl;
        }
    }

    { // Test 5 - Derivatives
        cout << "\n\nTest 5: Derivatives" << endl;
        int nTests = 0, nFailed = 0;
        const string funcName = "Derivatives";
        float x1, y1, x2, y2, x3, y3, der1, der2, expRes;
        PrecompData<float> test;

        // First derivative
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; expRes = 0.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 1" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; expRes = 1.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 2" << endl;
        }
        x1 = 1.0; y1 = 0.0; x2 = 0.0; y2 = 1.0; expRes = -1.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 3" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 2.0; y2 = 1.0; expRes = 0.5;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 4" << endl;
        }
        x1 = 0.0; y1 = -1.0; x2 = 1.0; y2 = 1.0; expRes = 2.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 5" << endl;
        }
        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; expRes = 0.0;
        der1 = test.FirstDerivative(x1, y1, x2, y2);
        ++nTests;
        if(fabs(der1 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - First derivative 6" << endl;
        }

        // Second derivative
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 0.0; x3 = 2.0; y3 = 0.0; expRes = 0.0;
        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);
        ++nTests;
        if(fabs(der2 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - Second derivative 1" << endl;
        }
        x1 = 0.0; y1 = 1.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 1.0; expRes = 0.0;
        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);
        ++nTests;
        if(fabs(der2 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - Second derivative 2" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 2.0; expRes = 0.0;
        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);
        ++nTests;
        if(fabs(der2 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - Second derivative 3" << endl;
        }
        x1 = 0.0; y1 = 0.0; x2 = 1.0; y2 = 1.0; x3 = 2.0; y3 = 4.0; expRes = 2.0;
        der2 = test.SecondDerivative(x1, y1, x2, y2, x3, y3);
        ++nTests;
        if(fabs(der2 - expRes) > 0.0001) {
            ++nFailed;
            cerr << "Error - Second derivative 4: Result = " << der2 << "; Expected = " << expRes << endl;
        }

        cout << "Derivatives:  Number of tests = " << nTests << ";  Number of failures = " << nFailed << endl;
    }
}

} // Utilities

int main()
{
    using namespace Utilities;

    PrecompData_test test;

    return 0;
}
<|endoftext|>


<commit_before>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;

ifstream inFile;     // define ifstream to inFile command

void readString();
void initialize(unsigned long); // function to initalize everything
void guess();
void hangmanDraw(int, int, string);

// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
unsigned long wordLength; // length of word

// functions

int main() // reads in the file and sets the functions in motion
{
	char repeat = 'Y'; // test if user wants to repeat
	while (repeat == 'Y' || repeat == 'y')
	{
		readString(); // reads the file and stores variables
		initialize(wordLength); // sends length of word to initialize function
		guess(); // game logic

		cout << "Do you want to play again? Y/N: ";
		cin >> repeat;
	}
	return 0;
}

void readString()
{
	int random20 = 0; // random number
	string dictionary[20]; // 20 words to load from file

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
	//cout << word << endl; // cheater! (testing)
	wordLength = word.size(); // size (length) of the string
}

void initialize(unsigned long wordLength)
{
	solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}

void guess()
{
	char guessLetter = ' '; // letter to guess
	int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
	int guessesCounter = 7; // hangman countdown

	hangmanDraw(guessesCounter, winning, solution); // show blank

	while ((guessesCounter > 0) && (winning == 0))
	{

		cout << "Guess a letter: ";
		cin >> guessLetter;
		guessLetter = toupper(guessLetter); // make guess uppercase

		for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
		{
			if (guessLetter == word[i])
			{
				//cout << "char " << (i + 1) /* +1 because first is 0*/ << " is " << guessLetter << endl; // outputs that guess was correct
				solution[i] = guessLetter; // set the i char in solution to guessLetter
				goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
			}
		}

		if (solution == word) // thus victory
		{
			winning = 1; // you won
			hangmanDraw(guessesCounter, winning, solution);
		}
		else if (goodGuess == 1)
		{
			goodGuess = 0; // clear flag for next run
			hangmanDraw(guessesCounter, winning, solution);
		}
		else
		{
			guessesCounter--; // decrement guess
			hangmanDraw(guessesCounter, winning, solution);
		}
	}
}

void hangmanDraw(int guessNumber, int winningResult, string solutionDisplay)
{
	// set up strings for game
	string hD01 = "    /\\  /\\__ _ _ __   __ _ _ __ ___   __ _ _ __  \n"; // have to escape out backslash
	string hD02 = "   / /_/ / _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ \n"; // have to escape out backslash
	string hD03 = "  / __  / (_| | | | | (_| | | | | | | (_| | | | |\n";
	string hD04 = "  \\/ /_/ \\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_|\n"; // have to escape out backslash
	string hD05 = "                     |___/                       \n";
	string hD06 = "                            by Elliott Plack     \n";
	string hD07 = "                                                 \n";
	string hD08 = "      _______                                    \n";
	string hD09 = "     |/      |          ______________________   \n";
	string hD10 = "     |                 |                      |  \n";
	string hD11 = "     |                 | Your Progress        |  \n";
	string hD12 = "     |                 |                      |  \n";
	string hD13 = "     |                 |                      |  \n";
	string hD14 = "     |                 |                      |  \n";
	string hD15 = "  ___|___              |______________________|  \n";

	// set up body parts
	string head = "(_)";
	string neck = "|";
	string leftArm = "\\";
	string rightArm = "/";
	string torso = "|";
	string leftLeg = "/";
	string rightLeg = "\\";
	const char space = ' ';
	string youWon = "YOU WON !!";
	string youLose = "YOU DIED !";

	system("CLS"); // clear the input screen (Windows only)

	if (guessNumber <= 7 && winningResult == 0)
	{
		switch (guessNumber)
		{
		case 7:
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 6:
			hD10 = hD10.replace(12, 3, head);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 5:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 1, leftArm);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 4:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 2, leftArm + neck);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 3:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 2:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 1:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(12, 2, leftLeg + space);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		case 0:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(12, 3, leftLeg + space + rightLeg);
			hD13 = hD13.replace(25, wordLength, word); // show the full word
			hD14 = hD14.replace(31, 10, youLose);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
			break;
		default:
			cout << "\aError!";
			break;
		}
	}
	else if (winningResult == 1)
	{
		hD13 = hD13.replace(25, wordLength, solutionDisplay);
		hD14 = hD14.replace(31, 10, youWon);
		cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
			<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15;
	}
}<commit_msg>added functionality to display guesses<commit_after>/**************************************************************
COSC 501
Elliott Plack
14 NOV 2013                            Due date: 30 NOV 2013

Problem:
	Write a program that plays the game of HANGMAN(guessing a
	mystery word).  Read a word to be guessed from a file into
	successive elements of the array WORD. The player must
	guess the letters belonging to WORD. A single guessing
	session should be terminated when either all letters have
	been guessed correctly (player wins) or a specified number
	of incorrect guesses have been made (computer wins). A run
	must consist of at least two sessions: one player wins and
	one computer wins. The player decides whether or not to
	start a new session.

***************************************************************/

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h> // for random
using namespace std;

ifstream inFile;     // define ifstream to inFile command

void readString();
void initialize(unsigned long); // function to initalize everything
void guess();
void hangmanDraw(int, int, string, char, int);

// global variables
string word; // word to be read from file (the solution)
string solution; // solution (guessed by user)
string hD17 = "  Your guesses:                                  \n"; // string to store guesses
unsigned long wordLength; // length of word

// functions

int main() // reads in the file and sets the functions in motion
{
	char repeat = 'Y'; // test if user wants to repeat
	while (repeat == 'Y' || repeat == 'y')
	{
		readString(); // reads the file and stores variables
		initialize(wordLength); // sends length of word to initialize function
		guess(); // game logic

		cout << "Do you want to play again? Y/N: ";
		cin >> repeat;
	}
	return 0;
}

void readString()
{
	int random20 = 0; // random number
	string dictionary[20]; // 20 words to load from file

	inFile.open("Words4Hangman.txt"); // open input file

	while (inFile.good())
	{
		for (int i = 0; i < 20; i++)
		{
			inFile >> dictionary[i]; // load file and fill dict
		}
	}

	inFile.close(); // close the file

	srand((int)time(NULL)); // initialize random seed
	random20 = (rand() % 20); // set random to 20 +-

	word = dictionary[rand() % 20]; // set word = to a random letter in the dictionary
	//cout << word << endl; // cheater! (testing)
	wordLength = word.size(); // size (length) of the string
}

void initialize(unsigned long wordLength)
{
	solution.assign(wordLength, '*'); // fills up the solution string (an array) with as many *s as the word length
}

void guess()
{
	char guessLetter = ' '; // letter to guess
	int winning = 0, goodGuess = 0; // variable to check if the game is won or the guess is good
	int guessesCounter = 7; // hangman countdown

	hangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess); // show blank

	while ((guessesCounter > 0) && (winning == 0))
	{

		cout << "Guess a letter: ";
		cin >> guessLetter;
		guessLetter = toupper(guessLetter); // make guess uppercase

		for (unsigned long i = 0; i < wordLength; i++) // loop through word looking for guess
		{
			if (guessLetter == word[i])
			{
				solution[i] = guessLetter; // set the i char in solution to guessLetter
				goodGuess = 1; // sets the flag goodGuess = 1 for the logic below
			}
		}

		if (solution == word) // thus victory
		{
			winning = 1; // variable flag telling drawing function victory is true
			hangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);
		}
		else if (goodGuess == 1)
		{
			hangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);
			goodGuess = 0; // clear flag for next run
		}
		else
		{
			guessesCounter--; // decrement guess
			hangmanDraw(guessesCounter, winning, solution, guessLetter, goodGuess);
		}
	}
}

void hangmanDraw(int guessNumber, int winningResult, string solutionDisplay, char guessLetter, int goodGuess)
{
	// set up strings for game
	string hD01 = "    /\\  /\\__ _ _ __   __ _ _ __ ___   __ _ _ __  \n"; // have to escape out backslash
	string hD02 = "   / /_/ / _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ \n"; // have to escape out backslash
	string hD03 = "  / __  / (_| | | | | (_| | | | | | | (_| | | | |\n";
	string hD04 = "  \\/ /_/ \\__,_|_| |_|\\__, |_| |_| |_|\\__,_|_| |_|\n"; // have to escape out backslash
	string hD05 = "                     |___/                       \n";
	string hD06 = "                            by Elliott Plack     \n";
	string hD07 = "                                                 \n";
	string hD08 = "      _______                                    \n";
	string hD09 = "     |/      |          ______________________   \n";
	string hD10 = "     |                 |                      |  \n";
	string hD11 = "     |                 | Your Progress        |  \n";
	string hD12 = "     |                 |                      |  \n";
	string hD13 = "     |                 |                      |  \n";
	string hD14 = "     |                 |                      |  \n";
	string hD15 = "  ___|___              |______________________|  \n";
	string hD16 = "                                                 \n";

	// set up body parts
	string head = "(_)";
	string neck = "|";
	string leftArm = "\\";
	string rightArm = "/";
	string torso = "|";
	string leftLeg = "/";
	string rightLeg = "\\";
	const char space = ' ';
	string youWon = "YOU WON !!";
	string youLose = "YOU DIED !";
	string guessStr;

	if (goodGuess != 1) // if the guess isn't good add the fail letter to string
	{
		guessStr.push_back(guessLetter); // store guess char to string
	}

	system("CLS"); // clear the input screen (Windows only)

	if (guessNumber <= 7 && winningResult == 0)
	{
		switch (guessNumber)
		{
		case 7: // no bad guesses or beginning case
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 6:
			hD10 = hD10.replace(12, 3, head);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(17, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 5:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 1, leftArm);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(20, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 4:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 2, leftArm + neck);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(23, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 3:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(26, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 2:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(29, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 1:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(12, 2, leftLeg + space);
			hD13 = hD13.replace(25, wordLength, solutionDisplay);
			if (goodGuess != 1)
				hD17 = hD17.replace(32, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		case 0:
			hD10 = hD10.replace(12, 3, head);
			hD11 = hD11.replace(12, 3, leftArm + neck + rightArm);
			hD12 = hD12.replace(13, 1, torso);
			hD13 = hD13.replace(12, 3, leftLeg + space + rightLeg);
			hD13 = hD13.replace(25, wordLength, word); // show the full word
			hD14 = hD14.replace(31, 10, youLose);
			if (goodGuess != 1)
				hD17 = hD17.replace(35, 1, guessStr);
			cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
				<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
			break;
		default:
			cout << "\aError!";
			break;
		}
	}
	else if (winningResult == 1)
	{
		hD13 = hD13.replace(25, wordLength, solutionDisplay);
		hD14 = hD14.replace(31, 10, youWon);
		cout << hD01 << hD02 << hD03 << hD04 << hD05 << hD06 << hD07
			<< hD08 << hD09 << hD10 << hD11 << hD12 << hD13 << hD14 << hD15 << hD16 << hD17;
	}
}<|endoftext|>


<commit_before>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

// libmesh includes
#include "libmesh/auto_ptr.h"
#include "libmesh/elem.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parsed_fem_function.h"
#include "libmesh/system.h"

// test includes
#include "test_comm.h"

using namespace libMesh;

class ParsedFEMFunctionTest : public CppUnit::TestCase
{
public:
  void setUp() {
    mesh.reset(new Mesh(*TestCommWorld));
    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);
    es.reset(new EquationSystems(*mesh));
    sys = &(es->add_system<System> ("SimpleSystem"));
    sys->add_variable("x2");
    sys->add_variable("x3");
    sys->add_variable("c05");
    sys->add_variable("y4");
    sys->add_variable("xy");
    sys->add_variable("yz");
    sys->add_variable("xyz");

    es->init();

    NumericVector<Number> & sol = *sys->solution;
    Elem *elem = mesh->elem(0);

    // Set x2 = 2*x
    sol.set(elem->get_node(1)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(2)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(4)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(5)->dof_number(0,0,0), 2);

    // Set x3 = 3*x
    sol.set(elem->get_node(1)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(2)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(4)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(5)->dof_number(0,1,0), 3);

    // Set c05 = 0.5
    sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);

    // Set y4 = 4*y
    sol.set(elem->get_node(2)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(3)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(6)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(7)->dof_number(0,3,0), 4);

    // Set xy = x*y
    sol.set(elem->get_node(2)->dof_number(0,4,0), 1);
    sol.set(elem->get_node(6)->dof_number(0,4,0), 1);

    // Set yz = y*z
    sol.set(elem->get_node(6)->dof_number(0,5,0), 1);
    sol.set(elem->get_node(7)->dof_number(0,5,0), 1);

    // Set xyz = x*y*z
    sol.set(elem->get_node(7)->dof_number(0,6,0), 1);

    sol.close();
    sys->update();
  }

  void tearDown() {
    es.reset();
    mesh.reset();
  }

  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);

  CPPUNIT_TEST(testValues);

  CPPUNIT_TEST_SUITE_END();

private:
  AutoPtr<Mesh> mesh;
  AutoPtr<EquationSystems> es;
  System * sys;

  void testValues()
  {
    Elem *elem = mesh->elem(0);

    ParsedFEMFunction<Number> parsed_func(*sys, "x2*y4");

    FEMContext c(*sys);

    c.pre_fe_reinit(*sys, elem);
    c.elem_fe_reinit();
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);
<commit_msg>More ParsedFEMFunction testing<commit_after>// Ignore unused parameter warnings coming from cppuint headers
#include <libmesh/ignore_warnings.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestCase.h>
#include <libmesh/restore_warnings.h>

// libmesh includes
#include "libmesh/auto_ptr.h"
#include "libmesh/elem.h"
#include "libmesh/equation_systems.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"
#include "libmesh/numeric_vector.h"
#include "libmesh/parsed_fem_function.h"
#include "libmesh/system.h"

// test includes
#include "test_comm.h"

using namespace libMesh;

class ParsedFEMFunctionTest : public CppUnit::TestCase
{
public:
  void setUp() {
    mesh.reset(new Mesh(*TestCommWorld));
    MeshTools::Generation::build_cube(*mesh, 1, 1, 1);
    es.reset(new EquationSystems(*mesh));
    sys = &(es->add_system<System> ("SimpleSystem"));
    sys->add_variable("x2");
    sys->add_variable("x3");
    sys->add_variable("c05");
    sys->add_variable("y4");
    sys->add_variable("xy");
    sys->add_variable("yz");
    sys->add_variable("xyz");

    es->init();

    NumericVector<Number> & sol = *sys->solution;
    Elem *elem = mesh->elem(0);

    // Set x2 = 2*x
    sol.set(elem->get_node(1)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(2)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(4)->dof_number(0,0,0), 2);
    sol.set(elem->get_node(5)->dof_number(0,0,0), 2);

    // Set x3 = 3*x
    sol.set(elem->get_node(1)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(2)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(4)->dof_number(0,1,0), 3);
    sol.set(elem->get_node(5)->dof_number(0,1,0), 3);

    // Set c05 = 0.5
    sol.set(elem->get_node(0)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(1)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(2)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(3)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(4)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(5)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(6)->dof_number(0,2,0), 0.5);
    sol.set(elem->get_node(7)->dof_number(0,2,0), 0.5);

    // Set y4 = 4*y
    sol.set(elem->get_node(2)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(3)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(6)->dof_number(0,3,0), 4);
    sol.set(elem->get_node(7)->dof_number(0,3,0), 4);

    // Set xy = x*y
    sol.set(elem->get_node(2)->dof_number(0,4,0), 1);
    sol.set(elem->get_node(6)->dof_number(0,4,0), 1);

    // Set yz = y*z
    sol.set(elem->get_node(6)->dof_number(0,5,0), 1);
    sol.set(elem->get_node(7)->dof_number(0,5,0), 1);

    // Set xyz = x*y*z
    sol.set(elem->get_node(7)->dof_number(0,6,0), 1);

    sol.close();
    sys->update();
  }

  void tearDown() {
    es.reset();
    mesh.reset();
  }

  CPPUNIT_TEST_SUITE(ParsedFEMFunctionTest);

  CPPUNIT_TEST(testValues);

  CPPUNIT_TEST_SUITE_END();

private:
  AutoPtr<Mesh> mesh;
  AutoPtr<EquationSystems> es;
  System * sys;

  void testValues()
  {
    Elem *elem = mesh->elem(0);

    FEMContext c(*sys);

    c.pre_fe_reinit(*sys, elem);
    c.elem_fe_reinit();

    ParsedFEMFunction<Number> x2(*sys, "x2");

    CPPUNIT_ASSERT_DOUBLES_EQUAL
      (x2(c,Point(0.5,0.5,0.5)), 1.0, 1.e-12);

    ParsedFEMFunction<Number> xy8(*sys, "x2*y4");

    CPPUNIT_ASSERT_DOUBLES_EQUAL
      (xy8(c,Point(0.5,0.5,0.5)), 2.0, 1.e-12);
  }

};

CPPUNIT_TEST_SUITE_REGISTRATION(ParsedFEMFunctionTest);
<|endoftext|>


<commit_before>#include <reflection/reflection.h>
#include <smartref/smartref.h>

// #include <vector>

namespace tests_containers {

// using T = int;
// using T = std::vector<int>;

// using reflection::reflect;

// //! Member-types
// constexpr auto is_valid = [](auto expression)
// {
//   // auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;
//   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;

//   return true;
//   // return actual == expected;
// };

// #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})

// TODO:
// - constructing a smartref (e.g. Ref<int> x;)

// static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);
// static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);
// static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);
// static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);
// static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);
// static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);
// static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);
// static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);
// static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);
// static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);
// static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);
// static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);

// //! Member functions
// // TODO: Test all overloads
// // TODO: (constructor)
// // TODO: Why does operator= work? What does it do?
// // static_assert(IS_VALID(_.operator=(_)));
// // static_assert(IS_VALID(_.operator=(__)));
// static_assert(IS_VALID(_ = __));
// static_assert(IS_VALID(_.assign(0, 0)));
// static_assert(IS_VALID(_.assign(begin(_), end(_))));
// static_assert(IS_VALID(_.get_allocator()));
// //! Element access
// static_assert(IS_VALID(_.at(T::size_type{})));
// static_assert(IS_VALID(_.operator[](0)));
// static_assert(IS_VALID(_[0]));
// static_assert(IS_VALID(_.front()));
// static_assert(IS_VALID(_.back()));
// static_assert(IS_VALID(_.data()));

// //! Iterators
// static_assert(IS_VALID(_.begin()));
// static_assert(IS_VALID(_.cbegin()));
// static_assert(IS_VALID(_.end()));
// static_assert(IS_VALID(_.cend()));
// static_assert(IS_VALID(_.rbegin()));
// static_assert(IS_VALID(_.crbegin()));
// static_assert(IS_VALID(_.rend()));
// static_assert(IS_VALID(_.crend()));

// //! Capacity
// static_assert(IS_VALID(_.empty()));
// static_assert(IS_VALID(_.size()));
// static_assert(IS_VALID(_.max_size()));
// static_assert(IS_VALID(_.reserve(T::size_type{})));
// static_assert(IS_VALID(_.capacity()));
// static_assert(IS_VALID(_.shrink_to_fit()));

// //! Modifiers
// static_assert(IS_VALID(_.clear()));
// static_assert(IS_VALID(_.insert(begin(_), 0)));
// static_assert(IS_VALID(_.emplace(begin(_), 0)));
// static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));
// static_assert(IS_VALID(_.erase(begin(_))));
// static_assert(IS_VALID(_.push_back(0)));
// static_assert(IS_VALID(_.emplace_back(0)));
// static_assert(IS_VALID(_.template emplace_back<int>(0)));
// static_assert(IS_VALID(_.pop_back()));
// static_assert(IS_VALID(_.resize(T::size_type{})));
// static_assert(IS_VALID(_.swap(_)));

// //! Non-member functions
// // static_assert(IS_VALID(_ == _);
// // TODO: operator!=
// // TODO: operator<
// // TODO: operator<=
// // TODO: operator>
// // TODO: operator>=
// // TODO: std::swap

// // TODO: Deduction guides

} // namespace tests_containers
<commit_msg>Re-enabled part of the containers unit tests.<commit_after>#include <reflection/reflection.h>
#include <smartref/smartref.h>

#include <vector>

namespace tests_containers {

using T = std::vector<int>;

template<typename T>
struct Ref : smartref::using_<T>
{
  T ref;

  operator T &()
  {
    return ref;
  }
};

using reflection::reflect;

//! Member-types
constexpr auto is_valid = [](auto expression)
{
  auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;
  auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;

  return actual == expected;
};

#define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})

// TODO:
// - constructing a smartref (e.g. Ref<int> x;)

// static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);
// static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);
// static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);
// static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);
// static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);
// static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);
// static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);
// static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);
// static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);
// static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);
// static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);
// static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);

//! Member functions
// TODO: Test all overloads
// TODO: (constructor)
// TODO: Why does operator= work? What does it do?
// static_assert(IS_VALID(_.operator=(_)));
// static_assert(IS_VALID(_.operator=(__)));
// static_assert(IS_VALID(_ = __));
// static_assert(IS_VALID(_.assign(0, 0)));
// static_assert(IS_VALID(_.assign(begin(_), end(_))));
// static_assert(IS_VALID(_.get_allocator()));
// //! Element access
// static_assert(IS_VALID(_.at(T::size_type{})));
// static_assert(IS_VALID(_.operator[](0)));
// static_assert(IS_VALID(_[0]));
// static_assert(IS_VALID(_.front()));
// static_assert(IS_VALID(_.back()));
// static_assert(IS_VALID(_.data()));

// //! Iterators
// static_assert(IS_VALID(_.begin()));
// static_assert(IS_VALID(_.cbegin()));
// static_assert(IS_VALID(_.end()));
// static_assert(IS_VALID(_.cend()));
// static_assert(IS_VALID(_.rbegin()));
// static_assert(IS_VALID(_.crbegin()));
// static_assert(IS_VALID(_.rend()));
// static_assert(IS_VALID(_.crend()));

// //! Capacity
// static_assert(IS_VALID(_.empty()));
// static_assert(IS_VALID(_.size()));
// static_assert(IS_VALID(_.max_size()));
// static_assert(IS_VALID(_.reserve(T::size_type{})));
// static_assert(IS_VALID(_.capacity()));
// static_assert(IS_VALID(_.shrink_to_fit()));

// //! Modifiers
// static_assert(IS_VALID(_.clear()));
// static_assert(IS_VALID(_.insert(begin(_), 0)));
// static_assert(IS_VALID(_.emplace(begin(_), 0)));
// static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));
// static_assert(IS_VALID(_.erase(begin(_))));
// static_assert(IS_VALID(_.push_back(0)));
// static_assert(IS_VALID(_.emplace_back(0)));
// static_assert(IS_VALID(_.template emplace_back<int>(0)));
// static_assert(IS_VALID(_.pop_back()));
// static_assert(IS_VALID(_.resize(T::size_type{})));
// static_assert(IS_VALID(_.swap(_)));

// //! Non-member functions
// // static_assert(IS_VALID(_ == _);
// // TODO: operator!=
// // TODO: operator<
// // TODO: operator<=
// // TODO: operator>
// // TODO: operator>=
// // TODO: std::swap

// // TODO: Deduction guides

} // namespace tests_containers
<|endoftext|>


<commit_before>#include <reflection/reflection.h>
#include <smartref/smartref.h>

// #include <vector>
#include <cassert>

namespace tests_containers {

// template <typename F>
// class reflect_member_function : public reflection::reflect_base<reflection::reflected_kind::member_function> {
// private:
//     template <typename... ExplicitArgs, typename... Args>
//     decltype(auto) indirect(Args&&... args)
//     {
//         auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward<Args>(args)...); else if constexpr (utils::always_true<Args...>) return obj.template operator=<ExplicitArgs...>( std::forward<Args>(args)...); };
//         return F{}(*this, f, std::forward<Args>(args)...);
//     }
// public:
//     template <typename... ExplicitArgs, typename... Args>
//     auto operator=(Args&&... args) -> decltype(indirect<ExplicitArgs...>(std::forward<Args>(args)...)) { return indirect<ExplicitArgs...>(std::forward<Args>(args)...); }
// };
// template<typename T>

struct Ref : smartref::reflect_member_function<Ref>
// struct Ref : smartref::using_<T>
{
  int ref;

  static auto &counter()
  {
    static auto count = 0;
    return count;
  }

  operator int &()
  {
    ++counter();
    return ref;
  }

  Ref(int arg) : ref{arg} {}

  using Base = smartref::reflect_member_function<Ref>;
  using Base::operator=;

  Ref() = default;

  Ref(const Ref &) = default;
  Ref &operator=(const Ref &) = default;
  Ref(Ref &&) = default;
  Ref &operator=(Ref &&) = default;
};

template<typename T, typename Delegate = int>
auto test = []{
  //! Uninitialized construction
  T a;

  //! Default construction
  T b{};
  T c = {};

  //! Copy construction
  T d{a};
  T e = a;
  T f = {a};
  auto g{a};
  auto h = a;
  auto i = {a};

  //! Move construction
  T j{std::move(a)};
  T k = std::move(a);
  T l = {std::move(a)};
  auto m{T{}};
  auto n = T{};
  auto o = {T{}};

  //! Delegate type copy construction
  auto delegate = Delegate{};
  T p{delegate};
  T q = delegate;
  T r = {delegate};
  auto s{T{delegate}};
  auto t = T{delegate};
  auto u = {T{delegate}};

  //! Delegate type move construction
  T v{std::move(delegate)};
  T w = std::move(delegate);
  T x = {std::move(delegate)};
  auto y{T{std::move(delegate)}};
  auto z = T{std::move(delegate)};
  auto A = {T{std::move(delegate)}};

  //! Copy assignments
  a = b;
  a = b = c;
  a = (b = c);
  (a = b) = c;

  //! Move assignments
  a = std::move(b);
  a = b = std::move(c);
  a = (b = std::move(c));
  (a = b) = std::move(c);

  //! Delegate type copy assignments
  a = delegate;
  a = b = delegate;
  a = (b = delegate);
  (a = b) = delegate;

  //! Delegate type move assignments
  a = std::move(delegate);
  a = b = std::move(delegate);
  a = (b = std::move(delegate));
  (a = b) = std::move(delegate);

  return 0;
};

auto test_int = test<int>();

auto test_ref = []{
  Ref<int>::counter() = 0;
  test<Ref<int>>();
  assert(Ref<int>::counter() == 18);

  Ref<float>::counter() = 0;
  test<Ref<float>>();
  assert(Ref<float>::counter() == 18);

  Ref<bool>::counter() = 0;
  test<Ref<bool>>();
  assert(Ref<bool>::counter() == 18);

  return 0;
}();

// using T = int;
// using T = std::vector<int>;

// using reflection::reflect;

// //! Member-types
// constexpr auto is_valid = [](auto expression)
// {
//   // auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;
//   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;

//   return true;
//   // return actual == expected;
// };

// #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})

// TODO:
// - constructing a smartref (e.g. Ref<int> x;)

// static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);
// static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);
// static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);
// static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);
// static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);
// static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);
// static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);
// static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);
// static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);
// static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);
// static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);
// static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);

// //! Member functions
// // TODO: Test all overloads
// // TODO: (constructor)
// // TODO: Why does operator= work? What does it do?
// // static_assert(IS_VALID(_.operator=(_)));
// // static_assert(IS_VALID(_.operator=(__)));
// static_assert(IS_VALID(_ = __));
// static_assert(IS_VALID(_.assign(0, 0)));
// static_assert(IS_VALID(_.assign(begin(_), end(_))));
// static_assert(IS_VALID(_.get_allocator()));
// //! Element access
// static_assert(IS_VALID(_.at(T::size_type{})));
// static_assert(IS_VALID(_.operator[](0)));
// static_assert(IS_VALID(_[0]));
// static_assert(IS_VALID(_.front()));
// static_assert(IS_VALID(_.back()));
// static_assert(IS_VALID(_.data()));

// //! Iterators
// static_assert(IS_VALID(_.begin()));
// static_assert(IS_VALID(_.cbegin()));
// static_assert(IS_VALID(_.end()));
// static_assert(IS_VALID(_.cend()));
// static_assert(IS_VALID(_.rbegin()));
// static_assert(IS_VALID(_.crbegin()));
// static_assert(IS_VALID(_.rend()));
// static_assert(IS_VALID(_.crend()));

// //! Capacity
// static_assert(IS_VALID(_.empty()));
// static_assert(IS_VALID(_.size()));
// static_assert(IS_VALID(_.max_size()));
// static_assert(IS_VALID(_.reserve(T::size_type{})));
// static_assert(IS_VALID(_.capacity()));
// static_assert(IS_VALID(_.shrink_to_fit()));

// //! Modifiers
// static_assert(IS_VALID(_.clear()));
// static_assert(IS_VALID(_.insert(begin(_), 0)));
// static_assert(IS_VALID(_.emplace(begin(_), 0)));
// static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));
// static_assert(IS_VALID(_.erase(begin(_))));
// static_assert(IS_VALID(_.push_back(0)));
// static_assert(IS_VALID(_.emplace_back(0)));
// static_assert(IS_VALID(_.template emplace_back<int>(0)));
// static_assert(IS_VALID(_.pop_back()));
// static_assert(IS_VALID(_.resize(T::size_type{})));
// static_assert(IS_VALID(_.swap(_)));

// //! Non-member functions
// // static_assert(IS_VALID(_ == _);
// // TODO: operator!=
// // TODO: operator<
// // TODO: operator<=
// // TODO: operator>
// // TODO: operator>=
// // TODO: std::swap

// // TODO: Deduction guides

} // namespace tests_containers
<commit_msg>Fixed a 'typo'.<commit_after>#include <reflection/reflection.h>
#include <smartref/smartref.h>

// #include <vector>
#include <cassert>

namespace tests_containers {

// template <typename F>
// class reflect_member_function : public reflection::reflect_base<reflection::reflected_kind::member_function> {
// private:
//     template <typename... ExplicitArgs, typename... Args>
//     decltype(auto) indirect(Args&&... args)
//     {
//         auto f = [](auto& obj, auto&&... args) { if constexpr (sizeof...(ExplicitArgs) == 0) return obj.operator=(std::forward<Args>(args)...); else if constexpr (utils::always_true<Args...>) return obj.template operator=<ExplicitArgs...>( std::forward<Args>(args)...); };
//         return F{}(*this, f, std::forward<Args>(args)...);
//     }
// public:
//     template <typename... ExplicitArgs, typename... Args>
//     auto operator=(Args&&... args) -> decltype(indirect<ExplicitArgs...>(std::forward<Args>(args)...)) { return indirect<ExplicitArgs...>(std::forward<Args>(args)...); }
// };
// template<typename T>

struct Ref : smartref::reflect_member_function<Ref>
// struct Ref : smartref::using_<T>
{
  int ref;

  static auto &counter()
  {
    static auto count = 0;
    return count;
  }

  operator int &()
  {
    ++counter();
    return ref;
  }

  Ref(int arg) : ref{arg} {}

  using Base = smartref::reflect_member_function<Ref>;
  using Base::operator=;

  Ref() = default;

  Ref(const Ref &) = default;
  Ref &operator=(const Ref &) = default;
  Ref(Ref &&) = default;
  Ref &operator=(Ref &&) = default;
};

template<typename T, typename Delegate = int>
auto test = []{
  //! Uninitialized construction
  T a;

  //! Default construction
  T b{};
  T c = {};

  //! Copy construction
  T d{a};
  T e = a;
  T f = {a};
  auto g{a};
  auto h = a;
  auto i = {a};

  //! Move construction
  T j{std::move(a)};
  T k = std::move(a);
  T l = {std::move(a)};
  auto m{T{}};
  auto n = T{};
  auto o = {T{}};

  //! Delegate type copy construction
  auto delegate = Delegate{};
  T p{delegate};
  T q = delegate;
  T r = {delegate};
  auto s{T{delegate}};
  auto t = T{delegate};
  auto u = {T{delegate}};

  //! Delegate type move construction
  T v{std::move(delegate)};
  T w = std::move(delegate);
  T x = {std::move(delegate)};
  auto y{T{std::move(delegate)}};
  auto z = T{std::move(delegate)};
  auto A = {T{std::move(delegate)}};

  //! Copy assignment
  a = b;
  a = b = c;
  a = (b = c);
  (a = b) = c;

  //! Move assignment
  a = std::move(b);
  a = b = std::move(c);
  a = (b = std::move(c));
  (a = b) = std::move(c);

  //! Delegate type copy assignment
  a = delegate;
  a = b = delegate;
  a = (b = delegate);
  (a = b) = delegate;

  //! Delegate type move assignment
  a = std::move(delegate);
  a = b = std::move(delegate);
  a = (b = std::move(delegate));
  (a = b) = std::move(delegate);

  return 0;
};

auto test_int = test<int>();

auto test_ref = []{
  Ref<int>::counter() = 0;
  test<Ref<int>>();
  assert(Ref<int>::counter() == 18);

  Ref<float>::counter() = 0;
  test<Ref<float>>();
  assert(Ref<float>::counter() == 18);

  Ref<bool>::counter() = 0;
  test<Ref<bool>>();
  assert(Ref<bool>::counter() == 18);

  return 0;
}();

// using T = int;
// using T = std::vector<int>;

// using reflection::reflect;

// //! Member-types
// constexpr auto is_valid = [](auto expression)
// {
//   // auto expected = reflect<decltype(expression(std::declval<    T >(), std::declval<    T >()))>;
//   auto actual   = reflect<decltype(expression(std::declval<Ref<T>>(), std::declval<    T >()))>;

//   return true;
//   // return actual == expected;
// };

// #define IS_VALID(expression) is_valid([](auto &&_, auto &&__) {return expression;})

// TODO:
// - constructing a smartref (e.g. Ref<int> x;)

// static_assert(reflect<Ref<T>::value_type>             == reflect<T::value_type>);
// static_assert(reflect<Ref<T>::allocator_type>         == reflect<T::allocator_type>);
// static_assert(reflect<Ref<T>::size_type>              == reflect<T::size_type>);
// static_assert(reflect<Ref<T>::difference_type>        == reflect<T::difference_type>);
// static_assert(reflect<Ref<T>::reference>              == reflect<T::reference>);
// static_assert(reflect<Ref<T>::const_reference>        == reflect<T::const_reference>);
// static_assert(reflect<Ref<T>::pointer>                == reflect<T::pointer>);
// static_assert(reflect<Ref<T>::const_pointer>          == reflect<T::const_pointer>);
// static_assert(reflect<Ref<T>::iterator>               == reflect<T::iterator>);
// static_assert(reflect<Ref<T>::const_iterator>         == reflect<T::const_iterator>);
// static_assert(reflect<Ref<T>::reverse_iterator>       == reflect<T::reverse_iterator>);
// static_assert(reflect<Ref<T>::const_reverse_iterator> == reflect<T::const_reverse_iterator>);

// //! Member functions
// // TODO: Test all overloads
// // TODO: (constructor)
// // TODO: Why does operator= work? What does it do?
// // static_assert(IS_VALID(_.operator=(_)));
// // static_assert(IS_VALID(_.operator=(__)));
// static_assert(IS_VALID(_ = __));
// static_assert(IS_VALID(_.assign(0, 0)));
// static_assert(IS_VALID(_.assign(begin(_), end(_))));
// static_assert(IS_VALID(_.get_allocator()));
// //! Element access
// static_assert(IS_VALID(_.at(T::size_type{})));
// static_assert(IS_VALID(_.operator[](0)));
// static_assert(IS_VALID(_[0]));
// static_assert(IS_VALID(_.front()));
// static_assert(IS_VALID(_.back()));
// static_assert(IS_VALID(_.data()));

// //! Iterators
// static_assert(IS_VALID(_.begin()));
// static_assert(IS_VALID(_.cbegin()));
// static_assert(IS_VALID(_.end()));
// static_assert(IS_VALID(_.cend()));
// static_assert(IS_VALID(_.rbegin()));
// static_assert(IS_VALID(_.crbegin()));
// static_assert(IS_VALID(_.rend()));
// static_assert(IS_VALID(_.crend()));

// //! Capacity
// static_assert(IS_VALID(_.empty()));
// static_assert(IS_VALID(_.size()));
// static_assert(IS_VALID(_.max_size()));
// static_assert(IS_VALID(_.reserve(T::size_type{})));
// static_assert(IS_VALID(_.capacity()));
// static_assert(IS_VALID(_.shrink_to_fit()));

// //! Modifiers
// static_assert(IS_VALID(_.clear()));
// static_assert(IS_VALID(_.insert(begin(_), 0)));
// static_assert(IS_VALID(_.emplace(begin(_), 0)));
// static_assert(IS_VALID(_.template emplace<int>(begin(_), 0)));
// static_assert(IS_VALID(_.erase(begin(_))));
// static_assert(IS_VALID(_.push_back(0)));
// static_assert(IS_VALID(_.emplace_back(0)));
// static_assert(IS_VALID(_.template emplace_back<int>(0)));
// static_assert(IS_VALID(_.pop_back()));
// static_assert(IS_VALID(_.resize(T::size_type{})));
// static_assert(IS_VALID(_.swap(_)));

// //! Non-member functions
// // static_assert(IS_VALID(_ == _);
// // TODO: operator!=
// // TODO: operator<
// // TODO: operator<=
// // TODO: operator>
// // TODO: operator>=
// // TODO: std::swap

// // TODO: Deduction guides

} // namespace tests_containers
<|endoftext|>