blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
437c78c81a971682854f4732f8585b5b343970e4 | C++ | heyjessiehey/CPP1 | /ws4_inlab/Passenger.cpp | UTF-8 | 1,387 | 3.15625 | 3 | [] | no_license | // TODO: add file header comments here
//Name: (Jessie) Gayeon Ko
//Section: OPP244SGG
//Student ID: 040704124
//Email: gko4@myseneca.ca
//Date: Feb 13 2018
// TODO: add your headers here
#include <iostream>
#include <cstring>
#include "Passenger.h"
using namespace std;
// TODO: continue your namespace here
namespace sict
{
// TODO: implement the default constructor here
Passenger::Passenger()
{
//cout << "Passenger::Passenger()" << endl;
m_passengerName[0] = '\0';
m_destination[0] = '\0';
}
// TODO: implement the constructor with 2 parameters here
Passenger::Passenger(const char* name, const char* destination)
{
//cout << "Passenger::Passenger(...)" << endl;
if (name == nullptr || destination == nullptr || destination[0] == '\0')
*this = Passenger();
else
{
strncpy(m_passengerName, name, max_name_length + 1);
m_passengerName[max_name_length] = '\0';
strncpy(m_destination, destination, max_name_length + 1);
m_destination[max_name_length] = '\0';
}
}
// TODO: implement isEmpty query here
bool Passenger::isEmpty() const
{
return m_passengerName[0] == '\0';
}
// TODO: implement display query here
void Passenger::display() const
{
if (isEmpty() == true)
cout << "No passenger!" << endl;
else
{
cout << m_passengerName << " - " << m_destination << endl;
}
}
}
| true |
9ce65af38f001395121ff2c4a44d909f36f23842 | C++ | BilalAli181999/Programming-Fundamentals-in-C_Plus_Plus | /practice file loops/practice file loops/Source.cpp | TIS-620 | 1,269 | 3.25 | 3 | [] | no_license |
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
int counter = 1, i = 1;
while (counter <= 10)
{
while (i <= counter)
{
cout << "+";
i = i + 1;
}
i = 1;
counter = counter + 1;
cout << "\n";
}
cout << "\n\n\n";
int count = 10;
int y = 1;
while (count > 0)
{
while (y <= count)
{
cout << "+";
y = y + 1;
}
y = 1;
count = count - 1;
cout << "\n";
}
/*int size;
cout << "nter size";
cin >> size;
int i = 1;
int y = 1;
while (size < 0 || size>15)
{
cout << "enter the size again";
cin >> size;
}
while (i <= size)
{
while (y <= size)
{
cout << "X";
y = y + 1;
}
y = 1;
cout << "\n";
i = i + 1;
}*/
/*
int number,x=100/2,y=100/4;
srand(time(0));
number = rand() % 99;
int guess;
cout << "enter the guessed number within 0-100";
cin >> guess;
while (guess!=number)
{
if (guess > number)
{
cout << "your guess is greater than number";
cin >> guess;
}
if (guess < number)
{
cout << "your guess is smaller than number";
cin >> guess;
}
if (guess == number)
{
cout << "your guess is correct"<<"\t";
cout << "the number was" << number << "\n";
cout << "you guessed" << guess;
}
}*/
return 0;
} | true |
c7037e2687fbc5201805f270f31aeb7fb108257f | C++ | TyRoXx/silicium | /test/html_tree.cpp | UTF-8 | 11,154 | 2.6875 | 3 | [
"MIT"
] | permissive | #include <silicium/html/tree.hpp>
#include <silicium/sink/iterator_sink.hpp>
#include <boost/test/unit_test.hpp>
#if SILICIUM_HAS_HTML_TREE
BOOST_AUTO_TEST_CASE(html_tree)
{
using namespace Si::html;
auto document = tag(
"html",
tag("head", tag("title", text("Title"))) +
tag("body",
text("Hello, ") + raw("<b>world</b>") +
fixed_length<0>(
[](Si::Sink<char, Si::success>::interface &destination)
{
Si::html::unpaired_element(destination, "br");
}) +
tag("input", detail::make_element<min_length<0>>(
[](Si::Sink<char, Si::success>::interface &
destination)
{
Si::html::add_attribute(
destination, "key", "value");
}),
empty)));
BOOST_CHECK_EQUAL(86u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<html><head><title>Title</title></head><body>Hello, "
"<b>world</b><br/><input key=\"value\"/></body></html>",
generated);
}
#if !SILICIUM_VC2013
BOOST_AUTO_TEST_CASE(html_tree_tag_without_attributes_argument)
{
using namespace Si::html;
auto document = tag("a", empty);
BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/>", generated);
}
#endif
BOOST_AUTO_TEST_CASE(html_tree_unpaired_tag)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document = tag("a", no_attributes, empty);
BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_paired_empty_tag)
{
using namespace Si::html;
auto document =
tag("a", fixed_length<0>([](Si::Sink<char, Si::success>::interface &)
{
}));
BOOST_CHECK_EQUAL(7u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a></a>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_0)
{
using namespace Si::html;
auto document = sequence();
BOOST_CHECK_EQUAL(0u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_1)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document = sequence(tag("a", no_attributes, empty));
BOOST_CHECK_EQUAL(4u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_2)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document = sequence(
tag("a", no_attributes, empty), tag("b", no_attributes, empty));
BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/><b/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sequence_of_tags_3)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document =
sequence(tag("a", no_attributes, empty), tag("b", no_attributes, empty),
tag("c", no_attributes, empty));
BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/><b/><c/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_2)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document =
tag("a", no_attributes, empty) + tag("b", no_attributes, empty);
BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/><b/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_tag_sum_of_tags_3)
{
using namespace Si::html;
auto no_attributes = detail::make_element<exact_length<0>>(
[](Si::Sink<char, Si::success>::interface &)
{
});
auto document = tag("a", no_attributes, empty) +
tag("b", no_attributes, empty) +
tag("c", no_attributes, empty);
BOOST_CHECK_EQUAL(12u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<a/><b/><c/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_attributes_of_unpaired_tag)
{
using namespace Si::html;
auto document = tag(
"input", detail::make_element<min_length<0>>(
[](Si::Sink<char, Si::success>::interface &destination)
{
Si::html::add_attribute(destination, "key", "value");
}),
empty);
BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<input key=\"value\"/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_attributes)
{
using namespace Si::html;
auto document = tag(
"input", detail::make_element<min_length<0>>(
[](Si::Sink<char, Si::success>::interface &destination)
{
Si::html::add_attribute(destination, "key", "value");
}),
text("content"));
BOOST_CHECK_EQUAL(22u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<input key=\"value\">content</input>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_one_attribute)
{
using namespace Si::html;
auto document = tag("i", attribute("key", "value"), empty);
BOOST_CHECK_EQUAL(16u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<i key=\"value\"/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_two_attributes)
{
using namespace Si::html;
auto document = tag(
"i", attribute("key", "value") + attribute("key2", "value2"), empty);
BOOST_CHECK_EQUAL(30u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<i key=\"value\" key2=\"value2\"/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_attribute_without_value)
{
using namespace Si::html;
auto document = tag("i", attribute("key"), empty);
BOOST_CHECK_EQUAL(8u, decltype(document)::length_type::value);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<i key/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_trait)
{
Si::html::Element<>::box const erased = Si::html::Element<>::make_box(
Si::html::tag("test", Si::html::text("Hello")));
std::string generated;
auto sink =
Si::Sink<char, Si::success>::erase(Si::make_container_sink(generated));
erased.generate(sink);
BOOST_CHECK_EQUAL("<test>Hello</test>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_dynamic_attribute_value)
{
using namespace Si::html;
auto document = tag("i", attribute("key", std::string("value")), empty);
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<i key=\"value\"/>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_dynamic_text)
{
using namespace Si::html;
auto document = tag("i", text(std::string("content")));
std::string generated = generate<std::string>(document);
BOOST_CHECK_EQUAL("<i>content</i>", generated);
}
BOOST_AUTO_TEST_CASE(html_tree_produces_same_output_as_generator)
{
bool const build_triggered = true;
std::vector<char> old_style_generated;
auto html =
Si::html::make_generator(Si::make_container_sink(old_style_generated));
html("html", [&]
{
html("head", [&]
{
html("title", [&]
{
html.write("Silicium build tester");
});
});
html("body", [&]
{
if (build_triggered)
{
html.write("build was triggered");
}
html("form",
[&]
{
html.attribute("action", "/");
html.attribute("method", "POST");
},
[&]
{
html("input",
[&]
{
html.attribute("type", "submit");
html.attribute(
"value", "Trigger build");
},
Si::html::empty);
});
});
});
using namespace Si::html;
auto document = tag(
"html",
tag("head", tag("title", text("Silicium build tester"))) +
tag("body",
dynamic([build_triggered](
Si::Sink<char, Si::success>::interface &destination)
{
if (!build_triggered)
{
return;
}
text("build was triggered").generate(destination);
}) +
tag("form",
attribute("action", "/") + attribute("method", "POST"),
tag("input", attribute("type", "submit") +
attribute("value", "Trigger build"),
empty))));
std::vector<char> new_style_generated =
Si::html::generate<std::vector<char>>(document);
BOOST_CHECK(old_style_generated == new_style_generated);
}
#endif
| true |
809a3ad80f64d8e42207108c4adcbfe37858f10b | C++ | cakkae/tasks-in-cpp | /niz2.h | UTF-8 | 1,855 | 2.953125 | 3 | [] | no_license | // niz2.h - Klasa nizova apstraktnih podataka.
#ifndef _niz2_h_
#define _niz2_h_
#include "podatak.h"
#include "niz2gr.h"
class Niz: public Podatak { // Atributi:
Podatak** niz; // - niz pokazivaca na podatke,
int kap; // - kapacitet niza.
// Pomocne metode:
void kopiraj (const Niz& n); // - kopiranje niza,
void brisi () { ~*this; delete [] niz; } // - unistavanje niza,
void pisi (ostream& it) const; // - pisanje niza.
public: // Konstruktori:
explicit Niz (int k=10); // - praznog niza,
Niz (const Niz& n) { kopiraj (n); } // - kopije.
~Niz () { brisi (); } // Destruktor.
Niz* kopija () const // Dinamicka kopija.
{ return new Niz (*this); }
Niz& operator= (const Niz& n) { // Dodela vrednosti.
if (this != &n) { brisi (); kopiraj (n); }
return *this;
}
int kapac () const { return kap; } // Kapacitet niza.
// Pristup komponenti:
Podatak& operator[] (int ind) { // - promenljivog niza,
if (ind < 0 || ind >= kap) throw GIndeks (ind, kap);
if (niz[ind] == 0) throw GPrazno ();
return *niz[ind];
}
const Podatak& operator[] (int ind) const // - nepromenljivog niza.
{ return const_cast<Niz&>(*this)[ind]; }
Niz& operator+= (const Podatak& pp); // Umetanje podatka.
Niz& operator-= (int ind) { // Izbacivanje podatka.
if (ind < 0 || ind >= kap) throw GIndeks (ind, kap);
delete niz[ind]; niz[ind] = 0;
return *this;
}
Niz& operator~ (); // Praznjenje niza.
};
#endif
| true |
026c2f7b196c0ead04ea0c829867f9291b0cb824 | C++ | seqan/seqan | /include/seqan/sequence/sequence_lexical.h | UTF-8 | 22,287 | 2.6875 | 3 | [
"BSD-3-Clause"
] | permissive | // ==========================================================================
// SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2021, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Andreas Gogol-Doering <andreas.doering@mdc-berlin.de>
// ==========================================================================
// Implementation of efficient lexical sequence comparison.
// ==========================================================================
#ifndef SEQAN_HEADER_LEXICAL_H
#define SEQAN_HEADER_LEXICAL_H
namespace seqan2
{
//////////////////////////////////////////////////////////////////////////////
// Switches for prefix ordering mode
//////////////////////////////////////////////////////////////////////////////
/*!
* @defgroup PrefixOrderTags Prefix Order Tags
* @brief Specify whether less-than or greather-than comparison is meant.
*
*
* @tag PrefixOrderTags#TagPrefixLess
* @headerfile <seqan/sequence.h>
* @brief A prefix is smaller.
*
* @signature typedef Tag<TagPrefixLess_> const TagPrefixLess;
*
*
* @tag PrefixOrderTags#TagPrefixGreater
* @headerfile <seqan/sequence.h>
* @brief A prefix is larger.
*
* @signature typedef Tag<TagPrefixGreater_> const TagPrefixGreater;
*/
struct TagPrefixLess_ {};
typedef Tag<TagPrefixLess_> const TagPrefixLess;
struct TagPrefixGreater_ {};
typedef Tag<TagPrefixGreater_> const TagPrefixGreater;
/*!
* @mfn DefaultPrefixOrder
* @headerfile <seqan/sequence.h>
* @brief The default prefix order.
*
* @signature DefaultPrefixOrder<T>::Type;
*
* @tparam T The type to query for the prefix order.
*
* @return Type The prefix order tag type of T, see @link PrefixOrderTags @endlink.
*/
template <typename T>
struct DefaultPrefixOrder
{
typedef TagPrefixLess Type;
};
//////////////////////////////////////////////////////////////////////////////
// Lexical
//////////////////////////////////////////////////////////////////////////////
/*!
* @class Lexical
* @headerfile <seqan/sequence.h>
* @brief Comparator for lexical comparison.
*
* @signature template <[typename TSpec]>
* class Lexical;
*
* @tparam TSpec The specializing size type, defaults to <tt>size_t</tt>.
*
* This class implement comparator objects that perform (lexical) comparisons between two sequences. The result of the
* comparison is stored in the data members of the instance and can be accessed by some functions, for example @link
* Lexical#isLess @endlink or @link Lexical#isEqual @endlink.
*
* In most cases, there is no need for an explicite use of comparators, but sometimes this concept provide the
* opportunity to speed up the code.
*
* @section Examples
*
* This program compares the strings <tt>str1</tt> and <tt>str2</tt>:
*
* @code{.cpp}
* if (isLess(str1, str2)) //first comparison
* {
* //str1 < str2
* }
* else if (isGreater(str1, str2)) //second comparison
* {
* //str1 > str2
* }
* else
* {
* //str == str2
* }
* @endcode
*
* Using a comparator, the same program only needs one comparison instead of two:
*
* @code{.cpp}
* Lexical <> comparator(str1, str2); //comparison is executed here
* if (isLess(comparator))
* {
* //str1 < str2
* }
* else if (lexGreater(comparator))
* {
* //str1 > str2
* }
* else
* {
* //str == str2
* }
* @endcode
*
* The state of a default constructed <tt>Lexical</tt> instance is undefined until it is set by a call of @link
* Lexical#compare @endlink.
*
* @see Comparator
*/
template <typename TSpec = size_t>
struct Lexical
{
public:
typename Size<Lexical>::Type data_lcp;
char data_compare;
public:
Lexical()
{
}
template <typename TLeft, typename TRight>
Lexical(TLeft const & left, TRight const & right)
{
compare(*this, left, right);
}
Lexical(Lexical const & other):
data_lcp(other.data_lcp),
data_compare(other.data_compare)
{
}
Lexical & operator=(Lexical const & other)
{
data_compare = other.data_compare;
data_lcp = other.data_lcp;
return *this;
}
~Lexical() {}
//____________________________________________________________________________
enum
{
EQUAL = 1,
LESS = 2,
GREATER = 4,
LEFT_IS_PREFIX = 8,
RIGHT_IS_PREFIX = 16
};
};
//////////////////////////////////////////////////////////////////////////////
// Metafunctions
//////////////////////////////////////////////////////////////////////////////
// Comparator: returns object that can compare objects of type T
// TODO(holtgrew): Does this belong to the StringConcept?
/*!
* @mfn Comparator
* @headerfile <seqan/sequence.h>
* @brief Type of comparator object
*
* @signature Comparator<T>::Type;
*
* @tparam T Type for which the comparator type is to be determined.
*
* @return Type the comparator type.
*
* Comparators are objects that can be used to compare other objects and store the result of comparisons.
*/
template <typename T>
struct Comparator
{
typedef Lexical<typename Size<T>::Type> Type;
};
//////////////////////////////////////////////////////////////////////////////
// Size
template <typename TSpec>
struct Size<Lexical<TSpec> >
{
typedef TSpec Type;
};
template <typename TSpec>
struct Size<Lexical<TSpec> const>
{
typedef TSpec Type;
};
//////////////////////////////////////////////////////////////////////////////
// Spec
template <typename TSpec>
struct Spec<Lexical<TSpec> >
{
typedef TSpec Type;
};
template <typename TSpec>
struct Spec<Lexical<TSpec> const>
{
typedef TSpec Type;
};
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// compare
//////////////////////////////////////////////////////////////////////////////
// TODO(holtgrew): Does this belong to Lexical?
/*!
* @fn Lexical#compare
* @headerfile <seqan/sequence.h>
* @brief Compares two objects.
*
* @signature void compare(comparator, left, right);
*
* @param[out] comparator Object that stores the results. Types: Lexical
* @param[in] left The first objects.
* @param[in] right The second objects that is compared to <tt>left</tt>.
*
* @see Comparator
*/
template <typename TSpec, typename TLeft, typename TRight>
inline void
compare_(Lexical<TSpec> & lexical,
TLeft & left,
TRight & right)
{
typename Iterator<TLeft, Standard>::Type left_it = begin(left, Standard());
typename Size<TLeft>::Type left_length = length(left);
typename Iterator<TRight, Standard>::Type right_it = begin(right, Standard());
typename Size<TRight>::Type right_length = length(right);
if (left_length == right_length) lexical.data_compare = Lexical<TSpec>::EQUAL;
else if (left_length < right_length) lexical.data_compare = Lexical<TSpec>::LEFT_IS_PREFIX;
else
{
lexical.data_compare = Lexical<TSpec>::RIGHT_IS_PREFIX;
left_length = right_length;
}
lexical.data_lcp = 0;
for (lexical.data_lcp = 0; lexical.data_lcp < left_length; ++lexical.data_lcp)
{
if (*left_it < *right_it)
{
lexical.data_compare = Lexical<TSpec>::LESS;
break;
}
if (*left_it > *right_it)
{
lexical.data_compare = Lexical<TSpec>::GREATER;
break;
}
++left_it;
++right_it;
}
}
//////////////////////////////////////////////////////////////////////////////
template <typename TSpec, typename TLeft, typename TRight>
inline void
compare(Lexical<TSpec> & lexical,
TLeft const & left,
TRight const & right)
{
compare_(lexical, left, right);
}
// TODO(holtgrew): Are these bugs present in currently supported VC++ versions or is this only a legacy issue?
//workaround for VC++ "const arrays" bug
template <typename TSpec, typename TLeftValue, typename TRight>
inline void
compare(Lexical<TSpec> & lexical,
TLeftValue const * left,
TRight const & right)
{
compare_(lexical, left, right);
}
template <typename TSpec, typename TLeftValue, typename TRightValue>
inline void
compare(Lexical<TSpec> & lexical,
TLeftValue const * left,
TRightValue const * right)
{
compare_(lexical, left, right);
}
template <typename TSpec, typename TLeft, typename TRightValue>
inline void
compare(Lexical<TSpec> & lexical,
TLeft const & left,
TRightValue const * right)
{
compare_(lexical, left, right);
}
//////////////////////////////////////////////////////////////////////////////
// isEqual
//////////////////////////////////////////////////////////////////////////////
// TODO(holtgrew): Do we need the left/right specialization of this function here?
/*!
* @fn Lexical#isEqual
* @headerfile <seqan/sequence.h>
* @brief Operator "==".
*
* @signature bool isEqual(left, right);
* @signature bool isEqual(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> equals <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight >
inline bool
isEqual(TLeft const & left,
TRight const & right)
{
return left == right;
}
template <typename TSpec>
inline bool
isEqual(Lexical<TSpec> const & _lex)
{
return (_lex.data_compare & Lexical<TSpec>::EQUAL);
}
//////////////////////////////////////////////////////////////////////////////
// isNotEqual
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isNotEqual
* @headerfile <seqan/sequence.h>
* @brief Operator "!=".
*
* @signature bool isNotEqual(left, right);
* @signature bool isNotEqual(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> does not equal <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight >
inline bool
isNotEqual(TLeft const & left,
TRight const & right)
{
return left != right;
}
template <typename TSpec>
inline bool
isNotEqual(Lexical<TSpec> const & _lex)
{
return !(_lex.data_compare & Lexical<TSpec>::EQUAL);
}
//////////////////////////////////////////////////////////////////////////////
// isLess
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isLess
* @headerfile <seqan/sequence.h>
* @brief Operator "<".
*
* @signature bool isLess(left, right);
* @signature bool isLess(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is less than <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight, typename TPrefixOrder >
inline bool
isLess(TLeft const & left,
TRight const & right,
Tag<TPrefixOrder> const tag)
{
typename Comparator<TLeft>::Type _lex(left, right);
return isLess(_lex, tag);
}
template <typename TLeft, typename TRight>
inline bool
isLess(TLeft const & left,
TRight const & right)
{
return left < right;
}
template <typename TSpec>
inline bool
isLess(Lexical<TSpec> const & _lex,
TagPrefixLess)
{
return (_lex.data_compare & (Lexical<TSpec>::LESS | Lexical<TSpec>::LEFT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isLess(Lexical<TSpec> const & _lex,
TagPrefixGreater)
{
return (_lex.data_compare & (Lexical<TSpec>::LESS | Lexical<TSpec>::RIGHT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isLess(Lexical<TSpec> const & _lex)
{
return isLess(_lex, typename DefaultPrefixOrder< Lexical<TSpec> >::Type());
}
//////////////////////////////////////////////////////////////////////////////
// isLessOrEqual
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isLessOrEqual
* @headerfile <seqan/sequence.h>
* @brief Operator "<=".
*
* @signature bool isLessOrEqual(left, right);
* @signature bool isLessOrEqual(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is less than or equal to <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight, typename TPrefixOrder >
inline bool
isLessOrEqual(TLeft const & left,
TRight const & right,
Tag<TPrefixOrder> const tag)
{
typename Comparator<TLeft>::Type _lex(left, right);
return isLessOrEqual(_lex, tag);
}
template <typename TLeft, typename TRight>
inline bool
isLessOrEqual(TLeft const & left,
TRight const & right)
{
return left <= right;
}
template <typename TSpec>
inline bool
isLessOrEqual(Lexical<TSpec> const & _lex,
TagPrefixLess)
{
return (_lex.data_compare & (Lexical<TSpec>::LESS | Lexical<TSpec>::EQUAL | Lexical<TSpec>::LEFT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isLessOrEqual(Lexical<TSpec> const & _lex,
TagPrefixGreater)
{
return (_lex.data_compare & (Lexical<TSpec>::LESS | Lexical<TSpec>::EQUAL | Lexical<TSpec>::RIGHT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isLessOrEqual(Lexical<TSpec> const & _lex)
{
return isLessOrEqual(_lex, typename DefaultPrefixOrder< Lexical<TSpec> >::Type());
}
//////////////////////////////////////////////////////////////////////////////
// isGreater
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isGreater
* @headerfile <seqan/sequence.h>
* @brief Operator ">".
*
* @signature bool isGreater(left, right);
* @signature bool isGreater(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is greater than <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight, typename TPrefixOrder >
inline bool
isGreater(TLeft const & left,
TRight const & right,
Tag<TPrefixOrder> const tag)
{
typename Comparator<TLeft>::Type _lex(left, right);
return isGreater(_lex, tag);
}
template <typename TLeft, typename TRight>
inline bool
isGreater(TLeft const & left,
TRight const & right)
{
return left > right;
}
template <typename TSpec>
inline bool
isGreater(Lexical<TSpec> const & _lex,
TagPrefixLess)
{
return (_lex.data_compare & (Lexical<TSpec>::GREATER | Lexical<TSpec>::RIGHT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isGreater(Lexical<TSpec> const & _lex,
TagPrefixGreater)
{
return (_lex.data_compare & (Lexical<TSpec>::GREATER | Lexical<TSpec>::LEFT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isGreater(Lexical<TSpec> const & _lex)
{
return isGreater(_lex, typename DefaultPrefixOrder< Lexical<TSpec> >::Type());
}
//////////////////////////////////////////////////////////////////////////////
// isGreaterOrEqual
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isGreaterOrEqual
* @headerfile <seqan/sequence.h>
* @brief Operator ">=".
*
* @signature bool isGreaterOrEqual(left, right);
* @signature bool isGreaterOrEqual(comparator);
*
* @param[in] left The first parameter.
* @param[in] right The second parameter that is compared to <tt>left</tt>.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is greater than or equal to <tt>right</tt>, <tt>false</tt> otherwise.
*/
template <typename TLeft, typename TRight, typename TPrefixOrder >
inline bool
isGreaterOrEqual(TLeft const & left,
TRight const & right,
Tag<TPrefixOrder> const tag)
{
typename Comparator<TLeft>::Type _lex(left, right);
return isGreaterOrEqual(_lex, tag);
}
template <typename TLeft, typename TRight>
inline bool
isGreaterOrEqual(TLeft const & left,
TRight const & right)
{
return left >= right;
}
template <typename TSpec>
inline bool
isGreaterOrEqual(Lexical<TSpec> const & _lex,
TagPrefixLess)
{
return (_lex.data_compare & (Lexical<TSpec>::GREATER | Lexical<TSpec>::EQUAL | Lexical<TSpec>::RIGHT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isGreaterOrEqual(Lexical<TSpec> const & _lex,
TagPrefixGreater)
{
return (_lex.data_compare & (Lexical<TSpec>::GREATER | Lexical<TSpec>::EQUAL | Lexical<TSpec>::LEFT_IS_PREFIX)) != 0;
}
template <typename TSpec>
inline bool
isGreaterOrEqual(Lexical<TSpec> const & _lex)
{
return isGreaterOrEqual(_lex, typename DefaultPrefixOrder< Lexical<TSpec> >::Type());
}
//////////////////////////////////////////////////////////////////////////////
// isPrefix
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#isPrefix
* @headerfile <seqan/sequence.h>
* @brief Test whether a sequence is the prefix of another sequence.
*
* @signature bool isPrefix(left, right);
* @signature bool isPrefix(comparator);
*
* @param[in] left The putative prefix.
* @param[in] right The second sequence.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is a prefix of<tt>right</tt>, <tt>false</tt> otherwise.
*
* By definition, a sequence is a prefix of itself: <tt>isPrefix("abc", "abc")</tt> is <tt>true</tt>.
*/
template <typename TLeft, typename TRight >
inline bool
isPrefix(TLeft const & left,
TRight const & right)
{
typename Comparator<TLeft>::Type _lex(left, right);
return isPrefix(_lex);
}
template <typename TSpec>
inline bool
isPrefix(Lexical<TSpec> const & _lex)
{
return (_lex.data_compare & (Lexical<TSpec>::LEFT_IS_PREFIX | Lexical<TSpec>::EQUAL)) != 0;
}
//////////////////////////////////////////////////////////////////////////////
// hasPrefix
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#hasPrefix
* @headerfile <seqan/sequence.h>
* @brief Test whether a sequence is the prefix of another sequence.
*
* @signature bool isPrefix(left, right);
* @signature bool isPrefix(comparator);
*
* @param[in] left The first sequence.
* @param[in] right The putative prefix.
* @param[in] comparator A comparator. Types: Lexical
*
* @return bool <tt>true</tt> if <tt>left</tt> is a prefix of<tt>right</tt>, <tt>false</tt> otherwise.
*
* By definition, a sequence is a prefix of itself: <tt>hasPrefix("abc", "abc")</tt> is <tt>true</tt>.
*/
template <typename TLeft, typename TRight >
inline bool
hasPrefix(TLeft const & left,
TRight const & right)
{
typename Comparator<TLeft>::Type _lex(left, right);
return hasPrefix(_lex);
}
template <typename TSpec>
inline bool
hasPrefix(Lexical<TSpec> const & _lex)
{
return (_lex.data_compare & (Lexical<TSpec>::RIGHT_IS_PREFIX | Lexical<TSpec>::EQUAL)) != 0;
}
//////////////////////////////////////////////////////////////////////////////
// lcpLength
//////////////////////////////////////////////////////////////////////////////
/*!
* @fn Lexical#lcpLength
* @headerfile <seqan/sequence.h>
* @brief Length of the longest common prefix.
*
* @signature TSize lcpLength(left, right);
* @signature TSize lcpLength(comparator);
*
* @param[in] left The first sequence.
* @param[in] right The second sequence.
* @param[in] comparator A comparator. Types: Lexical
*
* @return TSize The length of the longest common prefix of <tt>left</tt> and <tt>right</tt>. TSize is the Size type of
* the left size type.
*
* By definition, a sequence is a prefix of itself: <tt>hasPrefix("abc", "abc")</tt> is <tt>true</tt>.
*/
template <typename TLeft, typename TRight >
inline typename Size<TLeft>::Type
lcpLength(TLeft const & left, TRight const & right)
{
typename Comparator<TLeft>::Type _lex(left, right);
return lcpLength(_lex);
}
template <typename TSpec>
inline typename Size< Lexical<TSpec> >::Type
lcpLength(Lexical<TSpec> const & _lex)
{
return _lex.data_lcp;
}
} //namespace seqan2
#endif //#ifndef SEQAN_HEADER_...
| true |
6ef455cd060c858864c8c4c00c67b7fdfa8ceb24 | C++ | nayuta1019/AtCoder | /ABC/ABC021-030/ABC030/B/B.cpp | UTF-8 | 593 | 2.578125 | 3 | [] | no_license | /**
ABC030
2018/12/30/ 解説AC
**/
#include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i < (b); ++i)
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
inline int toInt(string s) {int v; istringstream sin(s);sin>>v; return v;}
typedef long long ll;
int main(){
int n, m;
cin >> n >> m;
n = n%12;
double s = (double)360/12*n+(double)360/12/60*m, l = (double)360/60*m;
double ans = abs(l - s);
if(180 <= ans) ans = 360 - ans;
cout << ans << endl;
return 0;
} | true |
27923cd02f19fa0f5749dc0a9e692d9a071be606 | C++ | jbji/2019-Programming-Basics-C- | /Other Works/20_7_5_p3/main.cpp | UTF-8 | 708 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int h;
cin >> h;
for(int line=0;line<h;line++){
//第line行,需要输出h-line-1个横杠,1个左斜边,line个空格;
//line个空格;1个右斜边;h-line-1个横杠,
for(int i=0;i<h-line-1;i++){
cout << '-';
}
cout << '/';
if(line!=h-1){
for(int i=0;i<2*line;i++){
cout <<' ';
}
}else{
for(int i=0;i<2*line;i++){
cout <<'_';
}
}
cout << '\\';
for(int i=0;i<h-line-1;i++){
cout << '-';
}
cout << endl;
}
return 0;
} | true |
6d35ca75204bbdd104df43980681f38e627c752e | C++ | nameisshenlei/1.0.0.beta2 | /Source/dataInfo.h | UTF-8 | 1,039 | 2.546875 | 3 | [] | no_license | #ifndef _DATA_INFO_H__
#define _DATA_INFO_H__
#include "publicHeader.h"
class dataInfo : public Timer
{
public:
dataInfo(String strVMemoryName, String strAMemoryName);
virtual ~dataInfo();
void VUpdataData(guint64 iVCurrentPts);
void AUpdataData(guint64 iACurrentPts);
void BeginTimer(int intervalInMilliseconds);
void EndTimer();
void DirectStopTimer();
private:
dataInfo();
virtual void timerCallback() override;
void startTimer(int intervalInMilliseconds) noexcept;
void stopTimer() noexcept;
private:
String m_strVMemoryName;
String m_strAMemoryName;
String m_strFileName;
int m_iTimerRefCount;
int m_intervalInMilliseconds;
guint64 m_uiVBeginPts;
guint64 m_uiVCurrentPts;
guint64 m_uiVOldPts;
guint64 m_uiVIndex;
gint64 m_iVMaxPtsDiff;
gint64 m_iVVAGDiff;
gint64 m_iVTotalDiff;
guint64 m_uiABeginPts;
guint64 m_uiACurrentPts;
guint64 m_uiAOldPts;
guint64 m_uiAIndex;
gint64 m_iAMaxPtsDiff;
gint64 m_iAVAGDiff;
gint64 m_iATotalDiff;
};
#endif//_DATA_INFO_H__ | true |
d8651af74f368872413198587c3d43d6f32f858b | C++ | pranshu2610/Algorithms-2 | /Bits Manipulation/reverse_bits.cpp | UTF-8 | 577 | 2.59375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
long long reverse_bits(unsigned int n)
{
unsigned long long rev = 0;
unsigned long long n1 = A;
int count = 0;
while(n1)
{
n1 = n1 >> 1;
count++;
}
while( A > 0)
{
rev = rev << 1;
if((A & 1) == 1)
rev = rev ^ 1;
A = A >> 1;
}
rev = rev << (32 - count);
return rev;
}
int main()
{
freopen("test.in", "r", stdin);
freopen("test.out", "w", stdout);
unsigned long long x;
cin >> x;
cout << reverse_bits(x);
} | true |
be50ee2144643479881bf2c11d3feb427a0e1663 | C++ | AbhishekPratik1810/my_cpp_dsa_practice | /3.03 Strings - Permuations.cpp | UTF-8 | 828 | 3.109375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
vector<string> getPermutations(int currPos,string &s){
if(currPos==s.size()-1){
string a;
a.push_back(s[currPos]);
return vector<string> (1,a);
}
vector<string> fwd = getPermutations(currPos+1, s);
vector<string> ans;
for(auto str : fwd){
ans.push_back(s[currPos]+str);
int length = str.size();
for(int i=1;i<length;i++)
ans.push_back(str.substr(0,i) + s[currPos] + str.substr(i));
ans.push_back(str+s[currPos]);
}
return ans;
}
int main() {
int t; cin>>t;
while(t--){
string s;
cin>>s;
vector<string> res = getPermutations(0,s);
sort(res.begin(),res.end());
for(auto str : res)
cout<<str<<" ";
cout<<endl;
}
return 0;
}
| true |
8c3347bb887d9999265d6e5ae29b8a74c08b09c4 | C++ | thaohien97/school_homework | /main_thread.cpp | UTF-8 | 4,327 | 2.734375 | 3 | [] | no_license | //
// main.cpp
// COSC3360_Hw3
//
// Created by Hien Nguyen on 4/6/19.
// Copyright © 2019 Hien Nguyen. All rights reserved.
//
#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <vector>
#include <stdio.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
//worked with Jeremy Bayangos
pthread_t threading_id[10];
static int sgroup;
int groupie[2] = {0,0};
int groupie2[2] = {0,0};
static bool foundation[10] = {false}; //database
static int occupy[10];
static int wait_g; //wait based on group
static int wait_p; //wait based on position
bool flag_s = false;
struct keep
{
int id, pos, start, end, group;
keep (int ngroup, int npos, int sstart, int nend, int nid){
id = nid;
pos = npos;
start = sstart;
end = nend;
group = ngroup;
}
};
static pthread_mutex_t pos_lock[10]; //position lock
static pthread_mutex_t group_lock = PTHREAD_MUTEX_INITIALIZER; //group lock
static pthread_cond_t grouper = PTHREAD_COND_INITIALIZER; //group condition
static pthread_cond_t poser[10]; //position condition
void *data(void *data_ptr) //condition variable
{
keep a=*(keep *)data_ptr;
cout<<"User "<<a.id;
cout <<" from group "<<a.group;
cout <<" arives to the DBMS"<<endl;
pthread_mutex_lock(&group_lock);
if(a.group!=sgroup){
cout<<"User "<<a.id;
cout <<" is waiting due to its group "<<endl;
pthread_cond_wait(&grouper, &group_lock);
wait_g++;
}
pthread_mutex_unlock(&group_lock); //unlock group lock
pthread_mutex_lock(&pos_lock[a.pos]);
if(foundation[a.pos]!=false)
{
cout<<"User "<<a.id;
cout <<" is waiting: position "<<a.pos;
cout <<" is being used by user ";
cout<<occupy[a.pos]<<endl;
wait_p++;
pthread_cond_wait(&poser[a.pos], &pos_lock[a.pos]);
}
pthread_mutex_unlock(&pos_lock[a.pos]); //unlock position lock
cout<<"User "<<a.id;
cout <<" is accesing the position "<<a.pos;
cout <<" of the database for "<<a.end;
cout <<" secound(s)"<<endl;
occupy[a.pos]=a.id;
foundation[a.pos]=true;
sleep(a.end);
cout<<"User "<<a.id;
cout<<" finished its execution"<<endl;
pthread_mutex_lock(&pos_lock[a.pos]);
pthread_cond_signal(&poser[a.pos]);
foundation[a.pos]=false;
groupie[a.group-1]--;
pthread_mutex_unlock(&pos_lock[a.pos]); //unlock position lock again
pthread_mutex_lock(&group_lock);
if(groupie[sgroup-1]==0){
if(!flag_s){
cout<<"All users from Group " <<sgroup;
cout << " finished their execution"<<endl;
int b=sgroup==1?2:1;
cout<<"The users from Group "<<b;
cout <<" start their execution\n"<<endl;
flag_s=true;
}
pthread_cond_signal(&grouper);
}
pthread_mutex_unlock(&group_lock);
return 0;
}
int main(int argc, const char * argv[]) {
for (int i =0; i<10; i++){
pos_lock[i] = PTHREAD_MUTEX_INITIALIZER;
poser[i] = PTHREAD_COND_INITIALIZER;
}
int pos, start, end, group;
int set = 1;
int i = 0;
cin >>sgroup;
while(cin >> group >> pos >> start >> end)
{
sleep(start);
//totaling
groupie[group-1]++;
//for copyer number 2
groupie2[group-1]++;
keep temp(group, pos, start, end, set);
if(pthread_create(&threading_id[i], NULL, data,(void*)&temp)) //used the sample file
{
cerr<< "Error creating thread" << endl;
return 1;
}set++; i++;
}
for(int i = 0; i<set;i++)
{
pthread_join(threading_id[i], NULL);
}
cout <<"Total request:"<<endl;
cout <<" Group 1: "<<groupie2[0]<<endl;
cout <<" Group 2: "<<groupie2[1]<<endl;
cout <<"Requests that waited:"<<endl;
cout <<" Due to its group: "<< wait_g <<endl;
cout <<" Due to locked position: "<<wait_g<<endl;
return 0;
}
| true |
0463e54ea8b9022403fef8faf3795314dd5b95b7 | C++ | idunnowhy9000/Projects | /SOURCE/C++/Numbers/Tile Cost.cpp | UTF-8 | 772 | 3.90625 | 4 | [
"MIT"
] | permissive | /**
* Tile Cost: Find Cost of Tile to Cover W x H Floor
*/
#include <iostream>
#include <string>
#include <cmath>
float calcCost (float cost, float width, float height) {
return cost*width*height;
}
int main() {
float width;
std::string str_width;
float height;
std::string str_height;
float cost;
std::string str_cost;
float total;
std::cout << "Cost per tile: ";
std::getline(std::cin, str_cost);
cost = std::stof(str_cost);
std::cout << "Width of room: ";
std::getline(std::cin, str_width);
width = std::stof(str_width);
std::cout << "Height of room: ";
std::getline(std::cin, str_height);
height = std::stof(str_height);
total = calcCost(cost, width, height);
std::cout << "Total cost of tiling is " << "$" << round(total);
return 0;
}
| true |
07307219a289cf338ed86e5c04c7e8d661204818 | C++ | bmcclelland/586-backend | /src/lib/util/color.h | UTF-8 | 978 | 2.8125 | 3 | [] | no_license | #pragma once
#include <string>
#include <iosfwd>
namespace mvc {
enum class Color
{
off = 0,
default_ = 39,
black = 30,
red = 31,
green = 32,
yellow = 33,
blue = 34,
magenta = 35,
cyan = 36,
lgray = 37,
gray = 90,
lred = 91,
lgreen = 92,
lyellow = 93,
lblue = 94,
lmagenta = 95,
lcyan = 96,
white = 97,
};
enum class BColor
{
off = 0,
default_ = 39,
black = 30,
red = 31,
green = 32,
yellow = 33,
blue = 34,
magenta = 35,
cyan = 36,
lgray = 37,
gray = 90,
lred = 91,
lgreen = 92,
lyellow = 93,
lblue = 94,
lmagenta = 95,
lcyan = 96,
white = 97,
};
std::string to_string(Color);
std::ostream& operator<<(std::ostream&, Color);
std::string to_string(BColor);
std::ostream& operator<<(std::ostream&, BColor);
} // namespace mvc
| true |
934f52a3a0a082d048a4288f6584a7011b09ba79 | C++ | NickArust/COP_3504C | /main.cpp | UTF-8 | 2,240 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include "StringData.h"
using namespace std;
int linearSearch(vector<string> dataset, string element);
int binarySearch(vector<string> dataset, string element);
vector<long long> timerSearch (vector<string> dataset, string element);
int main() {
vector<string> dataset = getStringData(); // gets data
vector<long long> times = timerSearch(dataset, "aaaaa"); // does the timing for each value and prints result
cout<<"aaaaa"<<endl;
cout<< times[0] <<endl;
cout<< times[1] <<endl;
times = timerSearch(dataset, "mzzzz");
cout<<"mzzzz"<<endl;
cout<< times[0] <<endl;
cout<< times[1] <<endl;
times = timerSearch(dataset, "not_here");
cout<<"not_here"<<endl;
cout<< times[0] <<endl;
cout<< times[1] <<endl;
return 0;
}
int linearSearch(vector<string> dataset, string element) {
for(int i = 0;i<dataset.capacity();i++){ // does linear search
if(dataset[i]==element){return i;}
}
return -1;
}
int binarySearch(vector<string> dataset, string element){
int minIndex = 0;
int maxIndex = dataset.capacity()-1;
int midIndex = minIndex + (maxIndex - minIndex) / 2; // sets the max, min, mid indexs
while (minIndex <= maxIndex){
if(dataset[midIndex] == element){ // returns if we have a match
return midIndex;
}
else if (element.compare(dataset[midIndex]) >0){ // changes indexs based on where we are reletive to element
minIndex = midIndex+1;
}
else if (element.compare(dataset[midIndex]) < 0) {
maxIndex = midIndex - 1;
}
midIndex = minIndex + (maxIndex - minIndex) / 2;
}
return -1;
}
vector<long long> timerSearch (vector<string> dataset, string element){
long long slTime = systemTimeNanoseconds();
linearSearch(dataset, element);
long long elTime = systemTimeNanoseconds();
long long sbTime = systemTimeNanoseconds();
binarySearch(dataset, element); // does the timing and returns array for binary and linear time
long long ebTime = systemTimeNanoseconds();
long long ltime = elTime-slTime;
long long btime = ebTime- sbTime;
vector<long long> timeArray{ltime,btime};
return timeArray;
}
| true |
96eccb91d431b2a04ee2e8e34d479af8f3331f1f | C++ | gusrl4025/algorithm | /d.com algorithm study/week 3/1260 - DFS와 BFS.cpp | UHC | 1,554 | 3.203125 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int n, m, v, from, to;
vector<int> a[1005];
queue<int> q;
int check[10005];
void dfs(int v) {
printf("%d ", v);
check[v] = true;
// ڽ ģ.
for (int i = 0; i < a[v].size(); i++) {
int x = a[v][i];
// İ.
if (check[x] == false) dfs(x);
}
}
void bfs(int v) {
check[v] = true;
// queue ִ´.
q.push(v);
while (!q.empty()) {
// ̵Ѵ.
int x = q.front();
printf("%d ", x);
// popŲ.
q.pop();
// queue ִ´.
for (int i = 0; i < a[x].size(); i++) {
// 뺰 δ.
int z = a[x][i];
if (check[z] == false) {
check[z] = true;
q.push(z);
}
}
}
}
int main() {
scanf("%d%d%d", &n, &m, &v);
for (int i = 0; i < m; i++) {
scanf("%d%d", &from, &to);
a[from].push_back(to);
a[to].push_back(from);
}
// sort ڽ̸ ũ µǰ Ѵ.
for (int i = 1; i <= n; i++) {
sort(a[i].begin(), a[i].end());
}
dfs(v);
printf("\n");
// check 迭 0 ʱȭش.
for (int i = 1; i <= n; i++) check[i] = 0;
bfs(v);
} | true |
9cb94f8c4074187bcd43755dad5b5f1f54cc0e51 | C++ | EvgeniyMsk/CPP_modules | /08/ex00/easyfind.hpp | UTF-8 | 1,477 | 2.78125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* easyfind.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: qsymond <qsymond@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/18 22:25:52 by qsymond #+# #+# */
/* Updated: 2020/12/18 22:25:53 by qsymond ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef EASYFIND_HPP
#define EASYFIND_HPP
#include <list>
#include <iostream>
#include <set>
#include <algorithm>
class FinderException : public std::exception
{
public:
FinderException(std::string const &reason)
{
std::cout << reason << std::endl;
};
};
template <typename T>
typename T::iterator easyfind(T &container, int value)
{
int result = *std::find(container.begin(), container.end(), value);
if (result == value)
{
std::cout << "Value was found: ";
return (std::find(container.begin(), container.end(), value));
}
throw FinderException("it can’t be found");
}
#endif | true |
e521ca34caa01b0b582570ace28c95bd86ab2dba | C++ | yuyuyu00/Tesi | /RHeroes/slam/support/nearestmatrices.h | UTF-8 | 1,318 | 2.75 | 3 | [] | no_license | /*
* nearestmatrices.h
*
* Created on: 01/feb/2013
* Author: Mladen Mazuran
*/
#ifndef NEARESTMATRICES_H_
#define NEARESTMATRICES_H_
#include <Eigen/Core>
#include <Eigen/Cholesky>
#include <Eigen/SVD>
#include "shared/utilities.h"
namespace SLAM {
namespace Support {
/*
Fan, K. and Hoffman, A.J. (1955) Some metric inequalities in the space of matrices,
Proc. Amer. Math. Soc. 6, 111–116.
*/
template <int N>
inline Eigen::Matrix<double, N, N> nearestSymmetric(const Eigen::Matrix<double, N, N> &m)
{
return (m + m.transpose()) / 2;
}
/*
Higham, N.J. (1988a) Computing a nearest symmetric positive semidefinite matrix,
Linear Algebra and Appl. 103, 103–118.
*/
template <int N>
inline Eigen::Matrix<double, N, N> nearestDefinitePositive(
const Eigen::Matrix<double, N, N> &m, double diagonalDelta = 1e-6)
{
if(!m.ldlt().isPositive()) {
Eigen::Matrix<double, N, N> s = nearestSymmetric(m);
Eigen::JacobiSVD<Eigen::Matrix<double, N, N> > svd(s, Eigen::ComputeFullV);
return (svd.matrixV() * svd.singularValues().asDiagonal() * svd.matrixV().transpose() +
s) / 2 + diagonalDelta * Eigen::Matrix<double, N, N>::Identity();
} else {
return m;
}
}
} /* namespace Support */
} /* namespace SLAM */
#endif /* NEARESTMATRICES_H_ */
| true |
89a93dedfe68bf6e4602c42712584186d02328ac | C++ | Zirias/shuttercontrol | /src/controlleraction.h | UTF-8 | 683 | 2.6875 | 3 | [] | no_license | #ifndef SCTL_CONTROLLERACTION_H
#define SCTL_CONTROLLERACTION_H
#include <QVector>
class ControllerAction
{
public:
class Step
{
friend class ControllerAction;
friend class QVector<Step>;
public:
enum Type
{
Direction,
Write,
Read,
WaitClock,
Done
};
Type type() const;
int value() const;
private:
Step(Type type, int value = 0);
Step();
Type _type;
int _value;
};
enum Type
{
Up,
Down,
Stop,
Status,
Cal
};
const Step &nextStep();
int address() const;
ControllerAction(Type type, int address);
private:
int _pos;
int _address;
QVector<Step> _steps;
};
#endif
| true |
eeab4f3604232aa745e56da97a2342651c6daef0 | C++ | OldSchmitty/CS457 | /Server/OutputManager.h | UTF-8 | 1,070 | 2.625 | 3 | [] | no_license | //
// Created by Mark Smith on 10/29/18.
//
#ifndef SERVER_OUTPUTMANAGER_H
#define SERVER_OUTPUTMANAGER_H
#include <string>
#include <mutex>
#include <vector>
#include "Server.h"
#include <queue>
#include <condition_variable>
#include <thread>
class OutputManager {
class Message{
public:
std::string msg;
std::string channel;
std::string user;
Message(std::string msg, std::string channel, std::string user){
this->msg = msg;
this->channel = channel;
this->user = user;
}
};
public:
void addToQueue(std::string msg, std::string channel, std::string user);
OutputManager(Server *server);
void stop();
void start();
bool ready = true;
std::mutex mtx;
std::condition_variable cv;
std::queue<Message> messages;
Server *server;
private:
static void outputThread(OutputManager &out);
std::unique_ptr<std::thread> ot;
};
#endif //SERVER_OUTPUTMANAGER_H
| true |
b614de261939c39dc110d480ed1867eb7517b727 | C++ | wikijin/92 | /hw12/InsertionSort.cpp | UTF-8 | 878 | 3.09375 | 3 | [] | no_license | //
// Created by TwoDog on 2017/4/25.
//
#include "InsertionSort.h"
/**
* Constructor.
* @param name the name of the algorithm.
*/
InsertionSort::InsertionSort(string name) : VectorSorter(name) {}
/**
* Destructor.
*/
InsertionSort::~InsertionSort() {}
/**
* Run the insertion sort algorithm.
* @throws an exception if an error occurred.
*/
void InsertionSort::run_sort_algorithm() throw (string)
{
/***** Complete this member function. *****/
for (int i = 1; i < size; ++i) {
long val = data[i].get_value();
int j = i - 1;
for (; j >= 0; --j) {
compare_count++;
if (val >= data[j].get_value())
break;
}
Element temp = data[i];
for (int k = i - 1; k > j; --k) {
data[k + 1] = data[k];
move_count++;
}
data[j + 1] = temp;
}
}
| true |
3d42be699fb24477e01fde417dbc859cb20358e0 | C++ | WangDrop/WangDropExercise | /algorithm/LeetCode/UniqueBinarySearchTreeII.cpp | UTF-8 | 1,278 | 3.046875 | 3 | [] | no_license | class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
return createNode(1, n);
}
vector<TreeNode*> createNode(int start, int end)
{
vector<TreeNode*> result;
if(start > end){
result.push_back(NULL);
return result;
}
for(int i = start; i <= end; ++i){
vector<TreeNode*> leftNode = createNode(start, i - 1);
vector<TreeNode*> rightNode = createNode(i + 1, end);
for(int j = 0; j < leftNode.size(); ++j){
for(int k = 0; k < rightNode.size(); ++k){
TreeNode * tmpNode = new TreeNode(i);
tmpNode->left = leftNode[j];
tmpNode->right = rightNode[k];
result.push_back(tmpNode);
}
}
}
return result;
}
};
| true |
47ee31b1162c6b8fa4a680eb5a005c62e9bbee69 | C++ | baibaixue/my_raytracer | /raytracer/geometry/Union.cpp | GB18030 | 1,258 | 2.703125 | 3 | [] | no_license | #include"geometry/Union.h"
namespace rt
{
Union::Union(std::vector<rt::Generation*> generations)
{
generation = generations;
}
IntersectResult Union::intersect(Ray3& _ray)
{
//printf("x:%lf y:%lf z:%lf\n", _ray.origin.x, _ray.origin.y, _ray.origin.z);
float minDistance = Mathf::inifinity; //̾
IntersectResult minresult = IntersectResult::noHit(); //ʼδӴ
for (int i = 0; i < generation.size(); i++)
{
IntersectResult result = generation[i]->intersect(_ray);
if (result.is_hit && result.distance < minDistance) //мҵཻļ
{
minDistance = result.distance; //¾
minresult = result; //¹ཻ
}
}
return minresult;
}
void Union::Add(Generation* _generation)
{
generation.push_back(_generation);
}
void Union::move_location(const Vector3& vec)
{
for (unsigned int i = 0; i < generation.size(); i++) {
generation[i]->move_location(vec);
}
return;
}
void Union::turn_location(const float& xoffset, const float& yoffset)
{
for (unsigned int i = 0; i < generation.size(); i++) {
generation[i]->turn_location(xoffset,yoffset);
}
return;
}
} | true |
19dc1af35f8a4779884526cb90e3a3fac630f00d | C++ | cdsama/LeetCode | /src/0714.cpp | UTF-8 | 1,462 | 3.3125 | 3 | [] | no_license | #include "LeetCode.hpp"
/*
714. Best Time to Buy and Sell Stock with Transaction Fee
Medium
Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.
You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)
Return the maximum profit you can make.
Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Note:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
Tags:
1. Array
2. Dynamic Programming
3. Greedy
Similar Questions:
1. Best Time to Buy and Sell Stock II
Hint 1:
Consider the first K stock prices. At the end, the only legal states are that you don't own a share of stock, or that you do. Calculate the most profit you could have under each of these two cases.
*/
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
}
};
TEST_CASE("best-time-to-buy-and-sell-stock-with-transaction-fee", "[714][Medium][array][dynamic-programming][greedy]") {
//TODO
CHECK(true);
}
| true |
5ecaa85f731cd53c7c5a62fb8e0ca31a9688d558 | C++ | nghiaho12/CellCounter | /OpenGLPanZoom.cpp | UTF-8 | 2,974 | 2.8125 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #include <cmath>
#include <cstdio>
#ifdef _WIN32
#include <windows.h> // This needs to preceed the GL includes
#endif
#include <GL/gl.h>
#include <GL/glu.h>
#include "OpenGLPanZoom.h"
OpenGLPanZoom::OpenGLPanZoom()
{
m_tx = 0.0f;
m_ty = 0.0f;
m_scale = 1.0f;
m_zoom_level = 0;
m_image_x = 0.0f;
m_image_y = 0.0f;
m_zoom_x = 0.0f;
m_zoom_y = 0.0f;
}
void OpenGLPanZoom::SetMouse(float x, float y)
{
m_last_mouse_x = m_cur_mouse_x;
m_last_mouse_y = m_cur_mouse_y;
m_cur_mouse_x = x;
m_cur_mouse_y = y;
}
void OpenGLPanZoom::SetImageWidth(int width, int height)
{
m_image_width = width;
m_image_height = height;
}
void OpenGLPanZoom::GetWorldPos(float screen_x, float screen_y, float &world_x, float &world_y)
{
GLdouble model[16];
GLdouble proj[16];
GLint view[4];
GLdouble x, y, z;
glGetDoublev(GL_MODELVIEW_MATRIX, model);
glGetDoublev(GL_PROJECTION_MATRIX, proj);
glGetIntegerv(GL_VIEWPORT, view);
gluUnProject((GLdouble)screen_x, (GLdouble)screen_y, 0.0, model, proj, view, &x, &y, &z);
world_x = (float)x;
world_y = (float)y;
}
void OpenGLPanZoom::UpdateZoom()
{
GetWorldPos(m_cur_mouse_x, m_cur_mouse_y,m_image_x, m_image_y);
m_zoom_x = m_cur_mouse_x;
m_zoom_y = m_cur_mouse_y;
// We don't need the extra translation from mouse moving anymore, taken care of by m_zoom_x/y
m_tx = 0;
m_ty = 0;
}
void OpenGLPanZoom::Move()
{
float dx = m_cur_mouse_x - m_last_mouse_x;
float dy = m_cur_mouse_y - m_last_mouse_y;
m_tx += dx;
m_ty += dy;
}
void OpenGLPanZoom::ZoomIn()
{
m_zoom_level++;
m_scale = powf(1.5f, (float)m_zoom_level);
UpdateZoom();
}
void OpenGLPanZoom::ZoomOut()
{
m_zoom_level--;
m_scale = powf(1.5f, (float)m_zoom_level);
UpdateZoom();
}
void OpenGLPanZoom::Centre()
{
GLint view[4];
glGetIntegerv(GL_VIEWPORT, view);
int view_width = view[2];
int view_height = view[3];
if(view_width < view_height) {
m_scale = (float)view_width/m_image_width;
}
else {
m_scale = (float)view_height/m_image_height;
}
// Round to the nearest zoom level
m_zoom_level = (int)(logf(m_scale)/logf(1.5f) + 0.5f);
m_zoom_x = view[2] * 0.5f;
m_zoom_y = view[3] * 0.5f;
m_image_x = m_image_width * 0.5f;
m_image_y = m_image_height * 0.5f;
m_tx = 0;
m_ty = 0;
}
void OpenGLPanZoom::Update()
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(m_tx, m_ty, 0.0f);
glTranslatef(m_zoom_x, m_zoom_y, 0.0f);
glScalef(m_scale, m_scale, 1.0f);
glTranslatef(-m_image_x, -m_image_y, 0.0f);
}
void OpenGLPanZoom::GetPos(float &x, float &y)
{
GetWorldPos(m_cur_mouse_x, m_cur_mouse_y, x, y);
}
float OpenGLPanZoom::GetScale()
{
return m_scale;
}
| true |
a5b92a32a6db5cc880e5d2fa8d281e602e46587b | C++ | DionysiosB/CodeChef | /PRB01.cpp | UTF-8 | 289 | 3.28125 | 3 | [] | no_license | #include <cstdio>
bool isPrime(long x){
for(long p = 2; p * p <= x; p++){if(x % p == 0){return false;}}
return true;
}
int main(){
int T; scanf("%d\n", &T);
while(T--){
long n; scanf("%ld\n", &n);
puts(isPrime(n) ? "yes" : "no");
}
return 0;
}
| true |
924f2865eb8a6182719277dbab77349db8771ee4 | C++ | CaseyYang/Academics | /WordSegmentationByHMM_1/HMM2.cpp | GB18030 | 6,111 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<stack>
#include<sys/stat.h>
#include<gdbm.h>
#include<cstdlib>
using namespace std;
const string DB_FILE_BLOCK = "dict_db";
GDBM_FILE dbm_ptr;
const int SNUM = 4; //״̬ϴС
const int ONUM = 4782; //۲ֵϴС
/*HMMģͲ*/
double PI[SNUM];
double A1[SNUM][SNUM];
double A2[SNUM][SNUM][SNUM];
double B1[SNUM][ONUM];
double B2[SNUM][SNUM][ONUM];
inline int stateIndex(char state)
{
switch (state) {
case 'B':
return 0;
break;
case 'M':
return 1;
break;
case 'E':
return 2;
break;
case 'S':
return 3;
break;
default:
return -1;
break;
}
}
inline int observIndex(string chinese)
{
//cout << chinese << endl;
datum key, value;
key.dptr = const_cast < char *>(chinese.c_str());
key.dsize = 3;
value = gdbm_fetch(dbm_ptr, key);
int index = atoi(value.dptr);
return index;
}
/*ļжHMMģͲ*/
void initHMM(string f1, string f2, string f3, string f4, string f5){
ifstream ifs1(f1.c_str());
ifstream ifs2(f2.c_str());
ifstream ifs3(f3.c_str());
ifstream ifs4(f4.c_str());
ifstream ifs5(f5.c_str());
if (!(ifs1 && ifs2 && ifs3 && ifs4 && ifs5)){
cerr << "Open file failed!" << endl;
exit(1);
}
//ȡPI
string line;
if (getline(ifs1, line)){
istringstream strstm(line);
string word;
for (int i = 0; i<SNUM; ++i){
strstm >> word;
PI[i] = atof(word.c_str());
}
}
else{
cerr << "Read PI failed!" << endl;
exit(1);
}
//ȡA1
for (int i = 0; i<SNUM; ++i){
getline(ifs2, line);
istringstream strstm(line);
string word;
for (int j = 0; j<SNUM; ++j){
strstm >> word;
A1[i][j] = atof(word.c_str());
}
}
//ȡA2
for (int i = 0; i<SNUM; ++i){
for (int j = 0; j<SNUM; ++j){
getline(ifs3, line);
istringstream strstm(line);
string word;
for (int k = 0; k<SNUM; ++k){
strstm >> word;
A2[i][j][k] = atof(word.c_str());
}
}
}
//ȡB1
for (int i = 0; i<SNUM; ++i){
getline(ifs4, line);
istringstream strstm(line);
string word;
for (int j = 0; j<ONUM; ++j){
strstm >> word;
B1[i][j] = atof(word.c_str());
}
}
//ȡB2
for (int i = 0; i<SNUM; ++i){
for (int j = 0; j<SNUM; ++j){
getline(ifs5, line);
istringstream strstm(line);
string word;
for (int k = 0; k<ONUM; ++k){
strstm >> word;
B2[i][j][k] = atof(word.c_str());
}
}
}
ifs1.close();
ifs2.close();
ifs3.close();
ifs4.close();
ifs5.close();
}
/*Viterbi㷨зִ*/
void viterbi(string sentence, string &result){
if (sentence.size() == 0)
return;
result.clear();
int time = sentence.size() / 3; //۲еij
if (time<3){ //۲ֻ1ֻ2֣Ϊ1
result = sentence.append(" ");
return;
}
double ***Q = new double **[SNUM]; //̬벢ʼQPath
int ***Path = new int**[SNUM];
for (int i = 0; i<SNUM; ++i){
Q[i] = new double *[SNUM];
Path[i] = new int *[SNUM];
for (int j = 0; j<SNUM; ++j){
Q[i][j] = new double[ONUM];
Path[i][j] = new int[ONUM];
for (int k = 0; k<ONUM; ++k){
Q[i][j][k] = 0.0;
Path[i][j][k] = 0;
}
}
}
//QPathĵ1渳ֵ
string chinese1 = sentence.substr(0, 3);
int o1 = observIndex(chinese1);
string chinese2 = sentence.substr(3, 3);
int o2 = observIndex(chinese2);
for (int i = 0; i<SNUM; ++i){
for (int j = 0; j<SNUM; ++j){
Q[i][j][0] = PI[i] * A1[i][j] * B1[i][o1] * B2[i][j][o2];
Path[i][j][0] = -1;
}
}
//QPathĺ渳ֵ
for (int t = 1; t<time - 1; ++t){
string chinese = sentence.substr(3 * (t + 1), 3);
int ot = observIndex(chinese);
for (int j = 0; j<SNUM; ++j){
for (int k = 0; k<SNUM; ++k){
double max = -1.0;
int maxindex = -1;
for (int i = 0; i<SNUM; ++i){
double product = Q[i][j][t - 1] * A2[i][j][k];
if (product>max){
max = product;
maxindex = i;
}
}
Q[j][k][t] = max*B2[j][k][ot];
Path[j][k][t] = maxindex;
}
}
}
//Qһֵ
double max = -1.0;
int maxindexi = -1;
int maxindexj = -1;
for (int i = 0; i<SNUM; ++i){
for (int j = 0; j<SNUM; ++j){
if (Q[i][j][time - 2]>max){
max = Q[i][j][time - 2];
maxindexi = i;
maxindexj = j;
}
}
}
//maxindexj,maxindexiPathҳܵ״̬
stack<int> st;
st.push(maxindexj);
st.push(maxindexi);
for (int t = time - 3; t >= 0; --t){
int maxindexk = Path[maxindexi][maxindexj][t + 1];
st.push(maxindexk);
maxindexj = maxindexi;
maxindexi = maxindexk;
}
//ͷά
for (int i = 0; i<SNUM; ++i){
for (int j = 0; j<SNUM; ++j){
delete[]Q[i][j];
delete[]Path[i][j];
}
delete[]Q[i];
delete[]Path[i];
}
delete[]Q;
delete[]Path;
//ݱǺõ״̬зִ
int pos = 0;
//cout<<sentence<<endl;
while (!st.empty()){
int mark = st.top();
st.pop();
result.insert(result.size(), sentence, pos, 3);
if (mark == 2 || mark == 3){ //״̬ES
result.append(" ");
}
pos += 3;
}
result.append("\t");
}
int main(int argc, char *argv[]){
if (argc<3){
cout << "Usage: " << argv[0] << " inputfile outputfile" << endl;
return 1;
}
dbm_ptr = gdbm_open(DB_FILE_BLOCK.c_str(), 0, GDBM_READER, S_IRUSR | S_IWUSR, NULL);
initHMM("PI.mat", "A1.mat", "A2.mat", "B1.mat", "B2.mat");
ifstream ifs(argv[1]);
ofstream ofs(argv[2]);
if (!(ifs&&ofs)){
cerr << "Open file failed!" << endl;
return 1;
}
string line, line_out;
int lineno = 0;
//ѭȡÿһ
while (getline(ifs, line)){
lineno++;
//cout<<"line="<<line<<endl;
line_out.clear();
istringstream strstm(line);
string sentence;
string result;
while (strstm >> sentence){
//if(sentence.size()<6){
// cout<<lineno<<": "<<sentence<<endl;
// continue;
//}
//cout<<"sentence="<<sentence<<endl;
viterbi(sentence, result);
line_out += result;
}
ofs << line_out << endl;
}
ifs.close();
ofs.close();
gdbm_close(dbm_ptr);
return 0;
} | true |
9cd8f664bee154bc2acf9c69b2db40d2c952f828 | C++ | germanohn/competitive-programming | /uri/1237-comparaSubstr.cpp | UTF-8 | 1,359 | 2.71875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int me[55][55];
char s1[55], s2[55];
//recursivo
/*int dp (int a, int b) {
if (a < 0 || b < 0) return 0;
if (me[a][b] != -1) return me[a][b];
if (s1[a] == s2[b])
return me[a][b] = 1 + dp (a - 1, b - 1);
dp (a - 1, b), dp (a, b - 1);
return me[a][b] = 0;
}
int main () {
while (scanf (" %[^\n]", s1) != EOF) {
memset (me, -1, sizeof me);
scanf (" %[^\n]", s2);
int n, m;
n = strlen (s1);
m = strlen (s2);
dp (n-1, m-1);
int ma = INT_MIN;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ma = max (ma, dp (i, j));
}
}
printf ("%d\n", ma);
}
}*/
//iterativo
int main () {
while (scanf (" %[^\n]", s1) != EOF) {
scanf (" %[^\n]", s2);
memset (me, -1, sizeof me);
int n, m, ma = INT_MIN;
n = strlen (s1), m = strlen (s2);
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (s1[i] == s2[j]) {
if (i == 0 || j == 0) me[i][j] = 1;
else me[i][j] = 1 + me[i-1][j-1];
} else
me[i][j] = 0;
ma = max (ma, me[i][j]);
}
}
printf ("%d\n", ma);
}
}
| true |
fc2de801a6f9cddd0a5ab6cc779a9cf77cb353f7 | C++ | iserramacsa/mcomms | /printers/jet/src/jetio.cpp | UTF-8 | 578 | 2.671875 | 3 | [] | no_license | #include "jet/jetio.h"
using namespace Macsa::Printers;
JetIO::JetIO(const std::string &id) :
_id(id)
{
_value = false;
}
JetIO::JetIO(const JetIO &other) :
_id(other._id)
{
_value = other._value;
}
std::string JetIO::id() const
{
return _id;
}
bool JetIO::value() const
{
return _value;
}
void JetIO::setValue(bool value)
{
_value = value;
}
JetIO &JetIO::operator = (const JetIO &other)
{
if (_id == other._id) {
_value = other._value;
}
return *this;
}
bool JetIO::equal(const JetIO &other) const
{
return (_id == other._id && _value == other._value);
}
| true |
5d6149dae9520f6d53d1e4e665172c98b2ee9fb6 | C++ | DeftHaHa/ACM | /牛客网/2019寒假训练赛1/G.cpp | UTF-8 | 1,022 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
int a[100005],pos[100005];
int main()
{
int N,x,y;
scanf("%d%d%d",&N,&x,&y);
int l,r,mx,mi;
for(int i = 1;i <= N;i++){
scanf("%d",&a[i]);
pos[a[i]] = i;
}
l = pos[x],r = pos[y];
if(l>r) swap(l,r);
int nl = l,nr = r;
mx = mi = x;
for(int i = l;i <= r;i++){
mx = max(a[i],mx);
mi = min(a[i],mi);
}
for(int i = mi;i <= mx;i++){
nl = min(pos[i],nl);
nr = max(pos[i],nr);
}
while(nr - nl != mx - mi){
//printf("%d( %d %d )%d %d-%d\n",nl,l,r,nr,mi,mx);
int tmi = mi,tmx = mx;
for(int i = nl;i < l;i++){
mx = max(a[i],mx);
mi = min(a[i],mi);
}
for(int i = r+1;i <=nr;i++){
mx = max(a[i],mx);
mi = min(a[i],mi);
}
l = nl,r = nr;
for(int i = mi;i < tmi;i++){
nl = min(pos[i],nl);
nr = max(pos[i],nr);
}
for(int i = tmx+1;i <= mx;i++){
nl = min(pos[i],nl);
nr = max(pos[i],nr);
}
}
cout<<nl<<' '<<nr<<endl;
return 0;
}
/*
5 2 3
2 5 1 3 4
*/
| true |
6f08f3157031d0bd8eec8f13aa77f2464e5b27ca | C++ | G-GFFD/Cendric2 | /src/GUI/ModifierSlot.cpp | UTF-8 | 4,634 | 2.640625 | 3 | [] | no_license | #include "GUI/ModifierSlot.h"
using namespace std;
const float ModifierSlot::SIDE_LENGTH = 50.f;
const float ModifierSlot::MARGIN = 2.f;
ModifierSlot::ModifierSlot(const SpellModifier& modifier)
{
m_spellModifier = modifier;
setBoundingBox(sf::FloatRect(0.f, 0.f, SIDE_LENGTH, SIDE_LENGTH));
setDebugBoundingBox(sf::Color::Red);
setInputInDefaultView(true);
m_inside.setSize(sf::Vector2f(SIDE_LENGTH, SIDE_LENGTH));
m_inside.setTexture(g_resourceManager->getTexture(ResourceID::Texture_gems));
m_inside.setTextureRect(sf::IntRect((modifier.level - 1) * 50, static_cast<int>(modifier.type) * 50, 50, 50));
m_outside.setSize(sf::Vector2f(SIDE_LENGTH, SIDE_LENGTH));
m_outside.setFillColor(CENDRIC_COLOR_TRANS_GREY);
m_outside.setOutlineThickness(MARGIN);
m_outside.setOutlineColor(CENDRIC_COLOR_PURPLE);
}
ModifierSlot::ModifierSlot()
{
m_spellModifier.type = SpellModifierType::VOID;
m_spellModifier.level = 1;
setBoundingBox(sf::FloatRect(0.f, 0.f, SIDE_LENGTH, SIDE_LENGTH));
setDebugBoundingBox(sf::Color::Red);
setInputInDefaultView(true);
m_inside.setSize(sf::Vector2f(SIDE_LENGTH, SIDE_LENGTH));
m_inside.setTexture(g_resourceManager->getTexture(ResourceID::Texture_gems));
m_inside.setTextureRect(sf::IntRect((m_spellModifier.level - 1) * 50, static_cast<int>(m_spellModifier.type) * 50, 50, 50));
m_outside.setSize(sf::Vector2f(SIDE_LENGTH, SIDE_LENGTH));
m_outside.setFillColor(CENDRIC_COLOR_TRANS_GREY);
m_outside.setOutlineThickness(MARGIN);
m_outside.setOutlineColor(CENDRIC_COLOR_DARK_GREY);
}
ModifierSlot::~ModifierSlot()
{
delete m_descriptionWindow;
}
void ModifierSlot::activate()
{
m_outside.setOutlineColor(sf::Color::Red);
m_outside.setFillColor(CENDRIC_COLOR_TRANS_GREY);
m_inside.setFillColor(sf::Color::White);
}
void ModifierSlot::deactivate()
{
m_outside.setOutlineColor(CENDRIC_COLOR_BLACK);
m_outside.setFillColor(CENDRIC_COLOR_TRANS_BLACK);
m_inside.setFillColor(sf::Color(150, 150, 150));
}
void ModifierSlot::highlight(bool highlight)
{
if (highlight)
{
m_outside.setOutlineColor(sf::Color::Green);
}
else
{
m_outside.setOutlineColor(m_isSelected ?
sf::Color::Red :
(m_spellModifier.type == SpellModifierType::VOID) ?
CENDRIC_COLOR_DARK_GREY :
CENDRIC_COLOR_PURPLE);
}
}
void ModifierSlot::select()
{
if (m_isSelected || m_spellModifier.type == SpellModifierType::VOID) return;
m_isSelected = true;
m_outside.setOutlineColor(sf::Color::Red);
}
void ModifierSlot::deselect()
{
if (!m_isSelected || m_spellModifier.type == SpellModifierType::VOID) return;
m_isSelected = false;
m_outside.setOutlineColor(CENDRIC_COLOR_DARK_PURPLE);
}
bool ModifierSlot::isClicked()
{
return m_isClicked;
}
bool ModifierSlot::isRightClicked()
{
return m_isRightClicked;
}
void ModifierSlot::setPosition(const sf::Vector2f& pos)
{
GameObject::setPosition(pos);
m_inside.setPosition(pos);
m_outside.setPosition(pos);
if (m_descriptionWindow != nullptr)
{
sf::Vector2f pos(getBoundingBox()->left, getBoundingBox()->top - m_descriptionWindow->getSize().y - 10.f);
m_descriptionWindow->setPosition(pos);
}
}
void ModifierSlot::render(sf::RenderTarget& renderTarget)
{
renderTarget.draw(m_outside);
renderTarget.draw(m_inside);
}
void ModifierSlot::update(const sf::Time& frameTime)
{
m_isClicked = false;
m_isRightClicked = false;
GameObject::update(frameTime);
}
void ModifierSlot::renderAfterForeground(sf::RenderTarget& target)
{
GameObject::renderAfterForeground(target);
if (m_showDescriptionWindow && m_descriptionWindow != nullptr)
{
m_descriptionWindow->render(target);
m_showDescriptionWindow = false;
}
}
void ModifierSlot::onLeftJustPressed()
{
if (m_spellModifier.type == SpellModifierType::VOID) return;
m_isClicked = true;
g_inputController->lockAction();
}
void ModifierSlot::onRightClick()
{
if (m_spellModifier.type == SpellModifierType::VOID) return;
m_isRightClicked = true;
g_inputController->lockAction();
}
void ModifierSlot::onMouseOver()
{
if (m_spellModifier.type == SpellModifierType::VOID) return;
if (m_descriptionWindow == nullptr)
{
m_descriptionWindow = new ModifierDescriptionWindow(m_spellModifier);
sf::Vector2f pos(getBoundingBox()->left, getBoundingBox()->top - m_descriptionWindow->getSize().y - 10.f);
m_descriptionWindow->setPosition(pos);
}
m_showDescriptionWindow = true;
}
GameObjectType ModifierSlot::getConfiguredType() const
{
return GameObjectType::_Interface;
}
const SpellModifier& ModifierSlot::getModifier() const
{
return m_spellModifier;
}
int ModifierSlot::getNr() const
{
return m_nr;
}
void ModifierSlot::setNr(int nr)
{
m_nr = nr;
} | true |
2f601dfa0fff6ba180b8372421c30858045fde65 | C++ | math715/cpp | /fp.cc | UTF-8 | 11,343 | 3.296875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <tuple>
#include <utility>
#include <string>
#include <vector>
#include <sstream>
template <typename T>
void print( T t) {
std::cout << t << std::endl;
}
class tfn_print{
public:
template <typename... Args>
auto operator()(Args&& ... args) const -> decltype( print(std::forward<Args>(args)...)) {
return print(std::forward<Args>(args)...);
}
};
// class universal_functor {
// public :
// template <typename ... Args>
// auto operator()(Args&&... args) const -> decltype ( global_func(std::forward<Args>(args)...)) {
// return global_func(std::forward<Args>(args)...);
// }
// }
// #define make_citizen(X) class tfn_##X { public: template <typename... Args> auto operator()(Args&&... args) const ->decltype(X(std::forward<Args>(args)...)) { return X(std::forward<Args>(args)...); } }
#define define_functor_type(func_name) class tfn_##func_name {\
public: template <typename ... Args> auto operator()(Args&&... args) const -> decltype(func_name(std::forward<Args>(args)...)) {\
return func_name(std::forward<Args>(args)...); }};
template<typename F, size_t ... I , typename ... Args>
inline auto tuple_apply_impl(const F & f, const std::index_sequence<I...> &, const std::tuple<Args...> &tp) {
return f (std::get<I>(tp) ...);
}
template<typename F, typename ... Args>
inline auto tuple_apply(const F& f, const std::tuple<Args...> &tp) -> decltype(f(std::declval<Args>() ...)) {
return tuple_apply_impl(f, std::make_index_sequence<sizeof ... (Args)>{}, tp );
}
template <typename T, class F >
auto operator| ( T && param, const F & f) -> decltype(f(std::forward<T>(param) )) {
return f(std::forward<T>(param));
}
int add(int a, int b) {
return a + b;
}
int add_one(int a) {
return 1 + a;
}
template <typename F, typename Before = std::tuple<> , typename After = std::tuple<>>
class curry_functor {
private:
F f_;
Before before_;
After after_;
public:
curry_functor(F && f) : f_(std::forward<F>(f)), before_(std::tuple<>()), after_(std::tuple<>()) {}
curry_functor(const F &f, const Before &before, const After &after): f_(f), before_(before), after_(after) {}
template <typename ... Args>
auto operator()(Args ... args) const -> decltype(tuple_apply(f_, std::tuple_cat(before_, std::make_tuple(args...), after_))) {
return tuple_apply(f_, std::tuple_cat(before_, std::make_tuple(std::forward<Args>(args)...), after_));
}
template <typename T>
auto curry_before( T && param) const {
using RealBefore = decltype( std::tuple_cat(before_, std::make_tuple(param)));
return curry_functor<F, RealBefore, After>(f_, std::tuple_cat(before_, std::make_tuple(std::forward<T>(param))), after_);
}
template<typename T>
auto curry_after( T && param) const {
using RealAfter = decltype ( std::tuple_cat(after_, std::make_tuple(param)));
return curry_functor<F, Before, RealAfter>(f_, before_, std::tuple_cat(after_, std::make_tuple(std::forward<T>(param))));
}
};
// template<typename F, typename Before = std::tuple<>, typename After = std::tuple<>>
// class curry_functor {
// private:
// F f_; ///< main functor
// Before before_; ///< curryed arguments
// After after_; ///< curryed arguments
// public:
// curry_functor(F && f) : f_(std::forward<F>(f)), before_(std::tuple<>()), after_(std::tuple<>()) {}
// curry_functor(const F & f, const Before & before, const After & after) : f_(f), before_(before), after_(after) {}
// template <typename... Args>
// auto operator()(Args... args) const -> decltype(tuple_apply(f_, std::tuple_cat(before_, make_tuple(args...), after_)))
// {
// // execute via tuple
// return tuple_apply(f_, std::tuple_cat(before_, make_tuple(std::forward<Args>(args)...), after_));
// }
// // curry
// template <typename T>
// auto curry_before(T && param) const
// {
// using RealBefore = decltype(std::tuple_cat(before_, std::make_tuple(param)));
// return curry_functor<F, RealBefore, After>(f_, std::tuple_cat(before_, std::make_tuple(std::forward<T>(param))), after_);
// }
// template <typename T>
// auto curry_after(T && param) const
// {
// using RealAfter = decltype(std::tuple_cat(after_, std::make_tuple(param)));
// return curry_functor<F, Before, RealAfter>(f_, before_, std::tuple_cat(after_, std::make_tuple(std::forward<T>(param))));
// }
// };
template <typename F>
auto fn_to_curry_functor(F && f) {
return curry_functor<F>(std::forward<F>(f));
}
template<typename UF, typename Arg>
auto operator<<( const UF &f, Arg && arg) -> decltype (f.template curry_before<Arg>(std::forward<Arg>(arg))) {
return f.template curry_before<Arg>(std::forward<Arg>(arg));
}
template<typename UF, typename Arg>
auto operator>>( const UF &f, Arg && arg) -> decltype(f.template curry_after<Arg>(std::forward<Arg>(arg))) {
return f.template curry_after<Arg>(std::forward<Arg>(arg));
}
template <typename ... FNs>
class fn_chain {
private:
const std::tuple<FNs ...> functions_;
const static size_t TUPLE_SIZE = sizeof ... (FNs);
template<typename Arg, std::size_t I>
auto call_impl(Arg&& arg, const std::index_sequence<I> &) const -> decltype ( std::get<I>(functions_)(std::forward<Arg>(arg))) {
return std::get<I>(functions_)(std::forward<Arg>(arg));
}
template<typename Arg, std::size_t I, std::size_t ...Is >
auto call_impl(Arg&& arg, const std::index_sequence<I, Is...> &) const -> decltype(call_impl(std::get<I>(functions_)(std::forward<Arg>(arg)), std::index_sequence<Is...>{})) {
return call_impl(std::get<I>(functions_)(std::forward<Arg>(arg)), std::index_sequence<Is...>{});
}
template <typename Arg>
auto call(Arg && arg) const ->decltype(call_impl(std::forward<Arg>(arg), std::make_index_sequence<sizeof ... (FNs)>{})) {
return call_impl(std::forward<Arg>(arg), std::make_index_sequence<sizeof ... (FNs)>{});
}
public:
fn_chain() : functions_(std::tuple<>()) {}
fn_chain(std::tuple<FNs...> functions) : functions_(functions){}
template< typename F>
inline auto add (const F & f) const {
return fn_chain<FNs..., F> (std::tuple_cat(functions_, std::make_tuple(f)));
}
template< typename Arg>
inline auto operator() ( Arg && arg)const -> decltype(call(std::forward<Arg>(arg))) {
return call (std::forward<Arg>(arg));
}
};
template <typename... FNs, typename F>
inline auto operator|(fn_chain<FNs...> && chain, F &&f ) {
return chain.add(std::forward<F>(f));
}
template <typename T, typename ... TArgs, template <typename...> class C, typename F>
auto fn_map( const C<T,TArgs...> & container, const F &f) -> C<decltype(f(std::declval<T>()))> {
using resultType = decltype( f (std::declval<T>()));
C<resultType> result;
for (const auto & item : container) {
result.push_back(f(item));
}
return result;
}
template <typename TResult, typename T, typename ... TArgs, template <typename...> class C, typename F>
TResult fn_reduce( const C<T, TArgs...> & container, const TResult &startValue, const F &f) {
TResult result = startValue;
for (const auto &item : container) {
result = f (result, item);
}
return result;
}
// template <typename TResult, typename T, typename... TArgs, template <typename...>class C, typename F>
// TResult fn_reduce(const C<T, TArgs...>& container, const TResult& startValue, const F& f)
// {
// TResult result = startValue;
// for (const auto& item : container)
// result = f(result, item);
// return result;
// }
template <typename T, typename ... TArgs, template < typename ...> class C, typename F>
C<T, TArgs...> fn_filter(const C<T, TArgs...> &container, const F &f) {
C<T, TArgs...> result;
for (const auto &item : container) {
if (f(item)) {
result.push_back(item);
}
}
return result;
}
#define make_globle_curry_functor(NAME, F) define_functor_type(F); const auto NAME = fn_to_curry_functor(tfn_##F());
make_globle_curry_functor(map, fn_map);
make_globle_curry_functor(reduce, fn_reduce);
make_globle_curry_functor(filter, fn_filter);
// define_functor_type(add);
// define_functor_type(add_one);
// #define make_global_functor(NAME,F) const auto NAME = define_functor_type(F);
// #define make_globle_functor(NAME, F) const auto NAME = define_functor_type(F);
// make_citizen(print);
// make_globle_functor(tfn_add, add);
// make_globle_functor(fn_add_one, add_one);
// make_global_functor(fn_add, add);
// make_global_functor(fn_add_one, add_one);
void test_curry() {
auto f = [](int x, int y, int z) { return x + y - z; };
auto fn = fn_to_curry_functor(f);
auto result = fn.curry_before(1)(2, 3); //0
result = fn.curry_before(1).curry_before(2)(3); //0
print(result);
result = fn.curry_before(1).curry_before(2).curry_before(3)(); //0
print(result);
result = fn.curry_before(1).curry_after(2).curry_before(3)(); //2
print(result);
result = fn.curry_after(1).curry_after(2).curry_before(2)(); //1
print(result);
}
#define tfn_chain fn_chain<>()
void test_pipe1()
{
//test map reduce
std::vector<std::string> slist = { "one", "two", "three" };
slist | (map >> [](auto s) { return s.size(); })
| (reduce >> 0 >> [](auto a, auto b) { return a + b; })
| [](auto a) { std::cout << a << std::endl; };
//test chain, lazy eval
auto chain = tfn_chain | (map >> [](auto s) { return s.size(); })
| (reduce >> 0 >> [](auto a, auto b) { return a + b; })
| ([](int a) { std::cout << a << std::endl; });
slist | chain;
}
void test_currying()
{
auto f = [](int x, int y, int z) { return x + y - z; };
auto fn = fn_to_curry_functor(f);
auto result = (fn << 1)(2, 3); //0
result = (fn << 1 << 2)(3); //0
result = (fn << 1 << 2 << 3)(); //0
result = (fn << 1 >> 2 << 3)(); //2
result = (fn >> 1 >> 2 << 3)(); //1
}
void test_pipe(){
auto f1 = [](int x) { return x + 3; };
auto f2 = [](int x) { return x * 2; };
auto f3 = [](int x) { return (double)x / 2.0; };
auto f4 = [](double x) { std::stringstream ss; ss << x; return ss.str(); };
auto f5 = [](std::string s) { return "Result: " + s; };
auto result = 2|f1|f2|f3|f4|f5; //Result: 5
}
int main(int argc, char *argv[] ) {
test_curry();
test_pipe();
// tfn_print print;
// auto f = [](int x, int y, int z) {
// return x + y + z;
// } ;
// auto params = std::make_tuple(1, 2, 3);
// auto result = tuple_apply(f, params);
// print(result);
// auto add_one = [] (auto a){return a + 1;};
// auto result1 = 2 | add_one ;
// print(result1);
// tfn_print print;
// print(5);
// print("Hello, World");
// tfn_add add_function;
// auto result = add_function(1, 2);
// print(result);
// tfn_add_one add_one_function;
// auto result1 = add_one_function(1);
// print(result1);
// auto result = fn_add(1, 2);
// print(result);
return 0;
} | true |
9c539fa145a7f2acd7a0d8fe1fbb76813f376bea | C++ | AyiStar/CppPrimer | /Chapter10/EXC10_14.cpp | UTF-8 | 234 | 3 | 3 | [] | no_license | //
// Created by ayistar on 2/20/17.
//
#include <iostream>
int add_9 (int x)
{
auto sum = [x] (int i) { return x + i; };
int z = sum(9);
return z;
}
int main()
{
std::cout << add_9(18) << std::endl;
return 0;
} | true |
5c140800cac8e74d672a9430a5a8aad95ea28c73 | C++ | chigichan24/kyogi2015 | /main/GA/ga-max.cpp | UTF-8 | 3,216 | 2.71875 | 3 | [] | no_license | #include "bits/stdc++.h"
struct GAData{
int score,time;
double f_pass,f_cir,f_hole;
double m_pass,m_cir,m_hole;
GAData(){}
GAData(int score,int time,double f_pass,double f_cir,double f_hole,double m_pass,double m_cir,double m_hole){
this->score = score;
this->time = time;
this->f_pass = f_pass;
this->f_cir = f_cir;
this->f_hole = f_hole;
this->m_pass = m_pass;
this->m_cir = m_cir;
this->m_hole = m_hole;
}
bool operator<(const GAData &data)const{
if(score == data.score)return time<data.time;
return score < data.score;
}
};
GAData data[32];
GAData next[32];
int N;
int bestscore;
int besttime;
void init(){
/*
pass : 5 < x < 300 , 1刻み
cir : -4 < x < 4 , 0.1刻み
hole : 0 < x < 20 , 0.1刻み
*/
for(int i = 0; i < N; ++i){
int a = rand()%295+5;
int b = rand()%80-40;
int c = rand()%200;
int d = rand()%295+5;
int e = rand()%80-40;
int f = rand()%200;
data[i] = GAData(0,0,(double)a,(double)b/10.0,(double)c/10.0,(double)d,(double)d/10.0,(double)f/10.0);
}
bestscore = 1e9;
besttime = 1e9;
return ;
}
void copy(){
for(int i = 0; i < N; ++i){
data[i] = next[i];
}
return ;
}
int main(){
N = 30;
char problemFile[128];
scanf("%s",problemFile);
srand(time(NULL));
init();
int cnt = 0;
while(true){
for(int i = 0; i < N; ++i){
char target[256];
sprintf(target,"Main.exe -GA %lf %lf %lf %lf %lf %lf -answer < %s > out.txt",data[i].f_pass,data[i].f_cir,data[i].f_hole,
data[i].m_pass,data[i].m_cir,data[i].m_hole,problemFile);
system(target);
FILE *fp;
fp = fopen("./out.txt","r");
int score,time;
fscanf(fp,"%d %d",&score,&time);
data[i].score = score;
data[i].time = time;
fclose(fp);
printf("%d %d\n",score,time);
if(bestscore > score || (bestscore == score && besttime > time)){
bestscore = score;
besttime = time;
char answerfile[256];
sprintf(answerfile,"cp ./out.txt ./result/answer%d.txt",cnt);
system(answerfile);
++cnt;
}
}
std::sort(data,data+N);
int nextIdx = 0;
for(int i = 0; i < 3; ++i){
next[nextIdx] = data[i];
nextIdx++;
}
double p[32];
std::vector<int> roulette;
for(int i = 0; i < N; ++i){
for(int j = 0; j < 1024 - data[i].score; ++j){
roulette.push_back(i);
}
}
random_shuffle(roulette.begin(),roulette.end());
for(int i = 0; i < 30; i+=2){
GAData a = data[roulette[i]];
GAData b = data[roulette[i+1]];
if(rand()%2)std::swap(a.f_pass,b.f_pass);
if(rand()%2)std::swap(a.f_cir,b.f_cir);
if(rand()%2)std::swap(a.f_hole,b.f_hole);
if(rand()%2)std::swap(a.m_pass,b.m_pass);
if(rand()%2)std::swap(a.m_cir,b.m_cir);
if(rand()%2)std::swap(a.m_hole,b.m_hole);
next[nextIdx] = a;
nextIdx++;
}
for(int i = 0; i < 5; ++i){
random_shuffle(roulette.begin(),roulette.end());
GAData a;
int tmp = 0;
a.f_pass = data[roulette[tmp]].f_pass; ++tmp;
a.f_cir = data[roulette[tmp]].f_cir; ++tmp;
a.f_hole = data[roulette[tmp]].f_hole; ++tmp;
a.m_pass = data[roulette[tmp]].m_pass; ++tmp;
a.m_cir = data[roulette[tmp]].m_cir; ++tmp;
a.m_hole = data[roulette[tmp]].m_hole; ++tmp;
next[nextIdx] = a;
nextIdx++;
}
copy();
}
} | true |
9a5cc059a5b8b7d87de12d34633182d87548ab21 | C++ | dalalsunil1986/OnlineJudge-Solution | /UVa Online Judge/uva 488.cpp | UTF-8 | 439 | 2.953125 | 3 | [] | no_license | #include<iostream>
using namespace std;
char *arr[] = {"", "1", "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"};
int main()
{
int tc,a,f,i,j;
cin>>tc;
while(tc--){
cin>>a>>f;
while(f--){
for(i = 1; i<a; i++)
cout<<arr[i]<<endl;
for(j =i; j; j--)
cout<<arr[j]<<endl;
if(f || tc)
cout<<endl;
}
}
return 0;
}
| true |
1b1a9cbef1155c8a32f986b6bd2cb40cc39ed4be | C++ | chtld/Programming-and-Algorithm-Course | /cplusplus/MyString2.cpp | UTF-8 | 3,749 | 3.21875 | 3 | [
"MIT"
] | permissive | #include <cstdlib>
#include <iostream>
using namespace std;
int strlen(const char * s)
{ int i = 0;
for(; s[i]; ++i);
return i;
}
void strcpy(char * d,const char * s)
{
int i = 0;
for( i = 0; s[i]; ++i)
d[i] = s[i];
d[i] = 0;
}
int strcmp(const char * s1,const char * s2)
{
for(int i = 0; s1[i] && s2[i] ; ++i) {
if( s1[i] < s2[i] )
return -1;
else if( s1[i] > s2[i])
return 1;
}
return 0;
}
void strcat(char * d,const char * s)
{
int len = strlen(d);
strcpy(d+len,s);
}
class MyString
{
// 在此处补充你的代码
char *p;
public:
MyString(const char *s) {
if(s == NULL) p = NULL;
else {
p = new char[strlen(s) + 1];
strcpy(p, s);
}
}
MyString(const MyString & temp){
if (temp.p == NULL) p = NULL;
else {
p = new char[strlen(temp.p) + 1];
strcpy(p, temp.p);
}
}
MyString(){p = NULL;};
~MyString(){if(p) delete []p;};
friend ostream & operator << (ostream & os, const MyString & temp){
if(temp.p) os << temp.p;
return os;
}
MyString & operator=(const MyString & temp){
if (p == temp.p) return *this;
if (temp.p == NULL) p = NULL;
else {
if(p) delete []p;
p = new char[strlen(temp.p) + 1];
strcpy(p, temp.p);
}
return *this;
}
MyString operator+(const MyString & temp){
char *s;
s = new char[strlen(p) + strlen(temp.p) + 1];
s[0] = '\0';
strcat(s, p);
strcat(s + strlen(p), temp.p);
MyString ret(s);
return ret;
}
char & operator[](int i){
return p[i];
}
MyString & operator=(const char *s){
if (p == s) return *this;
if (p) delete []p;
if(s == NULL) {
p = NULL;
} else {
p = new char[strlen(s) + 1];
strcpy(p, s);
}
return *this;
}
MyString & operator+=(const MyString &temp){
(*this) = (*this) + temp;
return *this;
}
MyString operator+(const char *s){
MyString temp2(s);
return (*this + temp2);
}
friend MyString operator+(const char *s, const MyString &temp2){
MyString temp1(s);
return (temp1 + temp2);
}
MyString operator()(int i, int j){
char *s = new char[j + 1];
for (int k = 0; k < j; k++) {
s[k] = p[k + i];
}
s[j] = '\0';
return MyString(s);
}
bool operator<(const MyString &temp2){
int flag = strcmp(p, temp2.p);
if(flag < 0) return true;
else return false;
}
bool operator>(const MyString &temp2){
int flag = strcmp(p, temp2.p);
if(flag > 0) return true;
else return false;
}
bool operator==(const MyString &temp2){
int flag = strcmp(p, temp2.p);
if(flag == 0) return true;
else return false;
}
};
int CompareString( const void * e1, const void * e2)
{
MyString * s1 = (MyString * ) e1;
MyString * s2 = (MyString * ) e2;
if( * s1 < *s2 )
return -1;
else if( *s1 == *s2)
return 0;
else if( *s1 > *s2 )
return 1;
}
int main()
{
MyString s1("abcd-"),s2,s3("efgh-"),s4(s1);
MyString SArray[4] = {"big","me","about","take"};
cout << "1. " << s1 << s2 << s3<< s4<< endl;
s4 = s3;
s3 = s1 + s3;
cout << "2. " << s1 << endl;
cout << "3. " << s2 << endl;
cout << "4. " << s3 << endl;
cout << "5. " << s4 << endl;
cout << "6. " << s1[2] << endl;
s2 = s1;
s1 = "ijkl-";
s1[2] = 'A' ;
cout << "7. " << s2 << endl;
cout << "8. " << s1 << endl;
s1 += "mnop";
cout << "9. " << s1 << endl;
s4 = "qrst-" + s2;
cout << "10. " << s4 << endl;
s1 = s2 + s4 + " uvw " + "xyz";
cout << "11. " << s1 << endl;
qsort(SArray,4,sizeof(MyString),CompareString);
for( int i = 0;i < 4;i ++ )
cout << SArray[i] << endl;
//s1的从下标0开始长度为4的子串
cout << s1(0,4) << endl;
//s1的从下标5开始长度为10的子串
cout << s1(5,10) << endl;
return 0;
} | true |
016ea95f9aab9f25a94e7cd568d0225025665f2d | C++ | sunil-sopho/Cop290 | /code/include/node.h | UTF-8 | 1,425 | 3.78125 | 4 | [] | no_license | #ifndef NODE_H
#define NODE_H
#include "point.h"
/* Wrapper class to store basic shapes (i.e., point,line,triangle and quadrilateral)*/
class node {
int code; /*! Represents if the shape is point,line,triangle or quadrilateral*/
point p1; /*! First point*/
point p2; /*! Second point*/
point p3; /*! Third point*/
point p4; /*! Fourth point*/
public:
node(){
}
/*! Constructor to create a shape of given type*/
node(int val){
this->code = val;
}
/*! Return the type of shape*/
int getCode(){
return this->code;
}
/*! Returns the asked point of the shape*/
point getP(int val){
if(val == 1)
return this->p1;
else if(val == 2)
return this->p2;
else if(val == 3)
return this->p3;
else if(val == 4)
return this->p4;
}
/*! Sets a point of the shape*/
void setP(int val,float x, float y , float z)
{
if(val == 1)
{
// if(p1 == NULL)
// {
// p1 = new point();
// }
p1.setC(x,y,z);
}
if(val == 2)
{
// if(p2 == NULL)
// {
// p2 = new point();
// }
p2.setC(x,y,z);
}
if(val == 3)
{
// if(p3 == NULL)
// {
// p3 = new point();
// }
p3.setC(x,y,z);
}
if(val == 4)
{
// if(p4 == NULL)
// {
// p4 = new point();
// }
p4.setC(x,y,z);
}
}
/*! Function to set the type of shape*/
void setCode(int val)
{
this->code = val;
}
};
#endif | true |
2ace985fba37edea9f9ace82592723d062e600fc | C++ | BeatrizHanae/OOEP1-Jogo-da-Vida | /src/main.cpp | UTF-8 | 1,788 | 2.90625 | 3 | [] | no_license | //Aluna: Beatriz Hanae Fujimoto (160113814)
#include <iostream>
#include "glider.hpp"
#include "campo.hpp"
#include "block.hpp"
#include "blinker.hpp"
#include "gosper.hpp"
#include <unistd.h>
#include <stdlib.h>
int main (int argc, char ** argv){
int i, j, numero;
int celulas;
int geracao = 0;
Campo vida;
Campo memoriag;
Blinker blinker;
Block block;
Glider glider;
Gosper gosper;
cout << "\n";
cout << "Escolha um número para abrir um jogo: " << endl;
cout << "Digite 1 para Blinker" << endl;
cout << "Digite 2 para Block" << endl;
cout << "Digite 3 para Glider" << endl;
cout << "Digite 4 para Gosper Glider Gun" << endl;
cin >> numero;
if (numero == 1){
vida = blinker;
} else if (numero == 2){
vida = block;
} else if (numero == 3){
vida = glider;
} else if (numero == 4){
vida = gosper;
}
memoriag = vida;
while (geracao < vida.getGeracao()) {
geracao++;
system ("clear");
for (i=0;i<35;i++){
for (j=0;j<45;j++){
cout << vida.getCampo (i,j) << " ";
if (i!=34 && i!=0 && j!=44 && j!=0){
celulas = memoriag.celulasv(memoriag,i,j);
if (vida.getCampo(i,j)=='*' && (celulas < 2 || celulas > 3)){
vida.setCampo('-', i, j);
}
if (vida.getCampo(i,j)=='-' && celulas == 3){
vida.setCampo('*', i, j);
}
if (vida.getCampo(i,j)=='*' && (celulas == 2 || celulas == 3)){
vida.setCampo('*', i, j);
}
}
}
cout << endl;
}
memoriag = vida;
std::cout << "\n";
usleep (200000);
}
return 0;
}
| true |
7c61bfe84c8e93737d6b26cac3d115facfc8457b | C++ | corrvax/DataStructure | /StackQueue/Polynomial/Polynomial.cpp | UTF-8 | 10,965 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
template <typename T> class Chain;
template <typename T>
class ChainNode
{
private:
T data;
ChainNode<T> *link;
public:
ChainNode(T element = 0, ChainNode *next = NULL) :data(element), link(next)
{
}
T getData()
{
return data;
}
ChainNode *Link()
{
return link;
}
friend class Chain<T>;
template <typename T>
friend ostream &operator<<(ostream &os, Chain<T> &c); //출력
};
template <typename T>
class Chain
{
private:
ChainNode<T> *first;
ChainNode<T> *last;
public:
Chain()
{
first = NULL;
}
ChainNode<T> *getFirst() //처음 노드 반환
{
return first;
}
ChainNode<T> *Insert(ChainNode<T> *x, T i) //노드 추가
{
if (first)
{
ChainNode<T> *temp = new ChainNode<T>(i, x->link);
x->link = temp; //x가 temp를 가르키도록
return x->link; //위치를 반환해야 그 다음 위치에 값을 대입
}
else //기존 노드가 없을 경우
{
first = new ChainNode<T>(i);
return first;
}
}
int Length()
{
int len = 0;
ChainNode *temp = first;
while (temp != NULL)
{
temp = temp->link;
len++;
}
return len;
}
void Delete(ChainNode<T> *x)
{
if (first == NULL)
{
cout << "체인은 비어있다" << endl;
return;
}
if (x == first)
first = first->link; //다음 노드를 가리킨다
else
{
ChainNode<T> *temp = first;
while (temp->link != x)
{
temp = temp->link; //x 전 노드를 찾아간다
}
temp->link = x->link; //x 다음을 temp와 연결시켜 자연스럽게 x가 없어지도록 한다
}
delete x;
}
void InsertBack(const T &item)
{
if (first)
{
last->link = new ChainNode<T>(item);
last = last->link;
last->link = NULL;
}
else
{
first = last = new ChainNode<T>(item);
first->link = NULL;
}
}
void Concatenate(Chain<T> &b) //합치다
{
if (first)
{
last->link = b.first;
last = b.last;
}
else
{
first = b.first;
last = b.last;
}
}
void Reverse() //거꾸로
{
ChainNode<T> *current = first, *previous = NULL; //previous는 current 전 노드
while (current)
{
ChainNode<T> *r = previous; //previous의 위치를 기억해두었다가
previous = current;
current = current->link;
previous->link = r; //이전의 current가 이전의 previous를 가르키도록 한다
}
first = previous;
}
class ChainIterator
{
private:
ChainNode<T> *current;
public:
ChainIterator(ChainNode<T> *startNode = NULL)
{
current = startNode;
}
T getData()
{
return current->data;
}
T &operator*() const
{
return current->data;
}
T *operator->()
{
return ¤t->data;
}
ChainIterator &operator++() //++c
{
current = current->link;
return *this;
}
ChainIterator operator++(int) //c++
{
ChainIterator old = *this;
current = current->link;
return old;
}
bool operator!=(const ChainIterator right) const
{
return current != right.current;
}
bool operator==(const ChainIterator right) const
{
return current = right.current;
}
bool operator&&(const ChainIterator right) const
{
return current && right.current;
}
template <typename T>
friend ostream &operator<<(ostream &os, Chain<T> &c); //출력
};
ChainIterator begin()
{
return ChainIterator(first);
}
ChainIterator end()
{
return ChainIterator(0);
}
template <typename T>
friend ostream &operator<<(ostream &os, Chain<T> &c); //출력
};
template <typename T>
ostream &operator<<(ostream &os, Chain<T> &c)
{
Chain<T>::ChainIterator i = c.begin();
while (i != c.end())
{
os << i.getData() << "->";
i++;
}
os << i.getData();
os << endl;
return os;
}
class Polynomial
{
public:
struct Term
{
int coef; //계수
int exp; //지수
Term Set(int c, int e)
{
coef = c;
exp = e;
return *this;
}
};
private:
Chain<Term> poly;
public:
Polynomial()
{
}
void InsertTerm(Term &term)
{
poly.InsertBack(term); //식 추가
}
Polynomial operator+(Polynomial &b) //오름차순이 되어있다고 가정
{
Term temp;
Chain<Term>::ChainIterator ai = poly.begin(), bi = b.poly.begin();
Polynomial c; //두 식의 합을 반환할 클래스
while (ai && bi)
{
if (ai->exp == bi->exp) //지수가 동일할시 더하고
{
int sum = ai->coef + bi->coef;
if (sum)
c.poly.InsertBack(temp.Set(sum, ai->exp));
ai++;
bi++;
}
else if (ai->exp < bi->exp) //지수가 더 작은 쪽을 먼저 더한다, 그래야 높은 지수끼리 기다리고 더할 수 있다
{
c.poly.InsertBack(temp.Set(ai->coef, ai->exp));
ai++;
}
else
{
c.poly.InsertBack(temp.Set(bi->coef, bi->exp));
bi++;
}
}
while (ai != 0) //식이 더 많은 쪽을 마저 더한다
{
c.poly.InsertBack(temp.Set(ai->coef, ai->exp));
ai++;
}
while (bi != 0)
{
c.poly.InsertBack(temp.Set(bi->coef, bi->exp));
bi++;
}
return c;
}
int Eval(int x)
{
int sum = 0;
Chain<Term>::ChainIterator ai = poly.begin();
while (ai != 0)
{
for (int i = 0; i < ai->exp; i++)
{
x *= x;
}
sum += ai->coef*x;
ai++;
}
return sum;
}
friend ostream &operator<<(ostream &os, Polynomial &p);
friend istream &operator>>(istream &is, Polynomial &p);
};
ostream &operator<<(ostream &os, Polynomial &p)
{
Chain<Polynomial::Term>::ChainIterator i = p.poly.begin();
while (1)
{
Polynomial::Term term = *i;
os << term.coef << "x^(" << term.exp << ")";
if (++i != p.poly.end())
os << " + "; //끝이 아닐 경우 +
else
{
os << " ";
break;
}
}
return os;
}
istream &operator>>(istream &is, Polynomial &p)
{
int coef, exp;
int num;
cout << "다항식에 몇개의 식을 추가할 것인가?";
is >> num;
for (int i = 0; i < num; i++)
{
cout << i + 1 << "번째 계수: ";
is >> coef;
cout << i + 1 << "번째 지수: ";
is >> exp;
Polynomial::Term temp;
temp.exp = exp;
temp.coef = coef;
p.InsertTerm(temp);
}
return is;
}
int main(void)
{
Polynomial p1, p2, p3;
Polynomial sum;
int x;
Polynomial::Term temp;
for (int i = 0; i < 5; i++)
{
temp.Set(i+1, i+1);
p1.InsertTerm(temp);
}
for (int i = 0; i < 3; i++)
{
temp.Set(i + 2, i + 2);
p2.InsertTerm(temp);
}
cout << "p3 다항식 입력" << endl;
cin >> p3;
cout << "첫 번째 다항식" << endl << p1 << endl;
cout << "두 번째 다항식" << endl << p2 << endl;
cout << "세 번째 다항식" << endl << p3 << endl;
sum = p1 + p2;
cout << "첫 번째 두번째 다항식의 합" << endl << sum << endl;
cout << "세 번째 다항식 계산" << endl;
cout << "x의 값 입력: ";
cin >> x;
cout<< "계산값: "<< p3.Eval(x);
return 0;
}
| true |
8a8fdbd3c734aa169cf63c3b183abf3d33fa1bea | C++ | GEPTON-INFOTECH/flutter-practice | /calc.cpp | UTF-8 | 339 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void add()
{
int a,b,c;
cout<<"enter two number\n";
cin>>a>>b;
c=a+b;
cout<<"your addition is "<<c;
}
int main()
{
char n;
cout <<"Enter your choice\n";
cout<<"a for addtion\n";
cout<<"s for sub\n";
cin >>n;
if(n == 'a')
{
add();
}
}
| true |
22c2d5e42d60d3bfcbf0d7ecb37133ad24071dac | C++ | chaeonee/baekjoon | /C++/4889_안정적인문자열.cpp | UTF-8 | 1,442 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <stack>
using namespace std;
int main() {
int T = 0; // 루프의 순서 알려줄 변수
while(true){
string S;
cin >> S;
int s_len = S.length();
if(s_len > 0 && S[0] == '-'){ // 만약 '-'가 한 개 이상 존재하면 종료
break;
}
T++;
int cnt = 0; // 연산의 수를 세기 위한 변수
stack<bool> s; // '{'를 넣기 위한 stack('{'를 true로 넣을 것)
for(int i = 0; i < s_len; i++){ // 문자열의 문자 하나씩 확인
if(S[i] == '{'){ // '{'일 경우
s.push(true); // stack에 추가
}
else{ // '}'일 경우
if(s.empty()){ // stack이 비어있는지 확인해서 비어있으면 짝이 맞지 않는 것
cnt++; // 이때 '}'를 '{'로 바꿔주기 -> 연산 수 1증가
s.push(true); // '{'로 바꾸었기 때문에 stack에 추가
}
else{ // stack이 비어있지 않으면
s.pop(); // stack의 '{'와 짝을 이루기 때문에 하나 pop!
}
}
}
int s_size = s.size();
if(s_size != 0){ // 안정적인 문자열이라면 짝이 모두 맞기 때문에 stack이 비어있어야 함 -> 비어있지 않은 경우는 '{'가 더 많은 경우
cnt += s_size/2; // 남은 '{'끼리 서로 짝을 만들어 주어야 하므로 남은 '{'의 절반을 '}'로 바꿔야 함 -> 연산수: 남은 '{'의 수/2 만큼 추가
}
cout << T << ". " << cnt << '\n';
}
return 0;
}
| true |
8a684fa9f8e9f82b1484aa9815e5d699a33c94b1 | C++ | BGCX067/ezgame-svn-to-git | /EzGame-1.0.0/CoreLibs/EzRenderer/Ez3DBuffer.h | UTF-8 | 2,874 | 2.65625 | 3 | [] | no_license | #pragma once
#include "../EzCore/EzRTTI.h"
#include "../EzCore/EzTypes.h"
#include "../EzCore/EzDebugHelper.h"
#include "../EzCore/EzSystem.h"
#include "../EzCore/EzRefObject.h"
class Ez3DBuffer : public EzRefObject
{
EzDeclareRootRTTI(Ez3DBuffer);
public:
enum EUsage
{
ESTATIC = 1,
EDYNAMIC = 2,
EWRITE_ONLY = 4,
EDISCARDABLE = 8,
ESTATIC_WRITE_ONLY = 5,
EDYNAMIC_WRITE_ONLY = 6,
EDYNAMIC_WRITE_ONLY_DISCARDABLE = 14
};
enum ELockOptions
{
ENORMAL,
EDISCARD,
EREAD_ONLY,
ENO_OVERWRITE
};
Ez3DBuffer(Ez3DBuffer::EUsage eUsage, bool bUseSystemMemory)
: m_bIsLock(false), m_eUsage(eUsage), m_bSystemMemory(bUseSystemMemory), m_uiLockSize(0)
{
}
~Ez3DBuffer(void)
{
}
virtual void* lock(size_t offset, size_t length, ELockOptions eOptions);
void* lock(ELockOptions eOptions);
virtual void unlock(void);
bool isLocked(void) const;
void readData(u32 uiOffset, u32 uiLength, void* pDest);
void writeData(u32 uiOffset, u32 uiLength, const void* pSource, bool bDiscardWholeBuffer = false);
void copyData(Ez3DBuffer& srcBuffer, u32 uiSrcOffset, u32 uiDstOffset, u32 uiLength, bool bDiscardWholeBuffer = false);
protected:
/// Internal implementation of lock()
virtual void* lockImpl(u32 uiOffset, u32 uiLength, ELockOptions eOptions) = 0;
/// Internal implementation of unlock()
virtual void unlockImpl(void) = 0;
protected:
bool m_bIsLock;
u32 m_uiSizeInBytes;
EUsage m_eUsage;
u32 m_uiLockStart;
u32 m_uiLockSize;
bool m_bSystemMemory;
};
inline bool Ez3DBuffer::isLocked(void) const
{
return m_bIsLock;
}
inline void* Ez3DBuffer::lock(size_t offset, size_t length, ELockOptions eOptions)
{
EZASSERT(!isLocked());
void* ret;
// Lock the real buffer if there is no shadow buffer
ret = lockImpl(offset, length, eOptions);
m_bIsLock = true;
m_uiLockStart = offset;
m_uiLockSize = length;
return ret;
}
inline void* Ez3DBuffer::lock(ELockOptions eOptions)
{
return lock(0, m_uiSizeInBytes, eOptions);
}
inline void Ez3DBuffer::unlock(void)
{
EZASSERT(isLocked());
unlockImpl();
m_bIsLock = false;
}
inline void Ez3DBuffer::readData(u32 uiOffset, u32 uiLength, void* pDest)
{
void* pSrc = this->lock(uiOffset, uiLength, EREAD_ONLY);
EzMemoryCopy(pDest, pSrc, uiLength);
this->unlock();
}
inline void Ez3DBuffer::writeData(u32 uiOffset, u32 uiLength, const void* pSource, bool bDiscardWholeBuffer)
{
void* pDst = lock(uiOffset, uiLength, bDiscardWholeBuffer ? EDISCARD : ENORMAL);
EzMemoryCopy(pDst, pSource, uiLength);
this->unlock();
}
inline void Ez3DBuffer::copyData(Ez3DBuffer& srcBuffer, u32 uiSrcOffset, u32 uiDstOffset, u32 uiLength, bool bDiscardWholeBuffer)
{
const void *srcData = srcBuffer.lock(uiSrcOffset, uiLength, EREAD_ONLY);
writeData(uiDstOffset, uiLength, srcData, bDiscardWholeBuffer);
srcBuffer.unlock();
}
| true |
aff136df12bdb03a94b1bdd0e00592af6616aa80 | C++ | mauroFH/OptiDAR_DEV | /Dev/Modulo-Opti/src/random.cpp | UTF-8 | 927 | 3.125 | 3 | [] | no_license | /** \file random.cpp
* --------------------------------------------------------------------------
* Licensed Materials - Property of
* --------------------------------------------------------------------------
*/
#define IA 7141 /// random parameter */
#define IC 54733 /// random parameter */
#define IM 259200 /// random parameter */
/**
* @brief Compute a random number in [0,1]
* @return Random number in [0,1]
*/
float f_random()
{
static int seed;
seed = seed*IA + IC;
seed = seed - seed/IM * IM;
return (float)( seed + 0.0 ) / (float)IM;
}
/**
* @brief Set the random seed
* @param k seed
*/
void f_seedran(int k)
{
int i;
if (k <= 0)
return;
for (i=0; i<k; i++)
f_random();
}
/**
* @brief Compute a random number in [a,b]
* @param a first number
* @param b second number
* @return Random number in [a,b]
*/
int f_ranval(int a, int b)
{
return (int) (a + f_random()*(b-a+1));
}
| true |
3e059d043f797e5fcd5dd6ffa762c6871adec46e | C++ | Volgara/R-Type | /server/GameManager.cpp | UTF-8 | 3,172 | 2.65625 | 3 | [] | no_license | //
// Created by Volgar on 11/01/2018.
// Contact: volgar.dev@gmail.com
//
#include <iostream>
#include <cstring>
#include <network/Socket.hpp>
#ifdef _WIN32
#include <winsock2.h>
#include <Ws2tcpip.h>
#endif
#if defined(linux) || defined(__APPLE__)
#include <sys/socket.h>
#endif
#include "GameManager.hpp"
RTypeServer::GameManager::GameManager() {
RTypeServer::Room *newRoom = new RTypeServer::Room("Room1");
_room.push_back(newRoom);
RTypeServer::Room *newRoom2 = new RTypeServer::Room("Room2");
_room.push_back(newRoom2);
RTypeServer::Room *newRoom3 = new RTypeServer::Room("cara#~#{#[#");
_room.push_back(newRoom3);
}
RTypeServer::GameManager::~GameManager() {
}
bool RTypeServer::GameManager::join(Player *p, std::string roomname) {
if (p->getRoomStatus())
{
std::cout << "join error, player aleady in room" << std::endl;
return (false);
}
roomname.erase(0, 5);
if (roomname.length() == 0)
{
std::cout << "join error, bad room name" << std::endl;
return (false);
}
for (auto it : _room)
{
if (strcmp(it->getName().c_str(), roomname.c_str()) == 0)
{
p->setRoom(it->getName());
return(it->join(p));
}
}
RTypeServer::Room *newRoom = new RTypeServer::Room(roomname);
_room.push_back(newRoom);
for (auto it : _room)
{
if (strcmp(it->getName().c_str(), roomname.c_str()) == 0)
{
p->setRoom(it->getName());
return(it->join(p));
}
}
std::cout << "join failed, unknow error" << std::endl;
return (false);
}
void RTypeServer::GameManager::listRoom(Player *p) {
std::string data = "";
int a = 0;
for (auto it : _room)
{
if (!it->_gameStart)
{
if (a != 0)
data += "|";
data += it->getName();
data += ",";
data += std::to_string(it->getNbrPlayer());
a += 1;
}
}
std::cout << "Data send: " << data << std::endl;
send(p->getFd(), data.c_str(), data.size() + 1, 0);
}
bool RTypeServer::GameManager::start(Player *p) {
for (auto it : _room)
{
if (strcmp(it->getName().c_str(), p->getRoomName().c_str()) == 0)
{
it->start(p);
return (true);
}
}
return (false);
}
bool RTypeServer::GameManager::leave(Player *p) {
if (p->getRoomStatus())
{
for (auto it : _room)
{
if (it->getName() == p->getRoomName())
{
return(it->leave(p));
}
}
}
send(p->getFd(), "Ko", 3, 0);
return false;
}
void RTypeServer::GameManager::inforoom(Player *p) {
if (!p->getRoomStatus())
{
std::cout << "Error player not in a room" << std::endl;
return;
}
for (auto it : _room)
{
if (it->getName() == p->getRoomName())
{
std::string res;
res += std::to_string(it->getNbrPlayer());
send(p->getFd(), res.c_str(), res.size() + 1, 0);
return;
}
}
std::cout << "No room found"<< std::endl;
}
| true |
44d7bdb0f0ee60a177edaa961c064b17f62e8f20 | C++ | teju85/nvgraph | /cpp/tests/readMatrix.hxx | UTF-8 | 11,986 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <fstream>
#include <sstream> //stringstream
#include <string.h>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <cfloat>
//Matrix Market COO reader-requires a call to sort in the test file
template<typename IndexType_, typename ValueType_>
struct Mat
{
IndexType_ i;
IndexType_ j;
ValueType_ val;
bool transpose;
Mat() {
} //default cosntructor
Mat(bool transpose) :
transpose(transpose) {
} //pass in when comapring rows or columns
bool operator()(const Mat<IndexType_, ValueType_> &x1, const Mat<IndexType_, ValueType_> &x2)
{
if (!transpose)
{
if (x1.i == x2.i)
return x1.j < x2.j; //if rows equal sort by column index
return x1.i < x2.i;
}
else
{
if (x1.j == x2.j)
return x1.i < x2.i; //if rows equal sort by column index
return x1.j < x2.j;
}
}
};
template<typename ValueType_>
void dump_host_dense_mat(std::vector<ValueType_>& v, int ld)
{
std::stringstream ss;
ss.str(std::string());
ss << std::setw(10);
ss.precision(3);
for (int i = 0; i < ld; ++i)
{
for (int j = 0; j < ld; ++j)
{
ss << v[i * ld + j] << std::setw(10);
}
ss << std::endl;
}
std::cout << ss.str();
}
/**
* Reads in graphs given in the "network" format. This format consists a
* row for each edge in the graph, giving its source and destination. There
* is no header or comment lines.
* @param filename The name of the file to read in.
* @param nnz The number of edges given in the file.
* @param src Vector to write out the sources to.
* @param dest Vector to write out the destinations to.
*/
template<typename IndexType>
void readNetworkFile(const char * filename,
size_t nnz,
std::vector<IndexType>& src,
std::vector<IndexType>& dest) {
std::ifstream infile;
infile.open(filename);
src.resize(nnz);
dest.resize(nnz);
for (size_t i = 0; i < nnz; i++) {
infile >> src[i];
infile >> dest[i];
}
infile.close();
std::cout << "Read in " << nnz << " rows from: " << filename << "\n";
}
//reads the Matrix Market format from the florida collection of sparse matrices assuming
//the first lines are comments beginning with %
template<typename IndexType_, typename ValueType_>
void readMatrixMarketFile(const char * filename,
IndexType_ &m,
IndexType_ &n,
IndexType_ &nnz,
std::vector<Mat<IndexType_, ValueType_> > &matrix,
bool edges_only) {
std::ifstream infile;
infile.open(filename);
std::string line;
std::stringstream params;
while (1)
{
std::getline(infile, line);
//ignore initial comments that begin with %
if (line[0] != '%')
{
//first line without % for comments will have matrix size
params << line;
params >> n;
params >> m;
params >> nnz;
break; //break and then read in COO format
}
}
//COO format
matrix.resize(nnz);
//remaining file lines are tuples of row ind, col ind and possibly value
//sometimes value assumed to be one
for (int k = 0; k < nnz; ++k)
{
infile >> matrix[k].i;
infile >> matrix[k].j;
if (edges_only)
matrix[k].val = 1.0;
else
infile >> matrix[k].val;
}
infile.close();
}
//binary matrix reader functions
void printUsageAndExit()
{
printf("%s", "Usage:./csrmv_pl matrix_csr.bin\n");
printf("%s", "M is square, in Amgx binary format\n");
exit(0);
}
int read_header_amgx_csr_bin(FILE* fpin,
int & n,
int & nz
)
{
char text_header[255];
unsigned int system_flags[9];
size_t is_read1, is_read2;
is_read1 = fread(text_header, sizeof(char), strlen("%%NVAMGBinary\n"), fpin);
is_read2 = fread(system_flags, sizeof(unsigned int), 9, fpin);
if (!is_read1 || !is_read2)
{
printf("%s", "I/O fail\n");
return 1;
}
// We assume that system_flags [] = { 1, 1, whatever, 0, 0, 1, 1, n, nz };
/*
bool is_mtx = system_flags[0];
bool is_rhs = system_flags[1];
bool is_soln = system_flags[2];
unsigned idx_t matrix_format = system_flags[3];
bool diag = system_flags[4];
unsigned idx_t block_dimx = system_flags[5];
unsigned idx_t block_dimy = system_flags[6];
*/
if (system_flags[0] != 1 || system_flags[1] != 1 ||
system_flags[3] != 0 || system_flags[4] != 0 || system_flags[5] != 1 ||
system_flags[6] != 1 || system_flags[7] < 1 || system_flags[8] < 1)
{
printf( "Wrong format : system_flags [] != { 1(%d), 1(%d), 0(%d), 0(%d), 0(%d), 1(%d), 1(%d), n(%d), nz(%d) }\n\n",
system_flags[0],
system_flags[1],
system_flags[2],
system_flags[3],
system_flags[4],
system_flags[5],
system_flags[6],
system_flags[7],
system_flags[8]);
return 1;
}
n = system_flags[7];
nz = system_flags[8];
return 0;
}
//reader is for ints and double
template<typename I>
int read_csr_bin(FILE* fpin,
I &n,
I &nz,
std::vector<I> &row_ptr,
std::vector<I> &col_ind
)
{
size_t is_read1, is_read2, is_read3, is_read4;
is_read1 = fread(&n, sizeof(I), 1, fpin);
is_read2 = fread(&nz, sizeof(I), 1, fpin);
if (!is_read1 || !is_read2)
{
printf("%s", "I/O fail\n");
return 1;
}
row_ptr.resize(n + 1);
col_ind.resize(nz);
is_read3 = fread(&row_ptr[0], sizeof(I), n + 1, fpin);
is_read4 = fread(&col_ind[0], sizeof(I), nz, fpin);
if (!is_read3 || !is_read4)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
//reader is for ints and double
int read_data_amgx_csr_bin(FILE* fpin,
int n,
int nz,
std::vector<int> & row_ptr,
std::vector<int> & col_ind,
std::vector<double>& val
)
{
size_t is_read1, is_read2, is_read3;
is_read1 = fread(&row_ptr[0], sizeof(std::vector<int>::value_type), n + 1, fpin);
is_read2 = fread(&col_ind[0], sizeof(std::vector<int>::value_type), nz, fpin);
is_read3 = fread(&val[0], sizeof(std::vector<double>::value_type), nz, fpin);
if (!is_read1 || !is_read2 || !is_read3)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
int read_data_amgx_csr_bin_rhs(FILE* fpin,
int n,
int nz,
std::vector<int> & row_ptr,
std::vector<int> & col_ind,
std::vector<double>& val,
std::vector<double>& rhs
)
{
size_t is_read1, is_read2, is_read3, is_read4;
is_read1 = fread(&row_ptr[0], sizeof(std::vector<int>::value_type), n + 1, fpin);
is_read2 = fread(&col_ind[0], sizeof(std::vector<int>::value_type), nz, fpin);
is_read3 = fread(&val[0], sizeof(std::vector<double>::value_type), nz, fpin);
is_read4 = fread(&rhs[0], sizeof(std::vector<double>::value_type), n, fpin);
if (!is_read1 || !is_read2 || !is_read3 || !is_read4)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
//reader is for ints and double
int read_data_amgx_csr_bin(FILE* fpin,
int n,
int nz,
std::vector<int> & row_ptr,
std::vector<int> & col_ind,
std::vector<float>& val
)
{
size_t is_read1, is_read2, is_read3;
is_read1 = fread(&row_ptr[0], sizeof(std::vector<int>::value_type), n + 1, fpin);
is_read2 = fread(&col_ind[0], sizeof(std::vector<int>::value_type), nz, fpin);
double* t_storage = new double[std::max(n, nz)];
is_read3 = fread(t_storage, sizeof(double), nz, fpin);
for (int i = 0; i < nz; i++)
{
val[i] = static_cast<float>(t_storage[i]);
}
delete[] t_storage;
if (!is_read1 || !is_read2 || !is_read3)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
int read_data_amgx_csr_bin_rhs(FILE* fpin,
int n,
int nz,
std::vector<int> & row_ptr,
std::vector<int> & col_ind,
std::vector<float>& val,
std::vector<float>& rhs
)
{
size_t is_read1, is_read2, is_read3, is_read4;
is_read1 = fread(&row_ptr[0], sizeof(std::vector<int>::value_type), n + 1, fpin);
is_read2 = fread(&col_ind[0], sizeof(std::vector<int>::value_type), nz, fpin);
double* t_storage = new double[std::max(n, nz)];
is_read3 = fread(t_storage, sizeof(double), nz, fpin);
for (int i = 0; i < nz; i++)
{
val[i] = static_cast<float>(t_storage[i]);
}
is_read4 = fread(t_storage, sizeof(double), n, fpin);
for (int i = 0; i < n; i++)
{
rhs[i] = static_cast<float>(t_storage[i]);
}
delete[] t_storage;
if (!is_read1 || !is_read2 || !is_read3 || !is_read4)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
//read binary vector from file
int read_binary_vector(FILE* fpin,
int n,
std::vector<float>& val
)
{
size_t is_read1;
double* t_storage = new double[n];
is_read1 = fread(t_storage, sizeof(double), n, fpin);
for (int i = 0; i < n; i++)
{
if (t_storage[i] == DBL_MAX)
val[i] = FLT_MAX;
else if (t_storage[i] == -DBL_MAX)
val[i] = -FLT_MAX;
else
val[i] = static_cast<float>(t_storage[i]);
}
delete[] t_storage;
if (is_read1 != (size_t) n)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
int read_binary_vector(FILE* fpin,
int n,
std::vector<double>& val
)
{
size_t is_read1;
is_read1 = fread(&val[0], sizeof(double), n, fpin);
if (is_read1 != (size_t) n)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
int read_binary_vector(FILE* fpin,
int n,
std::vector<int>& val
)
{
size_t is_read1;
is_read1 = fread(&val[0], sizeof(int), n, fpin);
if (is_read1 != (size_t) n)
{
printf("%s", "I/O fail\n");
return 1;
}
return 0;
}
//read in as one based
template<typename IndexType_, typename ValueType_>
void init_MatrixMarket(IndexType_ base,
const char *filename,
bool edges_only, //assumes value is 1
bool transpose, //parameter to run on A or A'
IndexType_ &n,
IndexType_ &m,
IndexType_ &nnz,
std::vector<ValueType_> &csrVal,
std::vector<IndexType_> &csrColInd,
std::vector<IndexType_> &csrRowInd)
{
FILE *inputFile = fopen(filename, "r");
if (inputFile == NULL)
{
std::cerr << "ERROR: File path not valid!" << std::endl;
exit(EXIT_FAILURE);
}
std::vector<Mat<IndexType_, ValueType_> > matrix;
readMatrixMarketFile<IndexType_, ValueType_>(filename, m, n, nnz,
matrix,
edges_only);
Mat<IndexType_, ValueType_> compare(transpose);
std::sort(matrix.begin(), matrix.end(), compare);
csrVal.resize(nnz);
csrColInd.resize(nnz);
csrRowInd.resize(nnz);
for (int k = 0; k < nnz; ++k)
{
csrVal[k] = matrix[k].val;
csrColInd[k] = (transpose) ? matrix[k].i : matrix[k].j; //doing the transpose
csrRowInd[k] = (transpose) ? matrix[k].j : matrix[k].i;
}
if (base == 0) //always give base 0
{
for (int i = 0; i < nnz; ++i)
{
csrColInd[i] -= 1; //get zero based
csrRowInd[i] -= 1;
}
}
fclose(inputFile);
}
/*template<typename val_t>
bool almost_equal (std::vector<val_t> & a, std::vector<val_t> & b, val_t epsilon)
{
if (a.size() != b.size()) return false;
bool passed = true;
std::vector<val_t>::iterator itb=b.begin();
for (std::vector<val_t>::iterator ita = a.begin() ; ita != a.end(); ++ita)
{
if (fabs(*ita - *itb) > epsilon)
{
printf("At ( %ld ) : x1=%lf | x2=%lf\n",ita-a.begin(), *ita,*itb);
passed = false;
}
++itb;
}
return passed;
}*/
| true |
832e5c22a7e3ca5109cece4366fc631fb5adfeb4 | C++ | RyanARinger/HackerRankProjects | /InterviewPrep/3MonthPrepKit/Week2/7_Pangrams/Pangrams.cpp | UTF-8 | 812 | 3.40625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
* Complete the 'pangrams' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING s as parameter.
*/
string pangrams(string s) {
int len = s.size();
int sum = 0;
int A = 65; //ascii
int alSize = 26;
vector<int> al(alSize, 0);
for(int i = 0; i < len; i++){
if (al[toupper(s[i])%A] == 0){
al[toupper(s[i])%A]++;
}
}
for(int i = 0; i < 26; i++){
sum += al[i];
}
if(sum == alSize){
return "pangram";
}
return "not pangram";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string s;
getline(cin, s);
string result = pangrams(s);
fout << result << "\n";
fout.close();
return 0;
}
| true |
01f1e7943910c76f1ba7b2b2da028a306c04116e | C++ | Sudoka/D3 | /D3/Mat3.hpp | UTF-8 | 5,120 | 2.953125 | 3 | [
"CC-BY-3.0"
] | permissive | //
// Mat3.hpp
//
//
// Created by Srđan Rašić on 8/11/12.
// Copyright (c) 2012 Srđan Rašić. All rights reserved.
//
#ifndef _Mat3_hpp
#define _Mat3_hpp
namespace d3 {
#pragma mark Interface
class Mat3 {
public:
union {
struct {
float a00, a01, a02;
float a10, a11, a12;
float a20, a21, a22;
};
float m[9];
} __attribute__((aligned(16)));
public:
/*! Default constructor.
* Creates identity matrix.
*/
Mat3();
Mat3(float a00, float a01, float a02,
float a10, float a11, float a12,
float a20, float a21, float a22);
bool operator==(const Mat3& b) const;
bool operator!=(const Mat3& b) const;
//! Component-wise addition.
Mat3 operator+(const Mat3& b) const;
//! Component-wise subtraction.
Mat3 operator-(const Mat3& b) const;
//! Matrix multiplication.
Mat3 operator*(const Mat3& b) const;
//! Scalar multiplication.
Mat3 operator*(float f) const;
//! Matrix transpose.
Mat3 transpose() const;
//! Matrix inverse.
Mat3 inverse() const;
//! Matrix determinant.
float determinant() const;
//! Convert to const float*.
operator const float*() const;
operator float*();
};
#pragma marko Implementation
inline Mat3::Mat3()
:
a00(1.f), a01(0.f), a02(0.f),
a10(0.f), a11(1.f), a12(0.f),
a20(0.f), a21(0.f), a22(1.f)
{
}
inline Mat3::Mat3(float a00, float a01, float a02,
float a10, float a11, float a12,
float a20, float a21, float a22)
{
m[0] = a00;
m[1] = a01;
m[2] = a02;
m[3] = a10;
m[4] = a11;
m[5] = a12;
m[6] = a20;
m[7] = a21;
m[8] = a22;
}
inline bool Mat3::operator==(const Mat3& b) const
{
return !( *this != b );
}
inline bool Mat3::operator!=(const Mat3& b) const
{
return
a00 != b.a00 || a01 != b.a01 || a02 != b.a02 ||
a10 != b.a10 || a11 != b.a11 || a12 != b.a12 ||
a20 != b.a20 || a21 != b.a21 || a22 != b.a22;
}
inline Mat3 Mat3::operator+(const Mat3& b) const
{
return Mat3(a00 + b.a00, a01 + b.a01, a02 + b.a02,
a10 + b.a10, a11 + b.a11, a12 + b.a12,
a20 + b.a20, a21 + b.a21, a22 + b.a22);
}
inline Mat3 Mat3::operator-(const Mat3& b) const
{
return Mat3(a00 - b.a00, a01 - b.a01, a02 - b.a02,
a10 - b.a10, a11 - b.a11, a12 - b.a12,
a20 - b.a20, a21 - b.a21, a22 - b.a22);
}
inline Mat3 Mat3::operator*(const Mat3& b) const
{
Mat3 result;
result.m[0] = m[0] * b.m[0] + m[3] * b.m[1] + m[6] * b.m[2];
result.m[3] = m[0] * b.m[3] + m[3] * b.m[4] + m[6] * b.m[5];
result.m[6] = m[0] * b.m[6] + m[3] * b.m[7] + m[6] * b.m[8];
result.m[1] = m[1] * b.m[0] + m[4] * b.m[1] + m[7] * b.m[2];
result.m[4] = m[1] * b.m[3] + m[4] * b.m[4] + m[7] * b.m[5];
result.m[7] = m[1] * b.m[6] + m[4] * b.m[7] + m[7] * b.m[8];
result.m[2] = m[2] * b.m[0] + m[5] * b.m[1] + m[8] * b.m[2];
result.m[5] = m[2] * b.m[3] + m[5] * b.m[4] + m[8] * b.m[5];
result.m[8] = m[2] * b.m[6] + m[5] * b.m[7] + m[8] * b.m[8];
return result;
}
inline Mat3 Mat3::operator*(float f) const
{
return Mat3(a00 * f, a01 * f, a02 * f,
a10 * f, a11 * f, a12 * f,
a20 * f, a21 * f, a22 * f);
}
inline Mat3 Mat3::transpose() const
{
return Mat3(a00, a10, a20,
a01, a11, a21,
a02, a12, a22);
}
inline Mat3 Mat3::inverse() const
{
Mat3 result;
float det = 1.0f / determinant();
result.m[0] = (a11 * a22 - a12 * a21) * det;
result.m[1] = (a02 * a21 - a01 * a22) * det;
result.m[2] = (a01 * a12 - a02 * a11) * det;
result.m[3] = (a12 * a20 - a10 * a22) * det;
result.m[4] = (a00 * a22 - a02 * a20) * det;
result.m[5] = (a02 * a10 - a00 * a12) * det;
result.m[6] = (a10 * a21 - a11 * a20) * det;
result.m[7] = (a20 * a01 - a00 * a21) * det;
result.m[8] = (a00 * a11 - a01 * a10) * det;
return result;
}
inline float Mat3::determinant() const
{
return
a00 * a11 * a22 +
a01 * a12 * a20 +
a02 * a10 * a21 -
a02 * a11 * a20 -
a01 * a10 * a22 -
a00 * a12 * a21;
}
inline Mat3::operator float*()
{
return m;
}
inline Mat3::operator const float*() const
{
return (const float*)m;
}
}
#endif
| true |
9cabc2a5440f69686d24f7836f8d880d1d88ec7c | C++ | Park18/Algorithm | /boj/gold/2533.cpp | UTF-8 | 1,930 | 3.265625 | 3 | [] | no_license | /**
* @url https://www.acmicpc.net/problem/2533
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define YES true
#define NO false
struct EDGE_INFO
{
int a;
int b;
};
void input_edge_info(EDGE_INFO* edge_info_group, int size)
{
for (int loop = 1; loop < size; loop++)
{
int a, b;
cin >> a >> b;
edge_info_group[loop].a = a;
edge_info_group[loop].b = b;
}
}
void init_tree(EDGE_INFO* edge_info_group, vector<int>* tree, int size)
{
for (int index = 1; index < size; index++)
{
int parent, children;
if (edge_info_group[index].a < edge_info_group[index].b)
{
parent = edge_info_group[index].a;
children = edge_info_group[index].b;
}
else
{
parent = edge_info_group[index].b;
children = edge_info_group[index].a;
}
tree[parent].push_back(children);
}
}
void init_dp(int** dp, int size)
{
for (int index = 0; index <= size; index++)
dp[index] = new int[2]{ -1, -1 };
//memset(dp, -1, sizeof(int) * (size + 1) * 2);
}
int dfs(vector<int>* tree, int** dp, int node, int is_early_adapter)
{
int& min_result = dp[node][is_early_adapter];
if (min_result != -1)
return min_result;
if (is_early_adapter)
{
min_result = 1;
for (int children = 0; children < tree[node].size(); children++)
min_result += min(dfs(tree, dp, tree[node][children], YES), dfs(tree, dp, tree[node][children], NO));
}
else
{
min_result = 0;
for (int children = 0; children < tree[node].size(); children++)
min_result += dfs(tree, dp, tree[node][children], YES);
}
return min_result;
}
int main()
{
int N;
cin >> N;
EDGE_INFO* edge_info_group = new EDGE_INFO[N + 1];
vector<int>* tree = new vector<int>[N + 1];
input_edge_info(edge_info_group, N);
init_tree(edge_info_group, tree, N);
int** dp = new int* [N + 1];
init_dp(dp, N);
cout << min(dfs(tree, dp, 1, YES), dfs(tree, dp, 1, NO)) << endl;
} | true |
c6ccf94bb1d26887a720fb4d35b68a86b51272e9 | C++ | Phuc-T-Tran/Brick-Breaker | /Brick Breaker/Brick Breaker/Ball.cpp | UTF-8 | 6,126 | 2.71875 | 3 | [] | no_license | #include "Ball.h"
#include "Paddle.h"
#include "Brick.h"
#include <stdlib.h>
#include "Constants.h"
#include "PlayState.h"
#include <iostream>
using std::cout;
using std::endl;
Ball::Ball(PlayState* playState)
: playState(playState),
image(playState->getResources().getTexture("ball")),
velocity(0,-BallConstants::SPEED),
bounce(playState->getResources().getSound("bounce"))
{
rect.width = image.getWidth();
rect.height = image.getHeight();
velocity.rotate(rand() % 360);
}
Ball::Ball(ResourceManager& resources)
: image(resources.getTexture("ball")),
bounce(resources.getSound("bounce"))
{
rect.x = rand() % GameConstants::GAME_WIDTH;
rect.y = rand() % GameConstants::GAME_HEIGHT;
rect.width = image.getWidth();
rect.height = image.getHeight();
int mod = BallConstants::TITLE_SPEED_MAX;
velocity.y = -(rand() % mod + BallConstants::TITLE_SPEED_MIN);
velocity.rotate(rand() % 360);
}
Ball::~Ball()
{
}
void Ball::setOnPaddle()
{
Paddle& paddle = playState->getPaddle();
onPaddle = true;
rect.x = (float)(paddle.getX() + paddle.getWidth() / 2 - image.getWidth() / 2);
rect.y = (float)(paddle.getY() - image.getHeight());
velocity = { 0, -BallConstants::SPEED };
}
void Ball::idleBounce()
{
rect.x += velocity.x;
rect.y += velocity.y;
if (rect.left() < 0)
{
rect.setLeft(0);
velocity.x *= -1;
}
if (rect.right() > GameConstants::GAME_WIDTH)
{
rect.setRight(GameConstants::GAME_WIDTH);
velocity.x *= -1;
}
if (rect.top() < 0)
{
rect.setTop(0);
velocity.y *= -1;
}
if (rect.bot() > GameConstants::GAME_HEIGHT)
{
rect.setBot(GameConstants::GAME_HEIGHT);
velocity.y *= -1;
}
}
void Ball::update(Input& input)
{
Paddle& paddle = playState->getPaddle();
std::vector<Brick*>& bricks = playState->getBricks();
if (onPaddle)
{
setOnPaddle();
if (input.keyHit(SDL_SCANCODE_SPACE))
{
// Shoot off paddle in a random direction
float angle = 0.0f;
while (angle >= -10 && angle <= 10)
{
angle = (rand() % 90 - 45.0);
}
velocity.rotate(angle);
onPaddle = false;
}
}
else
{
// x-Collisions
rect.x += velocity.x;
// Check paddle collision
if (rect.overlaps(paddle.getRect()))
{
if (rect.left() < paddle.getRect().left())
{
rect.setRight(paddle.getRect().left());
if (velocity.x > 0)
velocity.x *= -1;
}
else if (rect.right() > paddle.getRect().right())
{
rect.setLeft(paddle.getRect().right());
if (velocity.x < 0)
velocity.x *= -1;
}
}
// Check brick collisions
for (std::vector<Brick*>::iterator it = bricks.begin();
it != bricks.end(); it++)
{
Rectangle colRect = (*it)->getRect();
if (rect.overlaps(colRect))
{
(*it)->damage();
if (rect.right() > colRect.right())
rect.setLeft(colRect.right());
else if (rect.left() < colRect.left())
rect.setRight(colRect.left());
velocity.x *= -1;
bounce.play();
if ((*it)->isDead())
bricks.erase(it);
break;
}
}
// y-Collisions
rect.y += velocity.y;
// Check paddle collisions
if (rect.overlaps(paddle.getRect()))
{
velocity.x = (rect.centerX() - paddle.getRect().centerX()) / 12;
if (velocity.x > 3)
velocity.x = 3;
else if (velocity.x < -3)
velocity.x = -3;
if (rect.top() < paddle.getRect().top())
rect.setBot(paddle.getRect().top());
else if (rect.bot() > paddle.getRect().bot())
rect.setTop(paddle.getRect().bot());
velocity.y *= -1;
}
// Check brick collisions
for (std::vector<Brick*>::iterator it = bricks.begin();
it != bricks.end(); it++)
{
Rectangle colRect = (*it)->getRect();
if (rect.overlaps(colRect))
{
(*it)->damage();
if (rect.top() < colRect.top())
rect.setBot(colRect.top());
else if (rect.bot() > colRect.bot())
rect.setTop(colRect.bot());
velocity.y *= -1;
bounce.play();
if ((*it)->isDead())
bricks.erase(it);
break;
}
}
// Check wall collisions
if (rect.left() < 0)
{
rect.setLeft(0);
velocity.x *= -1;
}
if (rect.right() > GameConstants::GAME_WIDTH)
{
rect.setRight(GameConstants::GAME_WIDTH);
velocity.x *= -1;
}
if (rect.top() < 0)
{
rect.setTop(0);
velocity.y *= -1;
}
if (rect.top() > GameConstants::GAME_HEIGHT)
{
setOnPaddle();
playState->loseLife();
}
}
}
void Ball::render(Graphics& graphics)
{
// "Afterimage?"
if (!onPaddle)
{
image.setAlpha(120);
//image.setScale(0.5);
image.render(rect.x - velocity.x, rect.y - velocity.y, graphics);
image.setAlpha(80);
//image.setScale(0.25);
image.render(rect.x - velocity.x * 2, rect.y - velocity.y * 2, graphics);
image.setAlpha(40);
//image.setScale(0.25);
image.render(rect.x - velocity.x * 3, rect.y - velocity.y * 3, graphics);
}
image.setAlpha(255);
image.setScale(1);
image.render(rect.x, rect.y, graphics);
}
int Ball::getX()
{
return rect.x;
}
int Ball::getY()
{
return rect.y;
} | true |
90b8271ae4ae6854f029543fe14e17134244942c | C++ | dbstkd1101/SW_PRO | /PRO_ONLINE/구간성분_2918_YSL(미완성).cpp | UTF-8 | 2,794 | 2.625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NULL 0
#define MAX_BUCKET_SIZE 15000
#define MAX_BUF_SIZE 15000
typedef unsigned long long ULL;
char sA[MAX_BUF_SIZE];
char sB[MAX_BUF_SIZE];
int lenSA;
int lenSB;
int sumA[MAX_BUF_SIZE];
int sumB[MAX_BUF_SIZE];
int strLen(const char* str) {
int cnt = 0;
while (*str) {
cnt++;
str += 1;
}
return cnt;
}
int minStr(const char* sA, const char* sB) {
int rst = 0;
if (strLen(&sA[1]) <= strLen(&sB[1])) {
rst = -1;
}
else {
rst = 1;
}
return rst;
}
int getHash(const int * sumArr, int startIdx, int len) {
ULL sum = 5831;
sum += (sumArr[startIdx + len - 1] - sumArr[startIdx - 1]) % MAX_BUCKET_SIZE;
return sum % MAX_BUCKET_SIZE;
}
int bufCnt = 0;
struct node {
int pos;
node * next;
node * mAlloc(int _pos, int hash) {
buf[bufCnt].pos = _pos;
buf[bufCnt].next = bucket[hash];
return bucket[hash] = this;
}
}*bucket[MAX_BUCKET_SIZE], buf[MAX_BUF_SIZE];
void addNode(const int * sumArr, int startIdx, int len) {
ULL hash = getHash(sumArr, startIdx, len);
bucket[hash] = buf[bufCnt++].mAlloc(startIdx, hash);
}
int isSame(const char* shortStr, int shortStrStartIdx, const char * longStr, int longStrStartIdx, int len) {
int rst = 1;
int alphaForShortStr[27] = { 0 };
int alphaForLongStr[27] = { 0 };
for (int i = 1; i <= len; i++) {
alphaForShortStr[shortStr[shortStrStartIdx] - 96]++;
}
for (int i = 1; i <= len; i++) {
if (--alphaForShortStr[longStr[longStrStartIdx] - 96] < 0) {
return rst = 0;
};
}
return rst;
}
// 6634
int checkVal(const char* shortStr, int startIdx, const char* longStr, int len) {
//sB, j-len+1 ,sA, len
int rst = 0;
int hash;
if (minStr(sA, sB) == 1) {
hash= getHash(sumB, startIdx, len);
}
else {
hash = getHash(sumA, startIdx, len);
}
for (node* p = bucket[hash]; p && p->pos; p = p->next) {
if (isSame(shortStr, startIdx, longStr, p->pos, len)) {
return rst = len;
}
}
return rst;
}
void init() {
for (int i = 0; i < MAX_BUCKET_SIZE; i++) {
bucket[i] = NULL;
}
bufCnt = 0;
}
int main() {
freopen("input.txt", "r", stdin);
scanf("%s", &sA[1]);
scanf("%s", &sB[1]);
for (int i = 1; sA[i] != NULL; i++) {
lenSA++;
sumA[i] = sumA[i - 1] + (sA[i] - 96) * (sA[i] - 96);
}
for (int i = 1; sB[i] != NULL; i++) {
lenSB++;
sumB[i] = sumB[i - 1] + (sB[i] - 96) * (sB[i] - 96);
}
int answer = 0;
if (minStr(sA, sB) == 1) {
for (int i = lenSB; i > 0; i--) {
if (answer) break;
int len = i;
init();
for (int k = 1; k <= lenSA; k++) {
if (k >= len) {
addNode(sumA, k - len + 1, len);
}
}
for (int j = 1; j <= lenSB; j++) {
if (j >= len) {
if (answer=checkVal(sB, j - len + 1, sA, len)) {
break;
}
}
}
}
}
printf("%d\n", answer);
return 0;
} | true |
8b183508fbe3a3e5b8ca5167086302be464ce344 | C++ | dk-dev/rethinkdb | /src/concurrency/watchable_map.hpp | UTF-8 | 8,865 | 2.703125 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONCURRENCY_WATCHABLE_MAP_HPP_
#define CONCURRENCY_WATCHABLE_MAP_HPP_
#include <functional>
#include <map>
#include "concurrency/signal.hpp"
#include "concurrency/pubsub.hpp"
#include "concurrency/watchable.hpp"
#include "containers/map_sentries.hpp"
#include "containers/optional.hpp"
#include "utils.hpp"
/* `watchable_map_t` is like `watchable_t` except specialized for holding a map in which
the keys usually update independently. If the map contains N keys, it takes O(log(N))
time to propagate an update for that key, as opposed to a `watchable_t<std::map>`, which
would take O(N) time.
Note that `watchable_map_t` doesn't make any guarantees about update ordering. The values
visible in the `watchable_map_t` are guaranteed to quickly converge to the correct value,
but they could do so in any order. In addition, if a value is changed and then quickly
changed back, it's possible that no notification will be sent. (The current
implementation will always deliver notifications in this case, but there's no guarantee.)
*/
template<class key_t, class value_t>
class watchable_map_t : public home_thread_mixin_t {
public:
/* `all_subs_t` registers for notifications whenever any key in the map is inserted,
deleted, or changed. */
class all_subs_t {
public:
/* Starts watching for changes to the given map. When a change occurs to a key,
`cb` will be called with the key and a pointer to the new value, or `nullptr` if
the key was deleted. If `initial_call` is `YES`, then `cb` will be called once
for each key-value pair in the map at the time the `all_subs_t` is created. */
all_subs_t(
watchable_map_t<key_t, value_t> *map,
const std::function<void(const key_t &, const value_t *)> &cb,
initial_call_t initial_call = initial_call_t::YES);
private:
typename publisher_t<std::function<void(const key_t &, const value_t *)> >
::subscription_t subscription;
DISABLE_COPYING(all_subs_t);
};
/* `key_subs_t` registers for notifications whenever a specific key in the map
is inserted, deleted, or changed. */
class key_subs_t {
public:
/* Starts watching for changes to the given key in the given map. When `key` is
inserted, changed, or deleted in `map`, `cb` will be called with a pointer to the
new value, or `nullptr` if `key` was deleted. If `initial_call` is `YES`, then
the constructor will call `cb` once with the initial value of `key`. */
key_subs_t(
watchable_map_t<key_t, value_t> *map,
const key_t &key,
const std::function<void(const value_t *maybe_value)> &cb,
initial_call_t initial_call = initial_call_t::YES);
private:
multimap_insertion_sentry_t<key_t, std::function<void(const value_t *)> > sentry;
DISABLE_COPYING(key_subs_t);
};
/* Returns all of the key-value pairs in the map. This needs to copy all of the keys
and values in the map, so it's likely to be slow. */
virtual std::map<key_t, value_t> get_all() = 0;
/* Looks up a single key-value pair in the map. Returns the value if found, or an
empty `optional` if not. This needs to copy the value, so it's likely to be
slow. */
virtual optional<value_t> get_key(const key_t &key) = 0;
/* `read_all()` and `read_key()` are like `get_all()` and `get_key()`, except that
they avoid copying. */
virtual void read_all(
/* This function will be called once for each key-value pair in the map. The
`const value_t *` will always be non-NULL; it's a pointer for consistency with
other functions in this class. */
const std::function<void(const key_t &, const value_t *)> &) = 0;
virtual void read_key(
const key_t &key,
const std::function<void(const value_t *)> &) = 0;
/* `run_key_until_satisfied()` repeatedly calls `fun()` on a `const value_t *`
representing the current value of `key` until `fun` returns `true` or `interruptor`
is pulsed. It's efficient because it only retries `fun` when the value changes. */
template<class callable_t>
void run_key_until_satisfied(
const key_t &key,
const callable_t &fun,
signal_t *interruptor);
/* `run_all_until_satisfied()` repeatedly calls `fun()` with `this` until `fun`
returns `true` or `interruptor` is pulsed. It's efficient because it only retries
`fun` when a key has changed. */
template<class callable_t>
void run_all_until_satisfied(
const callable_t &fun,
signal_t *interruptor);
protected:
watchable_map_t() { }
virtual ~watchable_map_t() { }
/* Subclasses should call `notify_change()` any time that they alter values. */
void notify_change(
const key_t &key,
const value_t *new_value,
rwi_lock_assertion_t::write_acq_t *acq);
void rethread(threadnum_t new_thread) {
home_thread_mixin_t::real_home_thread = new_thread;
all_subs_publisher.rethread(new_thread);
}
private:
virtual rwi_lock_assertion_t *get_rwi_lock() = 0;
publisher_controller_t<std::function<void(const key_t &, const value_t *)> >
all_subs_publisher;
std::multimap<key_t, std::function<void(const value_t *)> > key_subs_map;
DISABLE_COPYING(watchable_map_t);
};
template<class key_t, class value_t>
class watchable_map_var_t : public watchable_map_t<key_t, value_t> {
public:
/* `entry_t` creates a map entry in its constructor and removes it in the destructor.
It is an alternative to `set_key()` and `delete_key()`. It crashes if an entry with
that key already exists. Don't call `delete_key()` on the entry that this creates,
and don't call `set_all()` while this exists. */
class entry_t {
public:
entry_t() : parent(nullptr) { }
entry_t(watchable_map_var_t *parent, const key_t &key, const value_t &value);
entry_t(const entry_t &) = delete;
entry_t(entry_t &&);
~entry_t();
entry_t &operator=(const entry_t &) = delete;
entry_t &operator=(entry_t &&);
key_t get_key() const;
value_t get_value() const;
void set(const value_t &new_value);
void set_no_equals(const value_t &new_value);
void change(const std::function<bool(value_t *value)> &callback);
private:
watchable_map_var_t *parent;
typename std::map<key_t, value_t>::iterator iterator;
};
watchable_map_var_t() { }
explicit watchable_map_var_t(std::map<key_t, value_t> &&source);
std::map<key_t, value_t> get_all();
optional<value_t> get_key(const key_t &key);
void read_all(const std::function<void(const key_t &, const value_t *)> &);
void read_key(const key_t &key, const std::function<void(const value_t *)> &);
/* `set_all()` removes all of the key-value pairs from the map and replaces them with
values from `new_value`. */
void set_all(const std::map<key_t, value_t> &new_value);
/* `set_key()` sets the value of `key` to `new_value`. If `key` was not in the
map before, it will be inserted. As an optimization, `set_key()` compares the
previous value of `key` to `new_value`; if they compare equal, it will not notify
subscriptions. If `value` does not support equality comparisons, use
`set_key_no_equals()`. */
void set_key(const key_t &key, const value_t &new_value);
void set_key_no_equals(const key_t &key, const value_t &new_value);
/* `delete_key()` removes `key` from the map if it was present before. */
void delete_key(const key_t &key);
/* `change_key()` atomically modifies the value of `key`. It calls the callback
exactly once, with two parameters `exists` and `value`. If the key is present,
`*exists` will be `true` and `*value` will be its value; if the key is absent, then
`*exists` will be `false` and `*value` will be a valid buffer but with undefined
contents. The callback can modify `*exists` and/or `*value`. It must return `true` if
it makes any changes. these changes will be reflected in the `watchable_map_t`. The
callback must not block or call any other methods of the `watchable_map_var_t`. */
void change_key(
const key_t &key,
const std::function<bool(bool *exists, value_t *value)> &callback);
void rethread(threadnum_t new_thread) {
watchable_map_t<key_t, value_t>::rethread(new_thread);
rwi_lock.rethread(new_thread);
}
private:
rwi_lock_assertion_t *get_rwi_lock() {
return &rwi_lock;
}
std::map<key_t, value_t> map;
rwi_lock_assertion_t rwi_lock;
};
#include "concurrency/watchable_map.tcc"
#endif /* CONCURRENCY_WATCHABLE_MAP_HPP_ */
| true |
f3ab5bb563c40238680bdb3e3537813d771d2584 | C++ | KusumaAonsatit/Maze-Robot | /PID_Motor/PID_Motor.ino | UTF-8 | 3,489 | 2.953125 | 3 | [] | no_license | // Motor A Left
int dir1PinA = 2;
int dir2PinA = 3;
int speedPinA = 6; // เพื่อให้ PWM สามารถควบคุมความเร็วมอเตอร์
// Motor B Right
int dir1PinB = 4;
int dir2PinB = 5;
int speedPinB = 7; // เพื่อให้ PWM สามารถควบคุมความเร็วมอเตอร์
//Counter speed sensor-----------------------------------------------------------------------//
const byte interruptPinL = 18;
const byte interruptPinR = 19;
long Left,Right;
int normalSpeed = 192; // 25% Duty Cycle
class PID{
public:
double error;
double sample;
double lastSample;
double kP, kI, kD;
double P, I, D;
double pid;
double setPoint;
long lastProcess;
PID(double _kP, double _kI, double _kD){
kP = _kP;
kI = _kI;
kD = _kD;
}
void addNewSample(double _sample){
sample = _sample;
}
void setSetPoint(double _setPoint){
setPoint = _setPoint;
}
double process(){
// Implementação P ID
error = setPoint - sample;
float deltaTime = (millis() - lastProcess) / 1000.0;
lastProcess = millis();
//P
P = error * kP;
//I
I = I + (error * kI) * deltaTime;
//D
D = (lastSample - sample) * kD / deltaTime;
lastSample = sample;
// Soma tudo
pid = P + I + D;
return pid;
}
};
PID pid(3, 7, 0.05);
void setup() {
pid.setSetPoint(0.0);
Serial.begin(9600);//set board
//interrupt--------------------------------------------------------------------
pinMode(interruptPinL, INPUT);
pinMode(interruptPinR, INPUT);
attachInterrupt(digitalPinToInterrupt(18), ISR_L, RISING );
attachInterrupt(digitalPinToInterrupt(19), ISR_R, RISING );
//Motor--------------------------------------------------------------------------
pinMode(dir1PinA,OUTPUT);
pinMode(dir2PinA,OUTPUT);
pinMode(speedPinA,OUTPUT);
pinMode(dir1PinB,OUTPUT);
pinMode(dir2PinB,OUTPUT);
pinMode(speedPinB,OUTPUT);
}
void ISR_L(){
Left++;
}
void ISR_R(){
Right++;
}
void loop() {
// TODO: critical section
long error = Left - Right;
long minCount = min(Left, Right);
Left -= minCount;
Right -= minCount;
// Add new sample to PID
pid.addNewSample(error);
// PID feedback
int powerDiff = int(pid.process());
Serial.print("Left: ");
Serial.print(Left);
Serial.print("Right: ");
Serial.print(Right);
Serial.print("-------------Error: ");
Serial.print(error);
Serial.print(" | powerDiff: ");
Serial.println(powerDiff);
// Update motor speed
if (powerDiff < 0)
set_power(normalSpeed + powerDiff, normalSpeed);
else
set_power(normalSpeed, normalSpeed - powerDiff);
}
int set_power(int speed_left,int speed_right){
speed_left = max(min(speed_left, 100), 0);
speed_right = max(min(speed_right, 100), 0);
// Motor A ด้านซ้าย
analogWrite(speedPinA, speed_left); //ตั้งค่าความเร็ว PWM ผ่านตัวแปร ค่าต่ำลง มอเตอร์จะหมุนช้าลง
digitalWrite(dir1PinA, LOW);
digitalWrite(dir2PinA, HIGH);
// Motor B ด้านขวา
analogWrite(speedPinB, speed_right); //ตั้งค่าความเร็ว PWM ผ่านตัวแปร ค่าต่ำลง มอเตอร์จะหมุนช้าลง
digitalWrite(dir1PinB, LOW);
digitalWrite(dir2PinB, HIGH);
}
| true |
abc36ceed66ffaab10b3b148b1b70bce59c662e1 | C++ | Mohumeddahir/Assignment10 | /main.cpp | UTF-8 | 3,599 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include"LinkedList.hpp"
using namespace std;
int main(){
LinkedList test1;
cout<<"is it empty "<<test1.is_empty()<<endl;
//test1.remove_first();
try{
//test1.remove_first();
//test1.remove_last();
//test1.remove_current();
//test1.next();
//test1.prev();
//test1.get_first();
//test1.get_last();
//test1.get_current();
test1.set_current(2);
}
catch(ListException &ex){
cout<<ex.to_string()<<endl;
}
test1.insert_first("g");
test1.insert_first("a");
//test1.print_contents();
test1.insert_first("m");
test1.insert_first("r");
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.print_contents();
test1.insert_last("z");
test1.print_contents();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"The last element is: "<<test1.get_last()<<endl;
test1.insert_after_current("y");
test1.print_contents();
test1.insert_before_current("w");
test1.print_contents();
test1.insert_first("n");
test1.print_contents();
cout<<"The last element is "<<test1.get_last()<<endl;
test1.insert_after_current("h");
test1.print_contents();
test1.insert_before_current("k");
test1.print_contents();
cout<<test1.get_first()<<endl;
cout<<test1.prev()<<endl;
test1.insert_after_current("o");
test1.print_contents();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the element in the current is: "<<test1.get_current()<<endl;
test1.set_current(4);
cout<<"the element in the current is: "<<test1.get_current()<<endl;
test1.update_current("tr");
cout<<"the element in the current is: "<<test1.get_current()<<endl;
test1.print_contents();
cout<<"the current is moved to the next: "<<test1.next()<<endl;
test1.remove_current();
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the first element that was removed is: "<<test1.remove_first()<<endl;
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the last element that was removed is: "<<test1.remove_last()<<endl;
cout<<"the current is moved to the prev: "<<test1.prev()<<endl;
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the element in the current that was removed is: "<<test1.remove_current()<<endl;
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the first element that was removed is "<<test1.remove_first()<<endl;
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
cout<<"the element in the current that was removed is "<<test1.remove_current()<<endl;
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.remove_last();
test1.print_contents();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.remove_current();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.print_contents();
test1.remove_first();
test1.print_contents();
test1.print_contents_reverse();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.remove_current();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.print_contents();
test1.remove_last();
cout<<"the size of the element is: "<<test1.get_size()<<endl;
test1.print_contents();
test1.print_contents_reverse();
test1.remove_current();
return 0;
}
| true |
43f84d9d9ef75b336bfd558c5b11ac93db673e5c | C++ | dantasunifei/UCTP | /CP-Empty/src/CP-Empty.cpp | UTF-8 | 6,727 | 2.625 | 3 | [] | no_license | #include <ilcp/cp.h>
#include <math.h>
#include <iostream>
#include <string.h>
using namespace std;
int array1[25] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24};
int array2[15] = {0,2,3,5,7,8,10,12,13,15,17,18,20,22,23};
int array3[5] = {2,7,12,17,22};
int main(int, const char * [])
{
IloEnv env;
IloModel model(env);
IloIntArray SlotsTam1(env, 25);
for(int i=0; i < 25; i++)
SlotsTam1.add(array1[i]);
IloIntArray SlotsTam2(env, 15);
for(int i=0; i < 15; i++)
SlotsTam2.add(array2[i]);
IloIntArray SlotsTam3(env, 5);
for(int i=0; i < 5; i++)
SlotsTam3.add(array3[i]);
try{
ifstream arq("dados.txt");
int nSlotsDia, nDiasSemana, nTurmas, nDisciplinas, nProfessores, nSalas, nConflitos;
// Lê as primeiras informações do arquivo
arq >> nSlotsDia;
arq >> nDiasSemana;
arq >> nProfessores;
arq >> nSalas;
arq >> nTurmas;
arq >> nConflitos;
arq >> nDisciplinas;
cout << "Atribuiu primeiras informações " << nSlotsDia << " " << nDiasSemana << " " << nProfessores << " " << nSalas << " " << nDisciplinas << " " << endl;
IloIntervalVarArray Professores[nProfessores];
for(int i = 0; i < nProfessores; i++)
Professores[i] = IloIntervalVarArray(env);
//Lendo Disciplinas
IloIntVarArray Inicios(env);
IloIntervalVar Disciplinas[nDisciplinas];
IloIntVarArray DiscSalas(env);
IloIntArray DisciplinaProfessor(env, nDisciplinas);
for(int i = 0; i < nDisciplinas; i++) {
string temp = "";
arq >> temp; //Sigla da Disciplina
const char * nomeDisc = temp.c_str();
int prof;
arq >> prof; //Professor vinculado a disciplina
DisciplinaProfessor[i] = prof;
int tamanho;
arq >> tamanho; //Tamanho dos Slots
cout << "Disciplina " << i << " " << nomeDisc << " tamanho " << tamanho << " professor " << prof ;
IloIntArray* ponteiro;
switch(tamanho)
{
case 1:
ponteiro = &SlotsTam1;
break;
case 2:
ponteiro = &SlotsTam2;
break;
case 3:
ponteiro = &SlotsTam3;
break;
}
string nome = "Inicio " + temp + ":";
IloIntVar x(env, *ponteiro, nome.c_str());
Inicios.add(x);
Disciplinas[i] = IloIntervalVar(env, tamanho, nomeDisc);
//Adicionando Professor
model.add(x == IloStartOf(Disciplinas[i])); //Adicionando início dos Slots
Professores[prof].add(Disciplinas[i]); //Adicionando Professor
//Adicionando salas
int nSalasDisc;
arq >> nSalasDisc;
cout << " Salas " << nSalasDisc << " ->";
IloIntArray SalasPossiveis(env);
for(int j=0; j < nSalasDisc; j++)
{
int idSalasDisc;
arq >> idSalasDisc;
SalasPossiveis.add(idSalasDisc);
cout << " " << idSalasDisc;
}
string nomesalas = "Salas Disciplina " + temp + ": ";
IloIntVar s (env, SalasPossiveis, nomesalas.c_str());
DiscSalas.add(s);
cout << endl;
}
cout << endl << "IMPRIMINDO PROFESSORES/DISCIPLINAS " << endl;
for(int i = 0; i < nProfessores; i++)
{
cout << "Prof: " << i << " ";
for(int j = 0; j < Professores[i].getSize(); j++ )
{
cout << Professores[i][j].getName() << "\t ";
}
cout << endl;
}
//Le as informações de turmas
IloIntervalVarArray DiscPorTurma[nTurmas];
IloIntArray DiscPorTurmaId[nTurmas];
for(int i = 0; i < nTurmas; i++) {
DiscPorTurma[i] = IloIntervalVarArray(env);
DiscPorTurmaId[i] = IloIntArray(env);
int nDisc;
arq >> nDisc;
cerr << "Turma " << i << " Numero Disciplinas " << nDisc << " ->";
for(int j = 0; j < nDisc; j++) {
int idDisc;
arq >> idDisc;
DiscPorTurma[i].add(Disciplinas[idDisc]);
DiscPorTurmaId[i].add(idDisc);
cerr << " " << idDisc;
}
cout << endl;
model.add(IloNoOverlap(env,DiscPorTurma[i]));
}
//Le as informações de Conflitos
for(int i = 0; i < nConflitos; i++) {
int nDisc;
arq >> nDisc;
cout << "Conflitos " << i << " Qtd " << nDisc << " -> ";
int DiscLista[nDisc];
for(int j = 0; j < nDisc; j++)
arq >> DiscLista[j];
for(int j = 0; j < nDisc -1; j++) {
for(int k = j+1; k < nDisc; k++) {
//SEG
model.add(IloIfThen(env, IloStartOf(Disciplinas[DiscLista[j]]) <= 4, IloStartOf(Disciplinas[DiscLista[k]]) >=5));
//TER
model.add(IloIfThen(env, 5 <= IloStartOf(Disciplinas[DiscLista[j]]) <= 9, IloStartOf(Disciplinas[DiscLista[k]]) <=4 || 10 <= IloStartOf(Disciplinas[DiscLista[k]])));
//QUA
model.add(IloIfThen(env, 10 <= IloStartOf(Disciplinas[DiscLista[j]]) <= 14, IloStartOf(Disciplinas[DiscLista[k]]) <=9 || 15 <= IloStartOf(Disciplinas[DiscLista[k]])));
//QUI
model.add(IloIfThen(env, 15 <= IloStartOf(Disciplinas[DiscLista[j]]) <= 19, IloStartOf(Disciplinas[DiscLista[k]]) <=15 || 20 <= IloStartOf(Disciplinas[DiscLista[k]])));
//SEX
model.add(IloIfThen(env, 20 <= IloStartOf(Disciplinas[DiscLista[j]]) <= 24, IloStartOf(Disciplinas[DiscLista[k]]) <=21 ));
cout << " D[" << DiscLista[j] << "]=" << Disciplinas[DiscLista[j]].getName() << "] D[" << DiscLista[k] << "]=" << Disciplinas[DiscLista[k]].getName() << ",";
}
}
cout << endl;
}
//Demais Restrições
for(int i = 0; i < nProfessores; i++)
model.add(IloNoOverlap(env,Professores[i]));
for(int i =0 ; i <nDisciplinas; i++)
{
for(int j =0 ; j <nDisciplinas; j++)
{
if(i != j)
model.add(IloIfThen(env, DiscSalas[i] == DiscSalas[j], IloStartOf(Disciplinas[i]) >= IloEndOf(Disciplinas[j]) || IloStartOf(Disciplinas[j]) >= IloEndOf(Disciplinas[i])));
}
}
//Realizando Resolução
IloCP cp(model);
cp.exportModel("ucp.cpo");
if (cp.solve()) {
cout << endl << "Status solucao: " << cp.getStatus() << endl;
for(int i = 0; i < nTurmas; i++)
{
cout << endl << "Turma " << i << std::endl;
cout << "SEGUNDA-FEIRA \t TERÇA-FEIRA \t QUARTA-FEIRA \t QUINTA-FEIRA \t SEXTA-FEIRA " << endl;
for(int j = 0; j < nSlotsDia; j++)
{
for(int w = 0; w < nDiasSemana; w++) {
IloInt c = w * nSlotsDia + j;
bool achou = false;
for(int d = 0; d < DiscPorTurma[i].getSize(); d++) {
int inicio = cp.getValue(Inicios[DiscPorTurmaId[i][d]]);
int final = (inicio + Disciplinas[DiscPorTurmaId[i][d]].getSizeMax());
if(inicio <= c && c < final) {
cout << "D:" << Disciplinas[DiscPorTurmaId[i][d]].getName();
cout << " S:" << cp.getValue(DiscSalas[DiscPorTurmaId[i][d]]);
cout << " P:" << DisciplinaProfessor[DiscPorTurmaId[i][d]] << " \t ";
achou = true;
}
}
if(!achou) {
cout << "Sem aula" << " \t ";
}
}
cout << endl;
}
cout << std::endl;
}
} else {
cp.out() << "No solution found. " << std::endl;
}
}catch(IloException& ex)
{
env.out() << "Erro: " << ex << std::endl;
}
}
| true |
5d2bc4a79d499a97126bb645820966006915e8a6 | C++ | Alybaev/UVA | /11629.cpp | UTF-8 | 1,240 | 3.265625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
double round(double var)
{
// 37.66666 * 100 =3766.66
// 3766.66 + .5 =37.6716 for rounding off value
// then type cast to int so value is 3766
// then divided by 100 so the value converted into 37.66
double value = (int)(var * 10 + .5);
return (double)value / 10;
}
int main()
{
int peop;
cin >> peop;
unordered_map<string,double> spis;
int test;
cin >> test;
for(int i = 0;i < peop;i++)
{
string name;
cin >> name;
double value;
cin >> value;
spis.insert({name,value});
}
for(int i = 0;i < test;i++)
{
string name;
string oper;
double sum = 0;
while(cin >> name >> oper and oper == "+")
{
sum += spis[name];
}
sum += spis[name];
sum = round(sum);
int comp;
cin >> comp;
bool res = false;
if (oper == "<"){
res = (sum < (double)(comp));
}else if(oper == ">")
{
res = (sum > (double)(comp));
}
else if (oper ==">=")
{
res = (sum >= (double)(comp));
}else if (oper == "<=")
{
res = (sum <= (double)(comp));
}else{
res = (sum == (double)(comp));
}
cout << "Guess #" << i+1 << " was " << ((res) ? "correct.\n" : "incorrect.\n");
}
return 0;
}
| true |
a1c42d551cc62b2365ba6728ac3a587a804f98e6 | C++ | Acejoy/LeetcodePrep | /22. Generate Parentheses/solution.cpp | UTF-8 | 1,013 | 3.34375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void printArray(vector<string> v) {
for(auto e: v) {
cout<<e<<endl;
}
cout<<"-----------------------"<<endl;
}
void getAns(int n, string s, stack<char> st, vector<string> &v) {
if(n>=1) {
int n1=n;
stack<char> new_st = st;
n1--;
new_st.push(')');
getAns(n1, s+'(',new_st, v );
if(!st.empty()) {
st.pop();
getAns(n, s+')', st, v);
}
} else {
while(!st.empty()) {
s += ')';
st.pop();
}
v.push_back(s);
}
}
void getAns2(int n, string s, int m, vector<string> &v) {
if(n>=1) {
int n1=n;
int m1 = m;
n1--;
m1++;
getAns2(n1, s+'(',m1, v );
if(m>0) {
//st.pop();
getAns2(n, s+')', m-1, v);
}
} else {
while(m>0) {
s += ')';
m--;
}
v.push_back(s);
}
}
vector<string> generateParenthesis(int n) {
stack<char> st;
string s;
vector<string> v;
getAns2(n, s, 0, v);
return v;
}
int main() {
vector<string> ans;
int n;
cin>>n;
ans = generateParenthesis(n);
printArray(ans);
return 0;
} | true |
0708a2df298e7cc5d9ed47c9c36e8a54c6546ccd | C++ | jamloya/coding-practice | /leetcode/Binary tree inorder traversal .cpp | UTF-8 | 1,024 | 3.40625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode* current=root;
int i=0;
while(current !=NULL)
{
if(current->left==NULL)
{ //cout<<++i<<current->val<<"H"<<endl;
result.push_back(current->val);
current=current->right;
}
else
{ //cout<<++i<<current->val<<"L"<<endl;
TreeNode* pre=current->left;
while(pre->right!=NULL)
{
pre=pre->right;
}
pre->right=current;
TreeNode* temp=current;
current=current->left;
temp->left=NULL;
}
}
return result;
}
};
| true |
0694de8792d98eeb27c834fc2c6eb2995dd56596 | C++ | ToLoveToFeel/LeetCode | /Cplusplus/_1310_XOR_Queries_of_a_Subarray/_1310_main.cpp | UTF-8 | 1,186 | 3.265625 | 3 | [] | no_license | // Created by WXX on 2021/5/12 10:04
#include <iostream>
#include <vector>
using namespace std;
/**
* 执行用时:80 ms, 在所有 C++ 提交中击败了63.53%的用户
* 内存消耗:32 MB, 在所有 C++ 提交中击败了32.15%的用户
*/
class Solution {
public:
vector<int> xorQueries(vector<int> &arr, vector<vector<int>> &queries) {
int n = arr.size();
vector<int> s(n + 1, 0);
for (int i = 1; i <= n; i++) s[i] = s[i - 1] ^ arr[i - 1];
vector<int> res;
for (int i = 0; i < queries.size(); i++) {
int l = queries[i][0] + 1, r = queries[i][1] + 1;
res.push_back(s[r] ^ s[l - 1]);
}
return res;
}
};
void OutputBasicArray1D(vector<int> nums) {
cout << "[";
for (int i = 0; i < nums.size(); i++) {
cout << nums[i];
if (i != nums.size() - 1) cout << ", ";
}
cout << "]" << endl;
}
int main() {
vector<int> arr = {1, 3, 4, 8};
vector<vector<int>> queries = {
{0, 1},
{1, 2},
{0, 3},
{3, 3},
};
OutputBasicArray1D(Solution().xorQueries(arr, queries)); // [2, 7, 14, 8]
return 0;
}
| true |
4ad66be24fcdaf68eea639ebee01631c5762058f | C++ | hbursk/shout-drums | /shout-drums/AdditionalSourceCode/Property.h | UTF-8 | 1,566 | 3.015625 | 3 | [] | no_license | #pragma once
#include "nod/nod.hpp"
#include <functional>
class AlwaysUpdatePolicy
{
public:
template <typename T>
bool operator()( const T&, const T& ) const
{
return true;
}
};
template <typename T, typename UpdatePolicy = std::not_equal_to<T>>
class Property
{
public:
Property() = default;
Property( T value )
: m_value( std::move( value ) )
{
}
const T& get() const
{
return m_value;
}
T& get()
{
return m_value;
}
const T& operator()() const
{
return get();
}
T& operator()()
{
return get();
}
void set( const T& value )
{
if ( UpdatePolicy()( m_value, value ) )
{
m_value = value;
changed( m_value );
}
}
void operator()( const T& value )
{
set( value );
}
void set( T&& value )
{
if ( UpdatePolicy()( m_value, value ) )
{
m_value = std::forward<T>( value );
changed( m_value );
}
}
void operator()( T&& value )
{
set( std::forward<T>( value ) );
}
nod::unsafe_signal<void( const T& newValue )> changed;
nod::connection onChanged( std::function<void( const T& )> callback )
{
return changed.connect( std::move( callback ) );
}
nod::connection onChangedAndNow( std::function<void( const T& )> callback )
{
callback( m_value );
return changed.connect( std::move( callback ) );
}
private:
T m_value{};
};
| true |
4627bfbda2ea68a239b912e3d418154c85c7c19e | C++ | green-fox-academy/hrumocsaba | /week-03/day-3/petrolstation/main.cpp | UTF-8 | 347 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include "Car.h"
#include "Station.h"
#include <vector>
#include <string>
using namespace std;
int main() {
Car car1;
Station fill;
do{
for (int i = 0; i < car1._capacity-car1._gasamount ; ++i) {
car1.fill();
fill.fill();
}
}while (!car1.isFull());
return 0;
} | true |
f03eaae5ed241919ad59a6ff5276e7f22f871108 | C++ | 2464599943/PAT | /A1078/main.cpp | UTF-8 | 1,325 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
#define inf 100000000
using namespace std;
bool ifprime(int num){
if(num<=1)return false;
else{
int sqr=(int)sqrt(1.0*num);
for(int i=2;i<=sqr;i++){
if(num%i==0)return false;
}
}
return true;
}
int findnum(int Msize){
for(int i=Msize;i<inf;i++){
if(ifprime(i))return i;
}
return -1;
}
int main()
{
int Msize,N;
scanf("%d%d",&Msize,&N);
int sizee=findnum(Msize);
if(sizee!=-1){
int *a=new int[sizee];
for(int i=0;i<sizee;i++){
a[i]=inf;
}
int b;
int countt=0,key;
for(int i=0;i<N;i++){
scanf("%d",&b);
countt=0;
key=b%sizee;
while(countt<sizee&&a[key]!=inf){
countt++;
key=(b+countt*countt)%sizee;
}
if(countt>=sizee){
if(i<N-1)
printf("- ");
else
printf("-");
}else{
a[key]=b;
if(i<N-1)
printf("%d ",key);
else
printf("%d",key);
}
}
}
return 0;
}
| true |
aca2aa6165f9d9958d575fc9c02d28b66eed928a | C++ | H2odude/C-867 | /C-867/roster.h | UTF-8 | 1,192 | 2.546875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <stdio.h>
#include <string>
#include "degree.h"
#include "networkStudent.h"
#include "securityStudent.h"
#include "softwareStudent.h"
#include <vector>
using namespace std;
const string studentData[5] =
{
"A1,John,Smith,John1989@gm ail.com,20,30,35,40,SECURITY",
"A2,Suzan,Erickson,Erickson_1990@gmailcom,19,50,30,40,NETWORK",
"A3,Jack,Napoli,The_lawyer99yahoo.com,19,20,40,33,SOFTWARE",
"A4,Erin,Black,Erin.black@comcast.net,22,50,58,40,SECURITY",
"A5,Eric,Waters,ewate10@wgu.edu,25,15,25,30,SOFTWARE"
};
class Roster {
public:
student* GetClassRoster(int Index) {
return classRosterArray[Index];
}
//student* classRosterArray[5] = { nullptr, nullptr, nullptr, nullptr, nullptr };
void add(string studentID, string firstName, string lastName, string emailAddress, int age, int daysInCourse1, int daysInCourse2, int daysInCourse3, degree Major);
void remove(string studentID);
void printAll();
void printDaysInCourse(string studentID);
void printInvalidEmails();
void printByDegreeProgram(degree Major);
int Index = 0;
Roster();
~Roster();
private:
student* classRosterArray[5] = { nullptr, nullptr, nullptr, nullptr, nullptr };
}; | true |
2035b36b8deceab0bfa53bd80a8de8a9eec176ad | C++ | GabeG1/CS_2336_Project_4 | /include/Order.h | UTF-8 | 1,275 | 2.9375 | 3 | [] | no_license | //Gabriel Goldstein
//gjg180000
#ifndef ORDER_H
#define ORDER_H
#include "TheaterSeat.h"
class Order
{
public:
Order();
Order(int, TheaterSeat*, int, int, int);
virtual ~Order();
void setNextOrder(Order* ord)
{
nextOrder = ord;
}
Order* getNextOrder()
{
return this->nextOrder;
}
int getAdultTickets()
{
return numAdultTickets;
}
int getChildTickets()
{
return numChildTickets;
}
int getSeniorTickets()
{
return numSeniorTickets;
}
void setNumAdults(int a)
{
numAdultTickets = a;
}
void setNumChildren(int c)
{
numChildTickets = c;
}
void setSeniorTickets(int s)
{
numSeniorTickets = s;
}
int getAuditorium()
{
return auditorium;
}
TheaterSeat* getStartingSeat()
{
return startingSeat;
}
void deleteTicket(TheaterSeat ts);
void increaseOrder(TheaterSeat, int, int, int);
bool exists(TheaterSeat);
protected:
private:
int auditorium;
TheaterSeat* startingSeat;
int numAdultTickets;
int numChildTickets;
int numSeniorTickets;
Order * nextOrder;
};
#endif // ORDER_H
| true |
ec13955a4ab36db6d40a959560383c1ac535ba07 | C++ | RanjeetKumarMaurya/Data-Structures-and-Algorithms-Using-CPP | /Array/missingNumberInArray.cpp | UTF-8 | 858 | 3.296875 | 3 | [] | no_license | // { Driver Code Starts
// Initial template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function template for C++
class Solution{
public:
int MissingNumber(vector<int>& array, int n) {
// Your code goes here
int sum = (n * (n + 1)) / 2;
int temp = 0;
for(int i = 0; i < n - 1; ++i){
temp = temp + array[i];
//printf("%d ", array[i]);
}
return sum - temp;;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<int> array(n - 1);
for (int i = 0; i < n - 1; ++i) cin >> array[i];
Solution obj;
cout << obj.MissingNumber(array, n) << "\n";
}
return 0;
} // } Driver Code Ends | true |
ba1ee2e8e411533dd89267bf357756e759d21275 | C++ | ThinkerBoy/soccerbot | /soccer/src/control/math/Geometry.cpp | UTF-8 | 74,728 | 3.484375 | 3 | [] | no_license | #include <assert.h>
#include <stdio.h>
#include "Geometry.h"
using namespace std;
namespace SIM {
Point2D testPoint;
/*! This function returns the sign of a give double.
1 is positive, -1 is negative
\param d first parameter
\return the sign of this double */
int Sign(double d) {
return (d > 0) ? 1 : -1;
}
/*! This function returns the maximum of two given doubles.
\param d1 first parameter
\param d2 second parameter
\return the maximum of these two parameters */
double max(double d1, double d2) {
return (d1 > d2) ? d1 : d2;
}
/*! This function returns the minimum of two given doubles.
\param d1 first parameter
\param d2 second parameter
\return the minimum of these two parameters */
double min(double d1, double d2) {
return (d1 < d2) ? d1 : d2;
}
/*! This function returns the square of the given double.
\param d1 parameter to be squared
\return the square of this parameter */
double square(double d1) {
return d1 * d1;
}
/** Crop the value to within minval, maxval */
double crop(double val, double minval, double maxval) {
return minmax(minval, val, maxval);
}
/**
* Function that finds the minmax of three values, x, min limit and
* max limit...
*/
double minmax(double minx, double x, double maxx) {
return ( min(max(minx, x), maxx));
}
/**
* Function that finds the minmax of three Point2Ds, x, min limit and
* max limit...
*/
Point2D minmax(Point2D minP, Point2D P, Point2D maxP) {
Point2D tempP(0, 0);
tempP.setX(minmax(minP.getX(), P.getX(), maxP.getX()));
tempP.setY(minmax(minP.getY(), P.getY(), maxP.getY()));
return tempP;
}
bool notANumber(double num) {
return ( isnan(num));
}
/*! This function returns the rounded value of a give double.
\param d is the input number which is double
\returns the rounded value of d which is an int */
int Round(double d) {
if (!finite(d))
return (int) (-1.0E10);
else if (d > 0)
return (int) (d + 0.5);
else
return (int) (d - 0.5);
}
int Floor(double d) {
if (!finite(d))
return (int) (-1.0E10);
else
return (int) d;
}
/*! This function converts an angle in radians to the corresponding angle in
degrees.
\param ang an angle in radians
\return the corresponding angle in degrees */
// TODO: daniel commented because including vecposition
AngDeg Rad2Deg(AngRad ang) {
return ( ang * RAD_T_DEG);
}
/*! This function converts an angle in degrees to the corresponding angle in
radians.
\param ang an angle in degrees
\return the corresponding angle in radians */
// TODO: daniel commented because including vecpositoin
AngRad Deg2Rad(AngDeg ang) {
return ( ang * DEG_T_RAD);
}
/*! This function returns a boolean value which indicates whether the value
'ang' (from interval [-2PI..2PI] lies in the interval [angMin..angMax].
Examples: isAngInInterval( -100, 4, -150) returns false
isAngInInterval( 45, 4, -150) returns true
\param ang angle that should be checked
\param angMin minimum angle in interval
\param angMax maximum angle in interval
\return boolean indicating whether ang lies in [angMin..angMax] */
bool isAngInInterval(AngRad ang, AngRad angMin, AngRad angMax) {
// convert all angles to interval 0..TWOPI
if ((ang + TWOPI) < TWOPI) ang += TWOPI;
if ((angMin + TWOPI) < TWOPI) angMin += TWOPI;
if ((angMax + TWOPI) < TWOPI) angMax += TWOPI;
if (angMin < angMax)
return angMin < ang && ang < angMax;
else
return !(angMax < ang && ang < angMin);
}
/*! This method returns the bisector (average) of two angles. It deals
with the boundary problem, thus when 'angMin' equals 170 and 'angMax'
equals -100, -145 is returned.
\param angMin minimum angle [-pi,pi]
\param angMax maximum angle [-pi,pi]
\return average of angMin and angMax. */
AngRad getBisectorTwoAngles(AngRad angMin, AngRad angMax) {
// separate sine and cosine part to circumvent boundary problem
return normalizeAngle(atan2((sin(angMin) + sin(angMax)) / 2.0,
(cos(angMin) + cos(angMax)) / 2.0));
}
/*****************/
/* Class Point2D */
/*****************/
Point2D::Point2D(double xx, double yy, CoordSystemT cs) {
setPoint(xx, yy, cs);
}
/*! Overloaded version of unary minus operator for Point2Ds. It returns the
negative Point2D, i.e. both the x- and y-coordinates are multiplied by
-1. The current Point2D itself is left unchanged.
\return a negated version of the current Point2D */
Point2D Point2D::operator-() const {
return ( Point2D(-x, -y));
}
/*! Overloaded version of the binary plus operator for adding a given double
value to a Point2D. The double value is added to both the x- and
y-coordinates of the current Point2D. The current Point2D itself is
left unchanged.
\param d a double value which has to be added to both the x- and
y-coordinates of the current Point2D
\return the result of adding the given double value to the current
Point2D */
Point2D Point2D::operator+(const double &d) const {
return ( Point2D(x + d, y + d));
}
/*! Overloaded version of the binary plus operator for Point2Ds. It returns
the sum of the current Point2D and the given Point2D by adding their
x- and y-coordinates. The Point2Ds themselves are left unchanged.
\param p a Point2D
\return the sum of the current Point2D and the given Point2D */
Point2D Point2D::operator+(const Point2D &p) const {
return ( Point2D(x + p.x, y + p.y));
}
/*! Overloaded version of the binary minus operator for subtracting a given
double value from a Point2D. The double value is subtracted from both
the x- and y-coordinates of the current Point2D. The current Point2D
itself is left unchanged.
\param d a double value which has to be subtracted from both the x- and
y-coordinates of the current Point2D
\return the result of subtracting the given double value from the current
Point2D */
Point2D Point2D::operator-(const double &d) const {
return ( Point2D(x - d, y - d));
}
/*! Overloaded version of the binary minus operator for Point2Ds. It returns
the difference between the current Point2D and the given Point2D by
subtracting their x- and y-coordinates. The Point2Ds themselves are left
unchanged.
\param p a Point2D
\return the difference between the current Point2D and the given
Point2D */
Point2D Point2D::operator-(const Point2D &p) const {
return ( Point2D(x - p.x, y - p.y));
}
/*! Overloaded version of the multiplication operator for multiplying a
Point2D by a given double value. Both the x- and y-coordinates of the
current Point2D are multiplied by this value. The current Point2D
itself is left unchanged.
\param d the multiplication factor
\return the result of multiplying the current Point2D by the given
double value */
Point2D Point2D::operator*(const double &d) const {
return ( Point2D(x * d, y * d));
}
/*! Overloaded version of the multiplication operator for Point2Ds. It
returns the product of the current Point2D and the given Point2D by
multiplying their x- and y-coordinates. The Point2Ds themselves are left
unchanged.
\param p a Point2D
\return the product of the current Point2D and the given Point2D */
Point2D Point2D::operator*(const Point2D &p) const {
return ( Point2D(x * p.x, y * p.y));
}
/*! Overloaded version of the division operator for dividing a Point2D by a
given double value. Both the x- and y-coordinates of the current Point2D
are divided by this value. The current Point2D itself is left unchanged.
\param d the division factor
\return the result of dividing the current Point2D by the given double
value */
Point2D Point2D::operator/(const double &d) const {
return ( Point2D(x / d, y / d));
}
/*! Overloaded version of the division operator for Point2Ds. It returns the
quotient of the current Point2D and the given Point2D by dividing
their x- and y-coordinates. The Point2Ds themselves are left unchanged.
\param p a Point2D
\return the quotient of the current Point2D and the given Point2D */
Point2D Point2D::operator/(const Point2D &p) const {
return ( Point2D(x / p.x, y / p.y));
}
/*! Overloaded version of the assignment operator for assigning a given double
value to both the x- and y-coordinates of the current Point2D. This
changes the current Point2D itself.
\param d a double value which has to be assigned to both the x- and
y-coordinates of the current Point2D */
void Point2D::operator=(const double &d) {
x = d;
y = d;
}
/*! Overloaded version of the sum-assignment operator for Point2Ds. It
returns the sum of the current Point2D and the given Point2D by
adding their x- and y-coordinates. This changes the current Point2D
itself.
\param p a Point2D which has to be added to the current Point2D */
void Point2D::operator+=(const Point2D &p) {
x += p.x;
y += p.y;
}
/*! Overloaded version of the sum-assignment operator for adding a given double
value to a Point2D. The double value is added to both the x- and
y-coordinates of the current Point2D. This changes the current
Point2D itself.
\param d a double value which has to be added to both the x- and
y-coordinates of the current Point2D */
void Point2D::operator+=(const double &d) {
x += d;
y += d;
}
/*! Overloaded version of the difference-assignment operator for Point2Ds.
It returns the difference between the current Point2D and the given
Point2D by subtracting their x- and y-coordinates. This changes the
current Point2D itself.
\param p a Point2D which has to be subtracted from the current
Point2D */
void Point2D::operator-=(const Point2D &p) {
x -= p.x;
y -= p.y;
}
/*! Overloaded version of the difference-assignment operator for subtracting a
given double value from a Point2D. The double value is subtracted from
both the x- and y-coordinates of the current Point2D. This changes the
current Point2D itself.
\param d a double value which has to be subtracted from both the x- and
y-coordinates of the current Point2D */
void Point2D::operator-=(const double &d) {
x -= d;
y -= d;
}
/*! Overloaded version of the multiplication-assignment operator for
Point2Ds. It returns the product of the current Point2D and the
given Point2D by multiplying their x- and y-coordinates. This changes
the current Point2D itself.
\param p a Point2D by which the current Point2D has to be
multiplied */
void Point2D::operator*=(const Point2D &p) {
x *= p.x;
y *= p.y;
}
/*! Overloaded version of the multiplication-assignment operator for multiplying
a Point2D by a given double value. Both the x- and y-coordinates of the
current Point2D are multiplied by this value. This changes the current
Point2D itself.
\param d a double value by which both the x- and y-coordinates of the
current Point2D have to be multiplied */
void Point2D::operator*=(const double &d) {
x *= d;
y *= d;
}
/*! Overloaded version of the division-assignment operator for Point2Ds. It
returns the quotient of the current Point2D and the given Point2D by
dividing their x- and y-coordinates. This changes the current Point2D
itself.
\param p a Point2D by which the current Point2D has to be divided */
void Point2D::operator/=(const Point2D &p) {
x /= p.x;
y /= p.y;
}
/*! Overloaded version of the division-assignment operator for dividing a
Point2D by a given double value. Both the x- and y-coordinates of the
current Point2D are divided by this value. This changes the current
Point2D itself.
\param d a double value by which both the x- and y-coordinates of the
current Point2D have to be divided */
void Point2D::operator/=(const double &d) {
x /= d;
y /= d;
}
/*! Overloaded version of the inequality operator for Point2Ds. It
determines whether the current Point2D is unequal to the given
Point2D by comparing their x- and y-coordinates.
\param p a Point2D
\return true when either the x- or y-coordinates of the given Point2D
and the current Point2D are different; false otherwise */
bool Point2D::operator!=(const Point2D &p) const {
return ( (x != p.x) || (y != p.y));
}
/*! Overloaded version of the inequality operator for comparing a Point2D to
a double value. It determines whether either the x- or y-coordinate of the
current Point2D is unequal to the given double value.
\param d a double value with which both the x- and y-coordinates of the
current Point2D have to be compared.
\return true when either the x- or y-coordinate of the current Point2D
is unequal to the given double value; false otherwise */
bool Point2D::operator!=(const double &d) const {
return ( (x != d) || (y != d));
}
/*! Overloaded version of the equality operator for Point2Ds. It determines
whether the current Point2D is equal to the given Point2D by
comparing their x- and y-coordinates.
\param p a Point2D
\return true when both the x- and y-coordinates of the given Point2D and
the current Point2D are equal; false otherwise */
bool Point2D::operator==(const Point2D &p) const {
return ( (x == p.x) && (y == p.y));
}
/*! Overloaded version of the equality operator for comparing a Point2D to a
double value. It determines whether both the x- and y-coordinates of the
current Point2D are equal to the given double value.
\param d a double value with which both the x- and y-coordinates of the
current Point2D have to be compared.
\return true when both the x- and y-coordinates of the current Point2D
are equal to the given double value; false otherwise */
bool Point2D::operator==(const double &d) const {
return ( (x == d) && (y == d));
}
/*! Overloaded version of the C++ output operator for output.
\param os output stream to which information should be written
\param p a Point2D which must be printed
\return output stream containing (x,y) */
ostream& operator<<(ostream &os, Point2D p) {
return ( os << "( " << p.x << ", " << p.y << " )");
}
/*! String coversion for Lua
\return string representation of point */
const char* Point2D::__str__() {
static char buffer[ 128 ];
sprintf(buffer, "( %f, %f )", x, y);
return buffer;
}
/*! Set method for the x-coordinate of the current Point2D.
\param x a double value representing a new x-coordinate */
void Point2D::setX(double xx) {
x = xx;
}
/*! Get method for the x-coordinate of the current Point2D.
\return the x-coordinate of the current Point2D */
double Point2D::getX() const {
return ( x);
}
/*! Set method for the y-coordinate of the current Point2D.
\param y a double value representing a new y-coordinate */
void Point2D::setY(double yy) {
y = yy;
}
/*! Get method for the y-coordinate of the current Point2D.
\return the y-coordinate of the current Point2D */
double Point2D::getY() const {
return ( y);
}
/*! This method (re)sets the coordinates of the current Point2D. The given
coordinates can either be polar or Cartesian coordinates. This is indicated
by the value of the third argument.
\param x a double value indicating either a new Cartesian x-coordinate when
cs=CARTESIAN or a new polar r-coordinate (distance) when cs=POLAR
\param y a double value indicating either a new Cartesian y-coordinate when
cs=CARTESIAN or a new polar phi-coordinate (angle) when cs=POLAR
\param cs a CoordSystemT indicating whether x and y denote cartesian
coordinates or polar coordinates */
void Point2D::setPoint(double xx, double yy, CoordSystemT cs) {
if (cs == CARTESIAN) {
x = xx;
y = yy;
} else
*this = getPointFromPolar(xx, yy);
}
/*! This method determines the distance between the current Point2D and a
given Point2D. This is equal to the magnitude (length) of the vector
connecting the two positions which is the difference vector between them.
\param p a Vecposition
\return the distance between the current Point2D and the given
Point2D */
double Point2D::getDistanceTo(const Point2D p) const {
return ( (*this -p).getMagnitude());
}
/*! This method determines the bearing to a point from the current Point2D
assuming the given orientation.
\param p a Vecposition
\param o an orientation
\return the bearing from the current Point2D to the point p
Point2D */
AngRad Point2D::getBearingTo(const Point2D p, const AngRad o) const {
Point2D relPoint = p - * this;
AngRad absDir = relPoint.getDirection();
return normalizeAngle(absDir - o);
}
/*! Gets the angle from this point to point p
\param p a Vecposition
\return the angle from the current Point2D to the point p
Point2D */
AngRad Point2D::getAngleTo(const Point2D p) const {
Point2D relPoint = p - * this;
return normalizeAngle(relPoint.getDirection());
}
/*! This method adjusts the coordinates of the current Point2D in such a way
that the magnitude of the corresponding vector equals the double value which
is supplied as an argument. It thus scales the vector to a given length by
multiplying both the x- and y-coordinates by the quotient of the argument
and the current magnitude. This changes the Point2D itself.
\param d a double value representing a new magnitude
\return the result of scaling the vector corresponding with the current
Point2D to the given magnitude thus yielding a different Point2D */
Point2D Point2D::setMagnitude(double d) {
if (getMagnitude() > EPSILON)
(*this) *= (d / getMagnitude());
return ( *this);
}
/*! This method determines the magnitude (length) of the vector corresponding
with the current Point2D using the formula of Pythagoras.
\return the length of the vector corresponding with the current
Point2D */
double Point2D::getMagnitude() const {
return ( sqrt(x * x + y * y));
}
/*! This method determines the direction of the vector corresponding with the
current Point2D (the phi-coordinate in polar representation) using the
arc tangent function. Note that the signs of x and y have to be taken into
account in order to determine the correct quadrant.
\return the direction in degrees of the vector corresponding with the
current Point2D */
AngRad Point2D::getDirection() const {
return ( atan2(y, x));
}
/*! This method determines whether the current Point2D is in front of a
given Point2D, i.e. whether the x-coordinate of the current Point2D
is larger than the x-coordinate of the given Point2D.
\param p a Point2D to which the current Point2D must be compared
\return true when the current Point2D is in front of the given
Point2D; false otherwise */
bool Point2D::isInFrontOf(const Point2D &p) const {
return ( y > p.getY());
}
/*! This method determines whether the x-coordinate of the current Point2D
is in front of (i.e. larger than) a given double value.
\param y a double value to which the current x-coordinate must be compared
\return true when the current x-coordinate is in front of the given value;
false otherwise */
bool Point2D::isInFrontOf(const double &yy) const {
return ( y > yy);
}
/*! This method determines whether the current Point2D is behind a given
Point2D, i.e. whether the x-coordinate of the current Point2D is
smaller than the x-coordinate of the given Point2D.
\param p a Point2D to which the current Point2D must be compared
\return true when the current Point2D is behind the given Point2D;
false otherwise */
bool Point2D::isBehind(const Point2D &p) const {
return ( y < p.getY());
}
/*! This method determines whether the x-coordinate of the current Point2D
is behind (i.e. smaller than) a given double value.
\param y a double value to which the current x-coordinate must be compared
\return true when the current x-coordinate is behind the given value; false
otherwise */
bool Point2D::isBehind(const double &yy) const {
return ( y < yy);
}
/*! This method determines whether the current Point2D is to the left of a
given Point2D, i.e. whether the y-coordinate of the current Point2D
is smaller than the y-coordinate of the given Point2D.
\param p a Point2D to which the current Point2D must be compared
\return true when the current Point2D is to the left of the given
Point2D; false otherwise */
bool Point2D::isLeftOf(const Point2D &p) const {
return ( x < p.getX());
}
/*! This method determines whether the y-coordinate of the current Point2D
is to the left of (i.e. smaller than) a given double value.
\param x a double value to which the current y-coordinate must be compared
\return true when the current y-coordinate is to the left of the given
value; false otherwise */
bool Point2D::isLeftOf(const double &xx) const {
return ( x < xx);
}
/*! This method determines whether the current Point2D is to the right of a
given Point2D, i.e. whether the y-coordinate of the current Point2D
is larger than the y-coordinate of the given Point2D.
\param p a Point2D to which the current Point2D must be compared
\return true when the current Point2D is to the right of the given
Point2D; false otherwise */
bool Point2D::isRightOf(const Point2D &p) const {
return ( x > p.getX());
}
/*! This method determines whether the y-coordinate of the current Point2D
is to the right of (i.e. larger than) a given double value.
\param x a double value to which the current y-coordinate must be compared
\return true when the current y-coordinate is to the right of the given
value; false otherwise */
bool Point2D::isRightOf(const double &xx) const {
return ( x > xx);
}
/*! This method determines whether the current Point2D is in between two
given Point2Ds when looking in the x-direction, i.e. whether the current
Point2D is in front of the first argument and behind the second.
\param p1 a Point2D to which the current Point2D must be compared
\param p2 a Point2D to which the current Point2D must be compared
\return true when the current Point2D is in between the two given
Point2Ds when looking in the x-direction; false otherwise */
bool Point2D::isBetweenX(const Point2D &p1, const Point2D &p2) const {
return ( isRightOf(p1) && isLeftOf(p2));
}
/*! This method determines whether the x-coordinate of the current Point2D
is in between two given double values, i.e. whether the x-coordinate of the
current Point2D is in front of the first argument and behind the second.
\param x1 a double value to which the current x-coordinate must be compared
\param x2 a double value to which the current x-coordinate must be compared
\return true when the current x-coordinate is in between the two given
values; false otherwise */
bool Point2D::isBetweenX(const double &x1, const double &x2) const {
return ( isRightOf(x1) && isLeftOf(x2));
}
/*! This method determines whether the current Point2D is in between two
given Point2Ds when looking in the y-direction, i.e. whether the current
Point2D is to the right of the first argument and to the left of the
second.
\param p1 a Point2D to which the current Point2D must be compared
\param p2 a Point2D to which the current Point2D must be compared
\return true when the current Point2D is in between the two given
Point2Ds when looking in the y-direction; false otherwise */
bool Point2D::isBetweenY(const Point2D &p1, const Point2D &p2) const {
return ( isInFrontOf(p1) && isBehind(p2));
}
/*! This method determines whether the y-coordinate of the current Point2D
is in between two given double values, i.e. whether the y-coordinate of the
current Point2D is to the right of the first argument and to the left
of the second.
\param y1 a double value to which the current y-coordinate must be compared
\param y2 a double value to which the current y-coordinate must be compared
\return true when the current y-coordinate is in between the two given
values; false otherwise */
bool Point2D::isBetweenY(const double &y1, const double &y2) const {
return ( isInFrontOf(y1) && isBehind(y2));
}
/**
* Mohan::Function returns true if the current Point2D lies in between
* (in terms of the x coordinate) the Point2Ds sent in as arguments -
* the two inputs need not be arranged in increasing order of
* x-coordinates...
*/
bool Point2D::pointIsBetweenX(const Point2D &p1, const Point2D &p2) const {
return ( (isRightOf(p1) && isLeftOf(p2)) ||
(isLeftOf(p1) && isRightOf(p2)));
}
/**
* Mohan::Function returns true if the current Point2D lies in between
* (in terms of the y coordinate) the Point2Ds sent in as arguments -
* the two inputs need not be arranged in increasing order of
* y-coordinates...
*/
bool Point2D::pointIsBetweenY(const Point2D &p1, const Point2D &p2) const {
return ( (isInFrontOf(p1) && isBehind(p2)) ||
(isBehind(p1) && isInFrontOf(p2)));
}
/**
* Function returns true iff the input point is in between the two
* points provided as input. ORDER IS IMPORTANT => the test point is
* checked for being greater than the first point and lesser than the
* second point...
*/
bool Point2D::isBetweenTwoPoints(const Point2D &p1,
const Point2D &p2) const {
return ( x >= p1.x && x <= p2.x &&
y >= p1.y && y <= p2.y);
}
/*! This method normalizes a Point2D by setting the magnitude of the
corresponding vector to 1. This thus changes the Point2D itself.
\return the result of normalizing the current Point2D thus yielding a
different Point2D */
Point2D Point2D::normalize() {
return ( setMagnitude(1.0));
}
/*! This method rotates the vector corresponding to the current Point2D over
a given angle thereby changing the current Point2D itself. This is done
by calculating the polar coordinates of the current Point2D and adding
the given angle to the phi-coordinate in the polar representation. The polar
coordinates are then converted back to Cartesian coordinates to obtain the
desired result.
\param ang an angle in degrees over which the vector corresponding to the
current Point2D must be rotated
\return the result of rotating the vector corresponding to the current
Point2D over the given angle thus yielding a different Point2D */
Point2D Point2D::rotate(AngRad ang) {
// determine the polar representation of the current Point2D
double dMag = this->getMagnitude();
double dNewDir = this->getDirection() + ang; // add rotation angle to phi
setPoint(dMag, dNewDir, POLAR); // convert back to Cartesian
return ( *this);
}
/*! This method converts the coordinates of the current Point2D (which are
represented in an global coordinate system with the origin at (0,0)) into
relative coordinates in a different coordinate system (e.g. relative to a
player). The new coordinate system is defined by the arguments to the
method. The relative coordinates are now obtained by aligning the relative
coordinate system with the global coordinate system using a translation to
make both origins coincide followed by a rotation to align the axes.
\param origin the origin of the relative coordinate frame
\param ang the angle between the world frame and the relative frame
(reasoning from the world frame)
\return the result of converting the current global Point2D into a
relative Point2D */
Point2D Point2D::globalToRelative(Point2D origin, AngRad ang) {
// convert global coordinates into relative coordinates by aligning relative
// frame and world frame. First perform translation to make origins of both
// frames coincide. Then perform rotation to make axes of both frames coincide
// (use negative angle since you rotate relative frame to world frame).
Point2D retVal(x, y);
retVal -= origin;
return ( retVal.rotate(-ang));
}
/*! This method converts the coordinates of the current Point2D (which are
represented in a relative coordinate system) into global coordinates in
the world frame (with origin at (0,0)). The relative coordinate system is
defined by the arguments to the method. The global coordinates are now
obtained by aligning the world frame with the relative frame using a
rotation to align the axes followed by a translation to make both origins
coincide.
\param origin the origin of the relative coordinate frame
\param ang the angle between the world frame and the relative frame
(reasoning from the world frame)
\return the result of converting the current relative Point2D into an
global Point2D */
Point2D Point2D::relativeToGlobal(Point2D origin, AngRad ang) {
// convert relative coordinates into global coordinates by aligning world
// frame and relative frame. First perform rotation to make axes of both
// frames coincide (use positive angle since you rotate world frame to
// relative frame). Then perform translation to make origins of both frames
// coincide.
Point2D retVal(x, y);
retVal.rotate(ang);
retVal += origin;
return retVal;
}
/*! This method returns a Point2D that lies somewhere on the vector between
the current Point2D and a given Point2D. The desired position is
specified by a given fraction of this vector (e.g. 0.5 means exactly in
the middle of the vector). The current Point2D itself is left unchanged.
\param p a Point2D which defines the vector to the current Point2D
\param frac double representing the fraction of the connecting vector at
which the desired Point2D lies.
\return the Point2D that lies at fraction frac on the vector
connecting p and the current Point2D */
Point2D Point2D::getPointOnLineFraction(Point2D &p,
double frac) {
return ( (*this) * (1.0 - frac) + (p * frac));
}
/*! This method returns the angle between the
vectors made by this point and the two given points.
\param p1 Point2D of first vector endpoint
\param p2 Point2D of second vector endpoint
\return the angle in degrees between the vectors
(this - p1) and (this - p2) */
AngRad Point2D::getAngleBetweenPoints(const Point2D &p1,
const Point2D &p2) {
Point2D v1 = *this -p1;
Point2D v2 = *this -p2;
Point2D vec = v1 * v2;
double dotProduct = vec.x + vec.y;
return fabs(normalizeAngle(acos(dotProduct / v1.getMagnitude()
/ v2.getMagnitude())));
}
/*! This method converts a polar representation of a Point2D into a
Cartesian representation.
\param mag a double representing the polar r-coordinate, i.e. the distance
from the point to the origin
\param ang the angle that the polar vector makes with the x-axis, i.e. the
polar phi-coordinate
\return the result of converting the given polar representation into a
Cartesian representation thus yielding a Cartesian Point2D */
Point2D Point2D::getPointFromPolar(double mag, AngRad ang) {
// cos(phi) = x/r <=> x = r*cos(phi); sin(phi) = y/r <=> y = r*sin(phi)
return ( Point2D(mag * cos(ang), mag * sin(ang)));
}
/*! This method normalizes an angle. This means that the resulting angle lies
between -2PI and 2PI degrees.
\param ang the angle which must be normalized
\return the result of normalizing the given angle */
AngRad normalizeAngle(AngRad ang) {
while (ang > M_PI) ang -= TWOPI;
while (ang < -M_PI) ang += TWOPI;
return ( ang);
}
/*****************/
/* Class Point3D */
/*****************/
Point3D::Point3D(double xx, double yy, double zz, CoordSystemT cs) {
setPoint(xx, yy, zz, cs);
}
/*! Overloaded version of unary minus operator for Point3Ds. It returns the
negative Point3D, i.e. both the x- and y-coordinates are multiplied by
-1. The current Point3D itself is left unchanged.
\return a negated version of the current Point3D */
Point3D Point3D::operator-() const {
return ( Point3D(-x, -y, -z));
}
/*! Overloaded version of the binary plus operator for adding a given double
value to a Point3D. The double value is added to both the x- and
y-coordinates of the current Point3D. The current Point3D itself is
left unchanged.
\param d a double value which has to be added to both the x- and
y-coordinates of the current Point3D
\return the result of adding the given double value to the current
Point3D */
Point3D Point3D::operator+(const double &d) const {
return ( Point3D(x + d, y + d, z + d));
}
/*! Overloaded version of the binary plus operator for Point3Ds. It returns
the sum of the current Point3D and the given Point3D by adding their
x- and y-coordinates. The Point3Ds themselves are left unchanged.
\param p a Point3D
\return the sum of the current Point3D and the given Point3D */
Point3D Point3D::operator+(const Point3D &p) const {
return ( Point3D(x + p.x, y + p.y, z + p.z));
}
/*! Overloaded version of the binary minus operator for subtracting a given
double value from a Point3D. The double value is subtracted from both
the x- and y-coordinates of the current Point3D. The current Point3D
itself is left unchanged.
\param d a double value which has to be subtracted from both the x- and
y-coordinates of the current Point3D
\return the result of subtracting the given double value from the current
Point3D */
Point3D Point3D::operator-(const double &d) const {
return ( Point3D(x - d, y - d, z - d));
}
/*! Overloaded version of the binary minus operator for Point3Ds. It returns
the difference between the current Point3D and the given Point3D by
subtracting their x- and y-coordinates. The Point3Ds themselves are left
unchanged.
\param p a Point3D
\return the difference between the current Point3D and the given
Point3D */
Point3D Point3D::operator-(const Point3D &p) const {
return ( Point3D(x - p.x, y - p.y, z - p.z));
}
/*! Overloaded version of the multiplication operator for multiplying a
Point3D by a given double value. Both the x- and y-coordinates of the
current Point3D are multiplied by this value. The current Point3D
itself is left unchanged.
\param d the multiplication factor
\return the result of multiplying the current Point3D by the given
double value */
Point3D Point3D::operator*(const double &d) const {
return ( Point3D(x * d, y * d, y * z));
}
/*! Overloaded version of the multiplication operator for Point3Ds. It
returns the product of the current Point3D and the given Point3D by
multiplying their x- and y-coordinates. The Point3Ds themselves are left
unchanged.
\param p a Point3D
\return the product of the current Point3D and the given Point3D */
Point3D Point3D::operator*(const Point3D &p) const {
return ( Point3D(x * p.x, y * p.y, z * p.z));
}
/*! Overloaded version of the division operator for dividing a Point3D by a
given double value. Both the x- and y-coordinates of the current Point3D
are divided by this value. The current Point3D itself is left unchanged.
\param d the division factor
\return the result of dividing the current Point3D by the given double
value */
Point3D Point3D::operator/(const double &d) const {
return ( Point3D(x / d, y / d, z / d));
}
/*! Overloaded version of the division operator for Point3Ds. It returns the
quotient of the current Point3D and the given Point3D by dividing
their x- and y-coordinates. The Point3Ds themselves are left unchanged.
\param p a Point3D
\return the quotient of the current Point3D and the given Point3D */
Point3D Point3D::operator/(const Point3D &p) const {
return ( Point3D(x / p.x, y / p.y, z / p.z));
}
/*! Overloaded version of the assignment operator for assigning a given double
value to both the x- and y-coordinates of the current Point3D. This
changes the current Point3D itself.
\param d a double value which has to be assigned to both the x- and
y-coordinates of the current Point3D */
void Point3D::operator=(const double &d) {
x = d;
y = d;
z = d;
}
/*! Overloaded version of the sum-assignment operator for Point3Ds. It
returns the sum of the current Point3D and the given Point3D by
adding their x- and y-coordinates. This changes the current Point3D
itself.
\param p a Point3D which has to be added to the current Point3D */
void Point3D::operator+=(const Point3D &p) {
x += p.x;
y += p.y;
z += p.z;
}
/*! Overloaded version of the sum-assignment operator for adding a given double
value to a Point3D. The double value is added to both the x- and
y-coordinates of the current Point3D. This changes the current
Point3D itself.
\param d a double value which has to be added to both the x- and
y-coordinates of the current Point3D */
void Point3D::operator+=(const double &d) {
x += d;
y += d;
z += d;
}
/*! Overloaded version of the difference-assignment operator for Point3Ds.
It returns the difference between the current Point3D and the given
Point3D by subtracting their x- and y-coordinates. This changes the
current Point3D itself.
\param p a Point3D which has to be subtracted from the current
Point3D */
void Point3D::operator-=(const Point3D &p) {
x -= p.x;
y -= p.y;
z -= p.z;
}
/*! Overloaded version of the difference-assignment operator for subtracting a
given double value from a Point3D. The double value is subtracted from
both the x- and y-coordinates of the current Point3D. This changes the
current Point3D itself.
\param d a double value which has to be subtracted from both the x- and
y-coordinates of the current Point3D */
void Point3D::operator-=(const double &d) {
x -= d;
y -= d;
z -= d;
}
/*! Overloaded version of the multiplication-assignment operator for
Point3Ds. It returns the product of the current Point3D and the
given Point3D by multiplying their x- and y-coordinates. This changes
the current Point3D itself.
\param p a Point3D by which the current Point3D has to be
multiplied */
void Point3D::operator*=(const Point3D &p) {
x *= p.x;
y *= p.y;
z *= p.z;
}
/*! Overloaded version of the multiplication-assignment operator for multiplying
a Point3D by a given double value. Both the x- and y-coordinates of the
current Point3D are multiplied by this value. This changes the current
Point3D itself.
\param d a double value by which both the x- and y-coordinates of the
current Point3D have to be multiplied */
void Point3D::operator*=(const double &d) {
x *= d;
y *= d;
z *= d;
}
/*! Overloaded version of the division-assignment operator for Point3Ds. It
returns the quotient of the current Point3D and the given Point3D by
dividing their x- and y-coordinates. This changes the current Point3D
itself.
\param p a Point3D by which the current Point3D has to be divided */
void Point3D::operator/=(const Point3D &p) {
x /= p.x;
y /= p.y;
z /= p.z;
}
/*! Overloaded version of the division-assignment operator for dividing a
Point3D by a given double value. Both the x- and y-coordinates of the
current Point3D are divided by this value. This changes the current
Point3D itself.
\param d a double value by which both the x- and y-coordinates of the
current Point3D have to be divided */
void Point3D::operator/=(const double &d) {
x /= d;
y /= d;
z /= d;
}
/*! Overloaded version of the inequality operator for Point3Ds. It
determines whether the current Point3D is unequal to the given
Point3D by comparing their x- and y-coordinates.
\param p a Point3D
\return true when either the x- ory-coordinates of the given Point3D
and the current Point3D are different; false otherwise */
bool Point3D::operator!=(const Point3D &p) const {
return ( (x != p.x) || (y != p.y) || (z != p.z));
}
/*! Overloaded version of the inequality operator for comparing a Point3D to
a double value. It determines whether either the x- or y-coordinate of the
current Point3D is unequal to the given double value.
\param d a double value with which both the x- and y-coordinates of the
current Point3D have to be compared.
\return true when either the x- or y-coordinate of the current Point3D
is unequal to the given double value; false otherwise */
bool Point3D::operator!=(const double &d) const {
return ( (x != d) || (y != d) || (z != d));
}
/*! Overloaded version of the equality operator for Point3Ds. It determines
whether the current Point3D is equal to the given Point3D by
comparing their x- and y-coordinates.
\param p a Point3D
\return true when both the x- and y-coordinates of the given Point3D and
the current Point3D are equal; false otherwise */
bool Point3D::operator==(const Point3D &p) const {
return ( (x == p.x) && (y == p.y) && (z == p.z));
}
/*! Overloaded version of the equality operator for comparing a Point3D to a
double value. It determines whether both the x- and y-coordinates of the
current Point3D are equal to the given double value.
\param d a double value with which both the x- and y-coordinates of the
current Point3D have to be compared.
\return true when both the x- and y-coordinates of the current Point3D
are equal to the given double value; false otherwise */
bool Point3D::operator==(const double &d) const {
return ( (x == d) && (y == d) && (z == d));
}
/*! Overloaded version of the C++ output operator for output.
\param os output stream to which information should be written
\param p a Point3D which must be printed
\return output stream containing (x,y) */
ostream& operator<<(ostream &os, Point3D p) {
return ( os << "( " << p.x << ", " << p.y << ", " << p.z << " )");
}
/*! String coversion for Lua
\return string representation of point */
const char* Point3D::__str__() {
static char buffer[ 128 ];
sprintf(buffer, "( %f, %f, %f )", x, y, z);
return buffer;
}
/*! Set method for the x-coordinate of the current Point3D.
\param x a double value representing a new x-coordinate */
void Point3D::setX(double xx) {
x = xx;
}
/*! Get method for the x-coordinate of the current Point3D.
\return the x-coordinate of the current Point3D */
double Point3D::getX() const {
return ( x);
}
/*! Set method for the y-coordinate of the current Point3D.
\param y a double value representing a new y-coordinate */
void Point3D::setY(double yy) {
y = yy;
}
/*! Get method for the y-coordinate of the current Point3D.
\return the y-coordinate of the current Point3D */
double Point3D::getY() const {
return ( y);
}
/*! Set method for the z-coordinate of the current Point3D.
\param z a double value representing a new z-coordinate */
void Point3D::setZ(double zz) {
z = zz;
}
/*! Get method for the z-coordinate of the current Point3D.
\return the z-coordinate of the current Point3D */
double Point3D::getZ() const {
return ( z);
}
/*! This method (re)sets the coordinates of the current Point3D. The given
coordinates can either be polar or Cartesian coordinates. This is indicated
by the value of the third argument.
\param x a double value indicating either a new Cartesian x-coordinate when
cs=CARTESIAN or a new polar r-coordinate (distance) when cs=POLAR
\param y a double value indicating either a new Cartesian y-coordinate when
cs=CARTESIAN or a new polar phi-coordinate (angle) when cs=POLAR
\param cs a CoordSystemT indicating whether x and y denote cartesian
coordinates or polar coordinates */
void Point3D::setPoint(double xx, double yy, double zz, CoordSystemT cs) {
if (cs == CARTESIAN) {
x = xx;
y = yy;
z = zz;
}//
//else
// *this = getPointFromPolar( xx, yy );
}
/*******************/
/* Class Rectangle */
/*******************/
/*! This is the constructor of a Rectangle. Two points will be given. The
order does not matter as long as two opposite points are given (left
top and right bottom or right top and left bottom).
\param p1 first point that defines corner of rectangle
\param p2 second point that defines other corner of rectangle
\return rectangle with 'p1' and 'p2' as opposite corners. */
Rectangle::Rectangle(Point2D p1, Point2D p2) {
setRectanglePoints(p1, p2);
}
/*! Overloaded version of the C++ output operator for output.
\param os output stream to which information should be written
\param r a Rectangle which must be printed
\return output stream containing rectangle endpoints */
ostream& operator<<(ostream &os, Rectangle r) {
return ( os << "[" << r.m_pTopLeft << ", " << r.m_pBottomRight << "]");
}
/*! Overloaded version of unary minus operator for Rectangles. It returns the
negative Rectangle, i.e. it is rotated 180 degrees around the origin.
The current Rectangle itself is left unchanged.
\return a negated version of the current Rectangle */
Rectangle Rectangle::operator-() const {
return ( Rectangle(-m_pBottomRight, -m_pTopLeft));
}
/*! This method sets the upper left and right bottom point of the current
rectangle.
\param p1 first point that defines corner of rectangle
\param p2 second point that defines other corner of rectangle */
void Rectangle::setRectanglePoints(Point2D p1, Point2D p2) {
m_pTopLeft.setX(min(p1.getX(), p2.getX()));
m_pTopLeft.setY(max(p1.getY(), p2.getY()));
m_pBottomRight.setX(max(p1.getX(), p2.getX()));
m_pBottomRight.setY(min(p1.getY(), p2.getY()));
}
/*! This method determines whether the given position lies inside the current
rectangle.
\param p position which is checked whether it lies in rectangle
\return true when 'p' lies in the rectangle, false otherwise */
bool Rectangle::isInside(Point2D p) const {
return p.isBetweenX(m_pTopLeft.getX(), m_pBottomRight.getX()) &&
p.isBetweenY(m_pBottomRight.getY(), m_pTopLeft.getY());
}
/*! This method sets the top left position of the rectangle
\param p new top left position of the rectangle
\return true when update was successful */
void Rectangle::setTopLeft(Point2D p) {
m_pTopLeft = p;
}
/*! This method returns the top left position of the rectangle
\return top left position of the rectangle */
Point2D Rectangle::getTopLeft() const {
return m_pTopLeft;
}
/*! This method sets the right bottom position of the rectangle
\param p new right bottom position of the rectangle
\return true when update was succesfull */
void Rectangle::setBottomRight(Point2D p) {
m_pBottomRight = p;
}
/*! This method returns the right bottom position of the rectangle
\return top right bottom of the rectangle */
Point2D Rectangle::getBottomRight() const {
return m_pBottomRight;
}
/*! This method returns the left bottom position of the rectangle
\return top left bottom of the rectangle */
Point2D Rectangle::getBottomLeft() const {
return Point2D(m_pTopLeft.getX(), m_pBottomRight.getY());
}
/*! This method returns the right top position of the rectangle
\return top right top of the rectangle */
Point2D Rectangle::getTopRight() const {
return Point2D(m_pBottomRight.getX(), m_pTopLeft.getY());
}
Point2D Rectangle::getCenter() const {
return ( (m_pBottomRight + m_pTopLeft) / 2);
}
Point2D Rectangle::getPosOutside() const {
return getTopRight() + 1;
}
double Rectangle::getWidth() const {
return ( m_pBottomRight - m_pTopLeft).getX();
}
double Rectangle::getLength() const {
return ( m_pTopLeft - m_pBottomRight).getY();
}
double Rectangle::getDiagonalLength() const {
return m_pTopLeft.getDistanceTo(m_pBottomRight);
}
double Rectangle::getLeft() const {
return m_pTopLeft.getX();
}
double Rectangle::getRight() const {
return m_pBottomRight.getX();
}
double Rectangle::getTop() const {
return m_pTopLeft.getY();
}
double Rectangle::getBottom() const {
return m_pBottomRight.getY();
}
/****************/
/* Class Line2D */
/****************/
Line2D::Line2D() {
m_a = 0;
m_b = 0;
m_c = 0;
isLineSegment = false;
}
/*! This constructor creates a line by given the three coefficents of the line.
A line is specified by the formula ay + bx + c = 0.
\param a a coefficients of the line
\param b b coefficients of the line
\param c c coefficients of the line */
Line2D::Line2D(double a, double b, double c) {
m_a = a;
m_b = b;
m_c = c;
isLineSegment = false;
}
/*! This constructor creates a line given two points.
\param p1 first point
\param p2 second point */
Line2D::Line2D(const Point2D& p1, const Point2D& p2) {
/*// Changing to a different (and I think better formula) MQ 16/10/2009
m_a = p1.getY() - p2.getY();
m_b = p2.getX() - p1.getX();
m_c = p2.getY()*p1.getX() - p2.getX()*p1.getY();
//normailse a,b,c
double denom=sqrt(pow(m_a,2)+pow(m_b,2));
m_a=m_a/denom;
m_b=m_b/denom;
m_c=m_c/denom;
center = (p1 + p2) / 2;
*/
// 1*y + bx + c = 0 => y = -bx - c
// with -b the direction coefficient (or slope)
// and c = - y - bx
m_a = 1.0;
double dTemp = p2.getX() - p1.getX(); // determine the slope
if (fabs(dTemp) < EPSILON) {
// ay + bx + c = 0 with vertical slope=> a = 0, b = 1
m_a = 0.0;
m_b = 1.0;
} else {
// y = (-b)x -c with -b the slope of the line
m_a = 1.0;
m_b = -(p2.getY() - p1.getY()) / dTemp;
}
// ay + bx + c = 0 ==> c = -a*y - b*x
m_c = -m_a * p2.getY() - m_b * p2.getX();
center = (p1 + p2) / 2;
//normailse a,b,c
double denom = sqrt(pow(m_a, 2) + pow(m_b, 2));
m_a = m_a / denom;
m_b = m_b / denom;
m_c = m_c / denom;
isLineSegment = true;
start = Point2D(p1.getX(), p1.getY());
end = Point2D(p2.getX(), p2.getY());
center = (p1 + p2) / 2;
}
/*! This constructor creates a line given a position and an angle.
\param p position through which the line passes
\param ang direction of the line */
Line2D::Line2D(const Point2D& p, const AngRad& ang) {
// calculate point somewhat further in direction 'angle' and make
// line from these two points.
*this = Line2D(p, p + Point2D(100, ang, POLAR));
isLineSegment = false;
}
Line2D Line2D::operator-() const {
return Line2D(m_a, m_b, -m_c);
}
/*! Overloaded version of the C++ output operator for output.
\param os output stream to which information should be written
\param l a Line2D which must be printed
\return output stream containing line equation */
ostream& operator<<(ostream &os, Line2D l) {
return ( os << l.m_a << "y + " << l.m_b << "x + " << l.m_c << " = 0");
}
/*! This method returns the intersection point between the current Line and
the specified line.
\param line line with which the intersection should be calculated.
\return Point2D position that is the intersection point. */
Point2D Line2D::getIntersection(Line2D line) const {
Point2D p;
double x, y;
if (getSlope() == line.getSlope()) // lines are parallel, no intersection
{
return p;
}
if (m_a == 0) // bx + c = 0 and a2*y + b2*x + c2 = 0 ==> x = -c/b
{ // calculate x using the current line
x = -m_c / m_b; // and calculate the y using the second line
y = line.getYGivenX(x);
} else if (line.getACoefficient() == 0) { // ay + bx + c = 0 and b2*x + c2 = 0 ==> x = -c2/b2
x = -line.getCCoefficient() / line.getBCoefficient(); // calculate x using
y = getYGivenX(x); // 2nd line and calculate y using current line
}// ay + bx + c = 0 and a2y + b2*x + c2 = 0
// y = (-b2/a2)x - c2/a2
// bx = -a*y - c => bx = -a*(-b2/a2)x -a*(-c2/a2) - c ==>
// ==> a2*bx = a*b2*x + a*c2 - a2*c ==> x = (a*c2 - a2*c)/(a2*b - a*b2)
// calculate x using the above formula and the y using the current line
else {
x = (m_a * line.getCCoefficient() - line.getACoefficient() * m_c) /
(line.getACoefficient() * m_b - m_a * line.getBCoefficient());
y = getYGivenX(x);
}
return Point2D(x, y);
}
/*! This method returns the orthogonal line to a Point2D. This is the
line between the specified position and the closest point on the
line to this position. \param p Point2D point with which tangent
line is calculated. \return Line line tangent to this position */
Line2D Line2D::getOrthogonalLine(Point2D p) const {
// ay + bx + c = 0 -> y = (-b/a)x + (-c/a)
// tangent: y = (a/b)*x + C1 -> by - ax + C2 = 0 => C2 = ax - by
// with p.y = y, p.x = x
return Line2D(m_b, -m_a, m_a * p.getX() - m_b * p.getY());
}
/**
* Mohan::This method returns the absolute value of the acute angle
* between the current line and the line sent in as input. \param
* line: line with which the angle is to be determined. \return
* Angrad: angle between the current line and input line...
*/
AngRad Line2D::getMyAngleWith(Line2D line) const {
double ang = 0;
double m1, m2;
// In our case we shall never have a case with a line that is
// parallel to the y-axis but I am checking for that as a
// matter-of-fact...
// Both lines parallel to y-axis...
if (m_a <= EPSILON && line.getACoefficient() <= EPSILON) {
return ang;
}// Current line parallel to y-axis...
else if (fabs(m_a) <= EPSILON) {
ang = atan(fabs(line.getACoefficient() / line.getBCoefficient()));
return ang;
}// Input line parallel to y-axis...
else if (fabs(line.getACoefficient()) <= EPSILON) {
ang = atan(fabs(m_a / m_b));
return ang;
}// Neither line parallel to the y-axis...
else {
m1 = -m_b / m_a;
m2 = -line.getBCoefficient() / line.getACoefficient();
ang = atan(fabs(m2 - m1) / (1 + m1 * m2));
return fabs(ang);
}
}
/**
* Mohan::This method returns the value of the normalized angle
* between the current line and the line sent in as input. \param
* line: line with which the angle is to be determined. \return
* Angrad: angle between the current line and input line...
*/
AngRad Line2D::getAngleToLine(Line2D line) const {
double ang = 0;
double m1, m2;
// In our case we shall never have a case with a line that is
// parallel to the y-axis but I am checking for that as a
// matter-of-fact...
// Both lines parallel to y-axis...
if (m_a <= EPSILON && line.getACoefficient() <= EPSILON) {
return ang;
}// Current line parallel to y-axis...
else if (fabs(m_a) <= EPSILON) {
ang = atan(fabs(line.getACoefficient() / line.getBCoefficient()));
return normalizeAngle(ang);
}// Input line parallel to y-axis...
else if (fabs(line.getACoefficient()) <= EPSILON) {
ang = atan(fabs(m_a / m_b));
return normalizeAngle(ang);
}// Neither line parallel to the y-axis...
else {
m1 = -m_b / m_a;
m2 = -line.getBCoefficient() / line.getACoefficient();
ang = atan(fabs(m2 - m1) / (1 + m1 * m2));
return normalizeAngle(ang);
}
}
/**
* Mohan::This method returns the intersection point between the
* current Line and the specified line. \param line line with which
* the intersection should be calculated. \return Point2D position
* that is the intersection point. */
Point2D Line2D::getMyIntersection(Line2D line) const {
Point2D p(0, 0);
double x, y;
double SLOPE_DIFF = EPSILON * 10;
double y_num = m_b * line.getCCoefficient() - line.getBCoefficient() * m_c;
double denom = m_a * line.getBCoefficient() - line.getACoefficient() * m_b;
// If the two lines are parallel, return the zero vector as the
// intersection point...
if (fabs(denom) <= SLOPE_DIFF) {
return p;
}
double x_num = line.getACoefficient() * m_c - m_a * line.getCCoefficient();
x = x_num / denom;
y = y_num / denom;
return Point2D(x, y);
}
/*! This method returns the closest point on a line to a given position.
\param p point to which closest point should be determined
\return Point2D closest point on line to 'p'. */
Point2D Line2D::getPointOnLineClosestTo(Point2D p) const {
Line2D l2 = getOrthogonalLine(p); // get tangent line
return getMyIntersection(l2); // and intersection between the two lines
}
///*! This method returns the closest point on a line segment to a given position.
// \param p point to which closest point should be determined
// \return Point2D closest point on line segment to 'p'. */
//Point2D Line2D::getPointOnLineSegClosestTo2( Point2D p ) const
//{
// double ab = start.getDistanceTo(p);
// double bc = p.getDistanceTo(end);
// double ac = start.getDistanceTo(end);
// if (abs(ab + bc - ac) < 0.001) {
// return p;
// } else {
// if (bc < ab) {
// return end;
// } else {
// return start;
// }
// }
//}
Point2D Line2D::getPointOnLineSegClosestTo(Point2D p) const {
double px = end.getX() - start.getX();
double py = end.getY() - start.getY();
double norm_squared = max(px * px + py*py, 1e-10);
double u = ((p.getX() - start.getX()) * px + (p.getY() - start.getY()) * py) / norm_squared;
if (u > 1)
u = 1;
else if (u < 0)
u = 0;
Point2D myPoint = Point2D(start.getX() + u*px, start.getY() + u * py);
return myPoint;
}
bool Line2D::intersectWithLineSeg(Line2D l, Point2D &pt) const {
double x1 = start.getX();
double x2 = end.getX();
double x3 = l.start.getX();
double x4 = l.end.getX();
double y1 = start.getY();
double y2 = end.getY();
double y3 = l.start.getY();
double y4 = l.end.getY();
double denom = (y4 - y3)*(x2 - x1) + (x4 - x3)*(y2 - y1);
if (fabs(denom) < 1e-10) {
return false;
}
double ua = ((x4 - x3)*(y1 - y3) - (y4 - y3)*(x1 - x3)) / denom;
double ub = ((x2 - x1)*(y1 - y3) + (y2 - y1)*(x1 - x3)) / denom;
if (0 < ua and ua < 1 and 0 < ub and ub < 1) {
pt.setX(x1 + ua * (x2 - x1));
pt.setY(y1 + ua * (y2 - y1));
return true;
} else {
return false;
}
}
Point2D Line2D::getStart() const {
return start;
}
Point2D Line2D::getEnd() const {
return end;
}
/*! This method returns the distance between a specified position and the
closest point on the given line.
\param p position to which distance should be calculated
\return double indicating the distance to the line. */
double Line2D::getDistanceToPoint(Point2D p) const {
return p.getDistanceTo(getPointOnLineClosestTo(p));
}
/*! This method determines whether the projection of a point on the current line
lies between two other points ('point1' and 'point2') that lie on the same
line.
\param p point of which projection is checked.
\param p1 first point on line
\param p2 second point on line
\return true when projection of 'p' lies between 'point1' and 'point2'.*/
bool Line2D::isInBetween(Point2D p, Point2D p1, Point2D p2) const {
p = getPointOnLineClosestTo(p); // get closest point
double dDist = p1.getDistanceTo(p2); // get distance between 2 p
// if the distance from both points to the projection is smaller than this
// dist, the p lies in between.
return p.getDistanceTo(p1) <= dDist &&
p.getDistanceTo(p2) <= dDist;
}
/*! This method calculates the y coordinate given the x coordinate
\param x coordinate
\return y coordinate on this line */
double Line2D::getYGivenX(double x) const {
if (m_a == 0) {
cerr << "(Line2D::getYGivenX) Cannot calculate Y coordinate: ";
cerr << endl;
return 0;
}
// ay + bx + c = 0 ==> ay = -(b*x + c)/a
return -(m_b * x + m_c) / m_a;
}
/*! This method calculates the x coordinate given the y coordinate
\param y coordinate
\return x coordinate on this line */
double Line2D::getXGivenY(double y) const {
if (m_b == 0) {
cerr << "(Line2D::getXGivenY) Cannot calculate X coordinate\n";
return 0;
}
// ay + bx + c = 0 ==> bx = -(a*y + c)/a
return -(m_a * y + m_c) / m_b;
}
/*! This method creates a line given two points.
\param p1 first point
\param p2 second point
\return line that passes through the two specified points. */
Line2D Line2D::makeLineFromTwoPoints(Point2D p1, Point2D p2) {
return Line2D(p1, p2);
}
/*! This method creates a line given a position and an angle.
\param p position through which the line passes
\param ang direction
of the line.
\return line that goes through position 'p' with angle 'ang'. */
Line2D Line2D::makeLineFromPositionAndAngle(Point2D p, AngRad ang) {
return Line2D(p, ang);
}
/*! This method returns the a coefficient from the line ay + bx + c = 0.
\return a coefficient of the line. */
double Line2D::getACoefficient() const {
return m_a;
}
/*! This method returns the b coefficient from the line ay + bx + c = 0.
\return b coefficient of the line. */
double Line2D::getBCoefficient() const {
return m_b;
}
/*! This method returns the c coefficient from the line ay + bx + c = 0.
\return c coefficient of the line. */
double Line2D::getCCoefficient() const {
return m_c;
}
/*! This method returns the slope of the line. \return m the slope of
the line. */
double Line2D::getSlope() const {
if (m_a == 0) {
cerr << "(Line2D:getSlope): divide by zero\n";
return 1000;
}
return -m_b / m_a;
}
/*! This method returns the y-intercept of the line.
\return b the y-intercept of the line. */
double Line2D::getYIntercept() const {
if (m_a == 0) {
return -m_c;
}
return -m_c / m_a;
}
/*! This method returns the x-intercept of the line.
\return the x-intercept of the line. */
double Line2D::getXIntercept() const {
if (m_b == 0) {
return -m_c;
}
return -m_c / m_b;
}
Point2D Line2D::getCenter() const {
return center;
}
/****************/
/* Class Circle */
/****************/
/*! This is the constructor of a circle.
\param pCenter first point that defines the center of circle
\param radius the radius of the circle
\return circle with p as center and radius as radius*/
Circle::Circle(const Point2D& pCenter, double radius) {
setCircle(pCenter, radius);
}
/*! This is the constructor of a circle which initializes a circle with a
radius of zero. */
Circle::Circle() {
setCircle(Point2D(-1000.0, -1000.0), 0);
}
/*! Overloaded version of the C++ output operator for output.
\param os output stream to which information should be written
\param c a Circle which must be printed
\return output stream containing center and radius */
ostream& operator<<(ostream &os, Circle c) {
return ( os << "c: " << c.m_pCenter << ", r: " << c.m_radius);
}
/*! String coversion for Lua
\return string representation of circle */
const char* Circle::__str__() {
static char buffer[ 128 ];
sprintf(buffer, "c: %s, r: %f ", m_pCenter.__str__(), m_radius);
return buffer;
}
/*! This method sets the values of the circle.
\param pCenter new center of the circle
\param radius new radius of the circle
( > 0 )
\return bool indicating whether radius was set */
bool Circle::setCircle(const Point2D& pCenter, double radius) {
setCenter(pCenter);
return setRadius(radius);
}
/*! This method sets the radius of the circle.
\param radius new radius of the circle ( > 0 )
\return bool indicating whether radius was set */
bool Circle::setRadius(double radius) {
if (radius > 0) {
m_radius = radius;
return true;
} else {
m_radius = 0.0;
return false;
}
}
/*! This method returns the radius of the circle.
\return radius of the circle */
double Circle::getRadius() const {
return m_radius;
}
/*! This method sets the center of the circle.
\param pCenter new center of the circle
\return bool indicating whether center was set */
void Circle::setCenter(const Point2D& pCenter) {
m_pCenter = pCenter;
}
/*! This method returns the center of the circle.
\return center of the circle */
Point2D Circle::getCenter() const {
return m_pCenter;
}
/*! This method returns the circumference of the circle.
\return circumference of the circle */
double Circle::getCircumference() const {
return 2.0 * M_PI * getRadius();
}
/*! This method returns the area inside the circle.
\return area inside the circle */
double Circle::getArea() const {
return M_PI * getRadius() * getRadius();
}
/*! This method returns a boolean that indicates whether 'p' is located inside
the circle.
\param pCenter position of which should be checked whether it is located in the
circle
\return bool indicating whether p lies inside the circle */
bool Circle::isInside(const Point2D& pCenter) const {
return m_pCenter.getDistanceTo(pCenter) < getRadius();
}
/*! This method returns the two possible intersection points between two
circles. This method returns the number of solutions that were found.
\param c circle with which intersection should be found
\param p1 will be filled with first solution
\param p2 will be filled with second solution
\return number of solutions. */
int Circle::getIntersectionPoints(Circle c, Point2D *p1, Point2D *p2) const {
double x0, y0, r0;
double x1, y1, r1;
x0 = getCenter().getX();
y0 = getCenter().getY();
r0 = getRadius();
x1 = c.getCenter().getX();
y1 = c.getCenter().getY();
r1 = c.getRadius();
double d, dx, dy, h, a, x, y, p2_x, p2_y;
// first calculate distance between two centers circles P0 and P1.
dx = x1 - x0;
dy = y1 - y0;
d = sqrt(dx * dx + dy * dy);
// normalize differences
dx /= d;
dy /= d;
// a is distance between p0 and point that is the intersection point P2
// that intersects P0-P1 and the line that crosses the two intersection
// points P3 and P4.
// Define two triangles: P0,P2,P3 and P1,P2,P3.
// with distances a, h, r0 and b, h, r1 with d = a + b
// We know a^2 + h^2 = r0^2 and b^2 + h^2 = r1^2 which then gives
// a^2 + r1^2 - b^2 = r0^2 with d = a + b ==> a^2 + r1^2 - (d-a)^2 = r0^2
// ==> r0^2 + d^2 - r1^2 / 2*d
a = (r0 * r0 + d * d - r1 * r1) / (2.0 * d);
// h is then a^2 + h^2 = r0^2 ==> h = sqrt( r0^2 - a^2 )
double arg = r0 * r0 - a*a;
h = (arg > 0.0) ? sqrt(arg) : 0.0;
// First calculate P2
p2_x = x0 + a * dx;
p2_y = y0 + a * dy;
// and finally the two intersection points
x = p2_x - h * dy;
y = p2_y + h * dx;
p1->setPoint(x, y);
x = p2_x + h * dy;
y = p2_y - h * dx;
p2->setPoint(x, y);
return (arg < 0.0) ? 0 : ((arg == 0.0) ? 1 : 2);
}
/*! This method returns the size of the intersection area of two circles.
\param c circle with which intersection should be determined
\return size of the intersection area. */
double Circle::getIntersectionArea(Circle c) const {
Point2D p1, p2, p3;
double d, h, dArea;
AngRad ang;
d = getCenter().getDistanceTo(c.getCenter()); // dist between two centers
if (d > c.getRadius() + getRadius()) // larger than sum radii
return 0.0; // circles do not intersect
if (d <= fabs(c.getRadius() - getRadius())) { // one totally in the other
double dR = min(c.getRadius(), getRadius()); // return area smallest circle
return M_PI * dR*dR;
}
int iNrSol = getIntersectionPoints(c, &p1, &p2);
if (iNrSol != 2)
return 0.0;
// the intersection area of two circles can be divided into two segments:
// left and right of the line between the two intersection points p1 and p2.
// The outside area of each segment can be calculated by taking the part
// of the circle pie excluding the triangle from the center to the
// two intersection points.
// The pie equals pi*r^2 * rad(2*ang) / 2*pi = 0.5*rad(2*ang)*r^2 with ang
// the angle between the center c of the circle and one of the two
// intersection points. Thus the angle between c and p1 and c and p3 where
// p3 is the point that lies halfway between p1 and p2.
// This can be calculated using ang = asin( d / r ) with d the distance
// between p1 and p3 and r the radius of the circle.
// The area of the triangle is 2*0.5*h*d.
p3 = p1.getPointOnLineFraction(p2, 0.5);
d = p1.getDistanceTo(p3);
h = p3.getDistanceTo(getCenter());
ang = asin(d / getRadius());
dArea = ang * getRadius() * getRadius();
dArea = dArea - d*h;
// and now for the other segment the same story
h = p3.getDistanceTo(c.getCenter());
ang = asin(d / c.getRadius());
dArea = dArea + ang * c.getRadius() * c.getRadius();
dArea = dArea - d*h;
return dArea;
}
} // namespace SIM
| true |
181a9786f892014fe36438d88134953175f0c02b | C++ | jifmarais/meicem | /src/libraries/mesh/include/TriangleContainer.hpp | UTF-8 | 1,163 | 3.0625 | 3 | [] | no_license | #pragma once
#include <vector>
#include <limits>
#include "NodeContainer.hpp"
#include "Triangle.hpp"
class TriangleContainer
{
public:
typedef std::vector<double>::size_type SizeType;
static const SizeType invalidIndex = std::numeric_limits<SizeType>::max();
TriangleContainer(NodeContainer& container);
virtual ~TriangleContainer();
NodeContainer& getPointContainer() const;
SizeType add(Triangle t);
SizeType find(Triangle t) const;
SizeType find(SizeType i1, SizeType i2, SizeType i3) const;
const Triangle &at(SizeType index) const;
SizeType size() const;
bool hasCommonNode(SizeType index1, SizeType index2) const;
protected:
private:
NodeContainer& m_pointContainer;
std::vector<SizeType> m_node1;
std::vector<SizeType> m_node2;
std::vector<SizeType> m_node3;
std::vector<Triangle> m_triangleList;
double m_tolerance;
SizeType matchIndices(SizeType ii, SizeType i1, SizeType i2, SizeType i3) const;
};
| true |
ce3c0f5b24544e45442ca93fa3a873aff73a9d30 | C++ | confi-surya/pythonicPracto | /conditionCompleteion/src/common/communication/unittest/unix_sock.cpp | UTF-8 | 1,275 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "communication/communication.h"
int main(){
FILE *fp;
int s, len;
struct sockaddr_un saun;
//Open socket
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){
//OSDLOG(FATAL, "Unable to create socket");
// PASSERT(false, "Socket creation failed for health monitoring!");
std::cout << "failed to open socket" << std::endl;
}
saun.sun_family = AF_UNIX;
strcpy(saun.sun_path, "/root/hidden");
//Connect to server
len = sizeof(saun.sun_family) + strlen(saun.sun_path);
if (connect(s, (struct sockaddr *)&saun, len) < 0) {
//OSDLOG(FATAL, "Connection to server failed");
// PASSERT(false, "Connection to server failed for health monitoring!");
std::cout << "failed to connect to the server" << std::endl;
}
fp = fdopen(s, "r");
//Populate fd in object
uint64_t fd = fileno(fp);
Communication::SynchronousCommunication * com = new Communication::SynchronousCommunication(fd);
delete com;
std::cout << "deleted \n";
//Communication::SynchronousCommunication * com1 = new Communication::SynchronousCommunication(fd);
}
| true |
23672cc4d752b54d469d5fd8e989834c65ba7c9f | C++ | 2018hsridhar/Leetcode_Solutions | /leetcode_640.cpp | UTF-8 | 3,876 | 3.125 | 3 | [] | no_license | class Solution {
public:
string solveEquation(string equation) {
// std::regex rxSplit(std::string("\\") + "s+");
// std::OutputIterator output; // NOT all types are available in the std namespace!
// std::copy(std::sregex_token_iterator(std::begin(equation),std::end(equation),rxSplit,-1),
// std::sregex_token_iterator(), output);
// https://stackoverflow.com/questions/10058606/splitting-a-string-by-a-character
std::stringstream test(equation);
std::string segment;
std::vector<std::string> handSides;
while(std::getline(test, segment, '=')) {
handSides.push_back(segment);
}
std::pair<int,int> lhsCoeffs = getCoeffs(handSides.at(0));
std::pair<int,int> rhsCoeffs = getCoeffs(handSides.at(1));
if(lhsCoeffs.first == rhsCoeffs.first && lhsCoeffs.second == rhsCoeffs.second){
return "Infinite solutions";
} else if ( lhsCoeffs.first != 0 || rhsCoeffs.first != 0 ) {
// int -> string in C++
if(rhsCoeffs.first - lhsCoeffs.first == 0){
return "No solution";
}
int temp = ((lhsCoeffs.second - rhsCoeffs.second) / (rhsCoeffs.first - lhsCoeffs.first));
printf("temp = %d\n", temp);
return "x=" + to_string(temp);
} else {
return "No solution";
}
return "";
}
private:
pair<int,int> getCoeffs(std::string expr){
std::pair<int,int> coeffs; // can I default initialize this?
// sliding window, in the reverse, more helpful
// Only operations : no negations :-)
// We can do indexOf methods with `+` or `-` too?
int rPtr = expr.size() - 1;
int lPtr = expr.size() - 1;;
int n = expr.size();
while(lPtr >= 0){
if(expr.at(lPtr) == '+'){
// printf("rPtr = %d\n", rPtr);
if(expr.at(rPtr) == 'x'){
// printf("here\n lPtr = %d \t rPtr = %d\n", lPtr, rPtr);
if(lPtr == rPtr - 1){
coeffs.first += 1;
}
else if(rPtr > lPtr + 1) {
int coeff = stoi(expr.substr(lPtr+1,rPtr+1)); // string to a nint
// printf("coeff = %d\n", coeff);
coeffs.first += coeff;
}
} else {
int coeff = stoi(expr.substr(lPtr+1,rPtr)); // string to a nint
coeffs.second += coeff;
}
rPtr = lPtr - 1;
} else if ( expr.at(lPtr) == '-'){
// printf("lPtr = %d \t rPtr = %d\n", lPtr, rPtr);
if(expr.at(rPtr) == 'x'){
if(lPtr == rPtr - 1){
coeffs.first -= 1;
}
else if(rPtr > lPtr + 1) {
int coeff = stoi(expr.substr(lPtr+1,rPtr)); // string to a nint
coeffs.first -= coeff;
}
} else {
int coeff = stoi(expr.substr(lPtr+1,rPtr)); // string to a nint
coeffs.second -= coeff;
}
rPtr = lPtr - 1;
}
--lPtr;
}
if(rPtr >= 0){
if(expr.at(rPtr) == 'x'){
if(lPtr == rPtr - 1){
coeffs.first += 1;
} else if(rPtr > lPtr + 1) {
int coeff = stoi(expr.substr(lPtr+1,rPtr)); // string to a nint
coeffs.first += coeff;
}
} else {
int coeff = stoi(expr.substr(lPtr+1,rPtr+1)); // string to a nint
coeffs.second += coeff;
}
}
return coeffs;
}
};
| true |
c20fa9c89793bbf6cd8c60c4bfbbf42b586e822d | C++ | HALIP192/OOP_LAB | /lab6_7/student.cpp | UTF-8 | 579 | 3.03125 | 3 | [] | no_license | #include "student.h"
Student::Student()
: mark(0) { }
Student::Student(std::string f, std::string d, Sex s, const int& p)
: Person(f, d, s), mark(p) { }
Student::Student(std::string f, std::string d, std::string s, const int& p)
: Person(f, d, s), mark(p) { }
Student::Student(Student&& a) {
id = a.id;
fio = std::move(a.fio);
date = std::move(a.date);
sex = a.sex;
mark = a.mark;
}
std::string Student::Print() const {
return "Student " + fio + " " + date + " " + (sex == Sex::FEMALE ? "female" : "male") + " " + std::to_string(mark);
}
| true |
ea30f88efd16e4cbeba13025ff52125ccec69c96 | C++ | SoMa-Project/vision | /thirdparty/GeometricTools/WildMagic5/SampleGraphics/MorphFaces/CubicInterpolator.h | UTF-8 | 2,332 | 2.6875 | 3 | [
"BSD-2-Clause-Views"
] | permissive | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.1.0 (2010/04/14)
#ifndef CUBICINTERPOLATOR_H
#define CUBICINTERPOLATOR_H
#include "Wm5Memory.h"
#include "Wm5Tuple.h"
using namespace Wm5;
template <int N, typename Real>
class CubicInterpolator
{
public:
// Construction and destruction. A bool input is set to 'true' whenever
// the corresponding array was dynamically allocated and you want the
// class to own the array and deallocate it during class destruction.
// The inputs must be a strictly increasing sequence of numbers.
CubicInterpolator (int numSamples, Real* inputs, Tuple<N,Real>* outputs,
Tuple<N,Real>* tangents0, Tuple<N,Real>* tangents1, bool ownerInputs,
bool ownerOutputs, bool ownerTangents0, bool ownerTangents1);
CubicInterpolator (const std::string& filename);
~CubicInterpolator ();
// Member access.
inline int GetNumSamples () const;
inline const Real* GetInputs () const;
inline const Real* GetOutputs () const;
inline const Real* GetTangents0 () const;
inline const Real* GetTangents1 () const;
inline const Real GetMinInput () const;
inline const Real GetMaxInput () const;
// Evaluate the interpolator. The input is clamped to [min,max], where
// min = inputs[0] and max = inputs[numSamples-1].
Tuple<N,Real> operator() (Real input) const;
private:
// Support for constructors.
void Initialize ();
// Lookup on bounding keys.
void GetKeyInfo (Real input, Real& normInput, int& key) const;
// Constructor inputs.
int mNumSamples;
Real* mInputs;
Tuple<N,Real>* mOutputs;
Tuple<N,Real>* mTangents0;
Tuple<N,Real>* mTangents1;
bool mOwnerInputs, mOwnerOutputs, mOwnerTangents0, mOwnerTangents1;
// Support for key lookup and evaluation.
int mNumSamplesM1;
Real* mInvDeltas;
Tuple<N,Real>* mC0;
Tuple<N,Real>* mC1;
Tuple<N,Real>* mC2;
Tuple<N,Real>* mC3;
// For O(1) lookup on bounding keys.
mutable int mLastIndex;
};
#include "CubicInterpolator.inl"
#endif
| true |
fd81e13333ad513683f8ad0c6bfd487a089c3bb6 | C++ | Hikaru-4/SourceTree | /GameSources/StageObject.h | SHIFT_JIS | 403 | 2.765625 | 3 | [] | no_license | #pragma once
#include "stdafx.h"
namespace basecross {
class StageObject : public GameObject
{
std::wstring m_name; // IuWFNg̎ޖ
public:
enum Type
{
Block, Grass
};
public:
StageObject(const std::shared_ptr<Stage>& stage, const std::wstring& name)
: GameObject(stage), m_name(name)
{
}
const std::wstring& GetName() const
{
return m_name;
}
};
} | true |
155663155f55cb5d35294ba4c29e3071e97f6256 | C++ | GokulVSD/ScratchPad | /LeetCode/1080 - Insufficient Nodes in Root to Leaf Paths.cpp | UTF-8 | 1,050 | 3.4375 | 3 | [
"Unlicense"
] | permissive | // https://leetcode.com/problems/insufficient-nodes-in-root-to-leaf-paths/submissions/
// Simple recursive tree pruning. Leetcode annoyingly accesses root after execution, preventing me from being able to deallocate memory pointed by root.
class Solution {
public:
bool prune(TreeNode* cur, int sum, int limit){
if(cur->left == NULL && cur->right == NULL){
if(sum + cur->val < limit){
return true;
} else return false;
}
if(cur->left != NULL){
if(prune(cur->left, sum + cur->val, limit)){
cur->left = NULL;
}
}
if(cur->right != NULL){
if(prune(cur->right, sum + cur->val, limit)){
cur->right = NULL;
}
}
if(cur->left == NULL && cur->right == NULL){
return true;
} else return false;
}
TreeNode* sufficientSubset(TreeNode* root, int limit) {
if(prune(root, 0, limit)){
return NULL;
}
return root;
}
}; | true |
c9190eb163d9b3755781f96d33533d2e3352dc35 | C++ | rachit-geek/code-daily | /450dsa/Arrays/prob5.cpp | UTF-8 | 519 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void swap()
void rearrange(int arr[],int n)
{
int j=0;
for(int i=0;i<n;i++)
{
if(arr[i]<0)
{
if(i!=j)
{
swap(arr[i],arr[j]);
j++;
}
}
}
}
void print(int arr[],int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<' ';
}
}
int main()
{
int arr[]={5,-88,66,-57};
int arr_size=4;
rearrange(arr,arr_size);
print(arr,arr_size);
} | true |
ac6f2fff732ea2224e5f6020d243aa175b52ec62 | C++ | Sagar-2-99/Finding-all-the-index-where-element-is-present-using-Recursion | /main.cpp | UTF-8 | 750 | 3.5 | 4 | [] | no_license | #include <iostream>
using namespace std;
int findall(int b[],int a,int c,int x,int y)
{
if(a==0)
{
return x;
}
else if(b[0]==c)
{
cout<<"The element is at: "<<y-a<<endl;
return findall(b+1,a-1,c,x+1,y);
}
else
{
return findall(b+1,a-1,c,x,y);
}
}
int main()
{
int a;
cout<<"Enter the size of the array you want"<<endl;
cin>>a;
int b[a];
for(int i=0; i<a; i++)
{
cout<<"Enter the element for the index: "<<i<<endl;
cin>>b[i];
}
cout<<"Enter the element you want to search for: "<<endl;
int c;
cin>>c;
int x=0;
int d=findall(b,a,c,x,a);
if(d==0)
{
cout<<"Sorry element is not present"<<endl;
}
}
| true |
308d7d9accc3d4e830dd651a9cfc8057b8aa56d7 | C++ | rap2363/huffmancoding | /datastructures/BinaryEncoder.cpp | UTF-8 | 3,392 | 2.75 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include "../utilities.hpp"
#include "BinaryEncoder.hpp"
const unsigned NUM_CHAR_BITS = 8;
void BinaryEncoder::addBinarySequenceToCharacterBuffer(char* &char_buffer, const std::vector<bool> &bits, int &buffer_index, int &bit_index) {
unsigned char last_buffer_char = bit_index % NUM_CHAR_BITS == 0 ? 0 : char_buffer[buffer_index];
unsigned char char_to_write = last_buffer_char;
for (auto iter = bits.begin(); iter != bits.end(); iter++) {
char_to_write = char_to_write << 1;
bit_index++;
if (*iter) {
char_to_write += 0x01;
}
if (bit_index % NUM_CHAR_BITS == 0) {
char_buffer[buffer_index++] = char_to_write;
last_buffer_char = 0;
char_to_write = 0;
}
}
char_buffer[buffer_index] = char_to_write;
}
void BinaryEncoder::compressToBinary(std::ifstream &char_fs, const int bit_stream_size, std::ofstream &bin_fs, const std::map<char, const std::vector<bool> > &stc_map) {
if (!char_fs) {
std::cerr << "Could not open file to stream characters from!" << std::endl;
return;
}
unsigned header_byte = NUM_CHAR_BITS - bit_stream_size % NUM_CHAR_BITS;
header_byte = header_byte == 8 ? 0 : header_byte; // So we don't skip the last byte.
unsigned buffer_size = 1 + bit_stream_size / NUM_CHAR_BITS;
if (bit_stream_size % 8 != 0) {
buffer_size++; //Streams that aren't exact multiples of 8 need one more character.
}
char* char_buffer = new char[buffer_size];
int buffer_index = 0;
int bit_index = NUM_CHAR_BITS; // Set index to right after the header
char_buffer[buffer_index++] = header_byte;
char c;
while (char_fs.get(c)) {
if (stc_map.find(c) != stc_map.end()) {
addBinarySequenceToCharacterBuffer(char_buffer, stc_map.at(c), buffer_index, bit_index);
}
}
char_buffer[buffer_index] = char_buffer[buffer_index] << header_byte;
if (!bin_fs) {
std::cerr << "Could not open file to stream bits to!" << std::endl;
return;
}
bin_fs.write(char_buffer, sizeof(char)*buffer_size);
delete[] char_buffer;
}
void BinaryEncoder::decompressFromBinary(std::ifstream &bin_fs, std::ofstream &char_fs, const HBTNode* &huffman_root) {
if (!bin_fs) {
std::cerr << "Could not open file to decompress!" << std::endl;
return;
}
unsigned buffer_size = bin_fs.tellg();
int buffer_index = 0;
std::vector<char> char_buffer;
char c;
bool isHeader = true;
unsigned header_byte;
unsigned offset = 0;
bool direction;
const HBTNode* huffman_ptr = huffman_root;
while (bin_fs.get(c)) {
if (isHeader) {
header_byte = c;
isHeader = false;
continue;
}
if (++buffer_index == buffer_size) {
offset = header_byte;
}
for (int i = 1; i <= NUM_CHAR_BITS - offset; i++) {
bool direction = (c >> (NUM_CHAR_BITS - i)) % 2;
huffman_ptr = direction ? huffman_ptr -> getRight() : huffman_ptr -> getLeft();
if (huffman_ptr -> isLeaf()) {
char_buffer.push_back(huffman_ptr -> getSymbol());
huffman_ptr = huffman_root;
}
}
}
char_fs.write(&char_buffer[0], sizeof(char)*char_buffer.size());
} | true |
59f36e7d9f390fed2ab1001c7978d0f93e005b9c | C++ | Ukio-G/live | /World.cpp | UTF-8 | 4,736 | 2.90625 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include "include/World.h"
#include "include/Executing.h"
void World::fillVectices() {
int counter = 0;
for (int y = 0; y < Settings::height; ++y)
for (int x = 0; x < Settings::width; ++x)
vertices[counter++] = {((float)1.8*x/Settings::width) - 0.9f,-(float)1.8*y/Settings::height + 0.9f};
}
void World::fillColors() {
int counter = 0;
for (int x = 0; x < Settings::width; ++x)
for (int y = 0; y < Settings::height; ++y)
colors[counter++] = {0.0f,0.0f,0.0f};
}
void World::fillExecutables() {
for (int y = 0; y < Settings::height; ++y)
for (int x = 0; x < Settings::width; ++x)
executables[x][y] = nullptr;
}
void World::fillObjects() {
for (int y = 0; y < Settings::height; ++y)
for (int x = 0; x < Settings::width; ++x)
objects[x][y] = nullptr;
}
World::World() {
fillColors();
fillVectices();
fillExecutables();
fillObjects();
}
void World::setColor(int num, fColor color) {
colors[num] = color;
}
void World::setColor(int x, int y, fColor color) {
int num = y * Settings::width + x;
colors[num] = color;
}
void World::appendExecutable(int num) {
iPoint p = numToPoint(num);
appendExecutable(p, emptyAbilities);
}
void World::appendExecutable(iPoint & position) {
appendExecutable(position, emptyAbilities);
}
void World::appendExecutable(int num, Abilities_t abilities) {
iPoint p = numToPoint(num);
appendExecutable(p, abilities);
}
template<typename T>
void World::appendWorldObject(iPoint & position) {
}
template<>
void World::appendWorldObject<EnergySource>(iPoint & position) {
worldObjectsCount++;
EnergySource * energySource = energyPool->get();
energySource->position = position;
objects[position.x][position.y] = (BasicObject*)energySource;
colors[pointToNum(position)] = energySource->color;
}
void World::appendExecutable(iPoint &position, Abilities_t abilities) {
executableCount++;
Executable * executable = ePoolPtr->getMutated();
executable->position = position;
executable->color = fColor(abilities);
executables[position.x][position.y] = executable;
colors[pointToNum(position)] = executables[position.x][position.y]->color;
}
void World::appendExecutableRandomPosition(Abilities_t abilities, size_t count) {
for (size_t i = 0; i < count ; i++)
appendExecutableRandomPosition(abilities);
}
void World::appendExecutableRandomPosition(Abilities_t abilities) {
iPoint position = getRandomFreeCell();
appendExecutable(position, abilities);
}
size_t World::freeCells() {
return Settings::height * Settings::width - (getExecutablesCount() + getWorldObjectCount());
}
bool World::isPointFree(const iPoint & point) {
BasicObject * object = objects[point.x][point.y];
bool isObstructionObject = (object == nullptr) ? true : !object->isObstruction;
return ((executables[point.x][point.y] == nullptr) && isObstructionObject);
}
bool World::hasExecutable(const iPoint & point) {
return executables[point.x][point.y] != nullptr;
}
void World::removeExecutable(iPoint point) {
if (hasExecutable(point)) {
executables[point.x][point.y] = nullptr;
}
colors[pointToNum(point)] = {0.0,0.0,0.0};
executableCount--;
}
void World::makeMove(Executable *subject, iPoint offset)
{
if (offset.x == 0 && offset.y == 0) return;
if (subject == nullptr) return;
iPoint oldPosition = subject->position;
iPoint newPosition = oldPosition + offset;
if(newPosition.x >= (int)Settings::width) newPosition.x = 0;
else if(newPosition.x < 0) newPosition.x = Settings::width - 1;
if (newPosition.y >= (int)Settings::height) newPosition.y = 0;
else if(newPosition.y < 0) newPosition.y = Settings::height - 1;
if (!isPointFree(newPosition)) return;
subject->position = newPosition;
colors[pointToNum(newPosition)] = subject->color;
if(objects[oldPosition.x][oldPosition.y] == nullptr)
colors[pointToNum(oldPosition)] = {0.0,0.0,0.0};
else
colors[pointToNum(oldPosition)] = objects[oldPosition.x][oldPosition.y]->color;
executables[oldPosition.x][oldPosition.y] = nullptr;
executables[newPosition.x][newPosition.y] = subject;
}
inline iPoint World::getRandomFreeCell() noexcept {
if (freeCells() == 0) return {0,0};
iPoint result = randomPosition();
while (!isPointFree(result))
result = randomPosition();
return result;
}
inline size_t World::getExecutablesCount() const noexcept {
return executableCount;
}
inline size_t World::getWorldObjectCount() const noexcept {
return worldObjectsCount;
}
| true |
7fc11e1b7cb6f3681813505ea5756cd928750f17 | C++ | chih7/c_learning | /fs/DBManager.h | UTF-8 | 1,201 | 2.625 | 3 | [] | no_license | #ifndef DBMANAGER_H
#define DBMANAGER_H
#include<cstdlib>
#include <string>
#include "User.h"
using namespace std;
class DBManager
{
public:
static void fresh(); //界面头
static void Login(); //登录界面
void start(); //初始化数据(从文件中读入)显示首界面
static void User_Write(); //保存用户数据
static bool Judge_Password(string); //读密码
static void resetPassword(); //设置密码
static void ui_AddUser(); //增加用户
static void ui_DelUser(); //删除用户
static string isExisted_User(string); //判断用户是否存在并返回密码
static string name_User(string); //判断用户是否存在并返回密码
static void Login_User(); //登录界面
static void Home_User(); //登录后界面
static User Find_User(string); //找到用户
static void Delete_User(string); //删除用户
static void Add_User(User user); //增加用户
static void Resetpassword_User(); //改密码
};
#endif // DBMANAGER_H
| true |
138fd2b87a70e896e0b3e46987766e0ba459f606 | C++ | yiuyh/ACM | /二叉树.cpp | GB18030 | 1,649 | 3.390625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
#include<queue>
#define maxn 100000+10
using namespace std;
int arr[maxn] = {0};
// 鴢Ķı ԭ
// α
void lev_tra(int *arr){
queue<int> q;
q.push(1);
while(q.size()){
int cur = q.front();
cout << arr[cur] << " ";
q.pop();
if(arr[cur*2]) q.push(cur*2);
if(arr[cur*2+1]) q.push(cur*2+1);
}
}
//
void preorder(int *arr,int cur){
if(!arr[cur]) return;
cout << arr[cur] << " ";
preorder(arr, cur*2);
preorder(arr, cur*2+1);
}
//
void inorder(int *arr,int cur){
if(!arr[cur]) return;
inorder(arr, cur*2);
cout << arr[cur] << " ";
inorder(arr, cur*2+1);
}
//
void postorder(int *arr,int cur){
if(!arr[cur]) return;
postorder(arr, cur*2);
postorder(arr, cur*2+1);
cout << arr[cur] << " ";
}
int in_order[maxn], post_order[maxn], lch[maxn], rch[maxn];
//+=>(ÿڵ㴢IJͬȨֵĶ)
int build(int L1, int R1, int L2, int R2){// L1,R1Ϊ߽ L2,R2Ϊ߽
if(L1 > R2) return 0;
int root = post_order[R2];
int p = R1;
while(in_order[p] != root) p++;
int cnt = p - R1;
lch[root] = build(L1, p-1, L2, L2+cnt-1);
rch[root] = build(p+1, R1, L2+cnt, R2-1);
}
int main(){
int n;
while(cin >> n){
for(int i = 1; i <= n; i++) arr[i] = i;
lev_tra(arr);
cout << endl;
preorder(arr, 1);
cout << endl;
inorder(arr, 1);
cout << endl;
postorder(arr, 1);
}
return 0;
}
| true |
9ee1ebb14184d249e8099ff347ed5237a231525b | C++ | Hen0k/Camera-Wrapper-Class | /app.cpp | UTF-8 | 432 | 2.5625 | 3 | [] | no_license | #include "./cameraWrapper.cpp"
int main()
{
// Create the Singleton instance with defaul cam and 400X400 dimentions
Singleton *Sing = Sing->Instance(0, 1000, 1000);
// hold the return value from the openCam function
// inside a VideoCapture class variable
VideoCapture c = Sing->openCam();
for(int i=0;i<100;i++)
{
imshow("edges", Sing->readFrame(c));
if(waitKey(30) >= 0) break;
}
Sing->closeCam(c);
return 0;
} | true |
14f2f5f9245e8e419169000c4c545c4c930d26c2 | C++ | vslavik/poedit | /deps/boost/libs/multiprecision/test/bug12039.cpp | UTF-8 | 1,533 | 2.578125 | 3 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0"
] | permissive | ///////////////////////////////////////////////////////////////////////////////
// Copyright 2016 John Maddock. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/multiprecision/cpp_bin_float.hpp>
int main()
{
typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<256> > ext_float_t;
typedef boost::multiprecision::number<boost::multiprecision::backends::cpp_bin_float<2046> > long_ext_float_t;
ext_float_t x = 5e15;
x += 0.5;
ext_float_t x1 = x + 255.0 / (1 << 20); // + 2^-12 - eps
ext_float_t x2 = x + 257.0 / (1 << 20); // + 2^-12 + eps
double d1 = x1.convert_to<double>();
double d2 = x2.convert_to<double>();
std::cout << std::setprecision(18) << d1 << std::endl;
std::cout << std::setprecision(18) << d2 << std::endl;
x = 1e7 + 0.5;
x1 = x + ldexp(255.0, -38); // + 2^-30 - eps
x2 = x + ldexp(257.0, -38); // + 2^-30 + eps
float f1 = x1.convert_to<float>();
float f2 = x2.convert_to<float>();
std::cout << std::setprecision(9) << f1 << std::endl;
std::cout << std::setprecision(9) << f2 << std::endl;
long_ext_float_t lf(1);
lf += std::numeric_limits<long_ext_float_t>::epsilon();
lf += std::numeric_limits<float>::epsilon() / 2;
BOOST_ASSERT(lf != 1);
float f3 = lf.convert_to<float>();
std::cout << std::setprecision(9) << f3 << std::endl;
return (d1 == d2) && (f1 == f2) && (f3 != 1) ? 0 : 1;
}
| true |
bd49702f9dcff784a2369b97b13162ac6b02a1e5 | C++ | BansiddhaBirajdar/C- | /program3.cpp | UTF-8 | 434 | 3.625 | 4 | [] | no_license | // 3. Write a C++ program to check two given integers, and return true if one of them is 30 or if their sum is 30.
// Sample Input:
// 30, 0
// 25, 5
// 20, 30
// 20, 25
// Sample Output:
// 1
// 1
// 1
// 0
#include<bits/stdc++.h>
using namespace std;
bool check(int ino1,int ino2){
return (ino1==30)||(ino2==30)||(ino1+ino2==30)?true:false;
}
int main()
{
int ino1,ino2;
cin>>ino1>>ino2;
cout<<"Result :: "<<check(ino1,ino2);
} | true |
b0d5f40b22c2d89d8de1f199dd596862f5bacaad | C++ | EduardoReisDev/EstruturaDeDados | /BoubleSort/Caractere/Nome composto/nomecomposto.cpp | UTF-8 | 631 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main (){
int TAM=7, x=0, y=0;
string vetor[7],aux;
for (x = 0; x < TAM; x++){
cout << "Entre com um inteiro para o vetor: ";
getline(cin, vetor[x]);
}
system("cls");
for (x = 0; x < TAM; x++){
for(y = x + 1; y < TAM; y++){
if (vetor[x] > vetor[y]){
aux = vetor[x];
vetor[x] = vetor[y];
vetor[y] = aux;
}
}
}
cout << "Elementos ordenados (decresente): \n";
for( x = 0; x < TAM; x++){
cout << "O numero na posicao "<<x<<" eh "<<vetor[x]<<"\n";
}
system("pause");
}
| true |
d6acb897d4770c0bd4fb59ddc8c9af8db30ee418 | C++ | WhiZTiM/coliru | /Archive2/ef/80154164218dd8/main.cpp | UTF-8 | 274 | 2.703125 | 3 | [] | no_license | template<typename>
struct type {
template<typename Up>
constexpr void operator()(Up&&) const noexcept {
}
};
template<typename Tp>
struct wrapper {
using type_ = type<Tp>;
static constexpr type_ object{};
};
int main() {
wrapper<void>::object(1);
return 0;
} | true |
34c7d4889f7534434b3e11f70563c608940a6328 | C++ | milanpro/ParProg20Assignments | /assignment4/task4.3/colorfilter_tb.cpp | UTF-8 | 693 | 2.703125 | 3 | [] | no_license | #include "colorfilter.h"
#include <fstream>
int main() {
mtl_stream in;
mtl_stream out;
mtl_stream_element element;
std::ifstream infile("/workspace/apples.bmp", std::ifstream::in | std::ifstream::binary);
do {
infile.read((char *)&element.data, STREAM_BYTES);
element.keep = (mtl_stream_keep)-1;
element.last = infile.eof();
in.write(element);
} while (!element.last);
infile.close();
colorfilter(in, out);
std::ofstream outfile("/workspace/apples.out.bmp", std::ofstream::out | std::ofstream::binary);
do {
element = out.read();
outfile.write((char *)&element.data, STREAM_BYTES);
} while (!element.last);
outfile.close();
return 0;
}
| true |
e65cb7d24ab84759068e4b7cd814e389beaccc0a | C++ | VinInn/FPOptimization | /examples/multilib.cc | UTF-8 | 2,035 | 2.734375 | 3 | [] | no_license | typedef float __attribute__( ( vector_size( 16 ) ) ) float32x4_t;
typedef float __attribute__( ( vector_size( 32 ) ) ) float32x8_t;
typedef float __attribute__( ( vector_size( 64 ) ) ) float32x16_t;
float //__attribute__ ((__target__ ("default")))
mySum(float vx, float vy) {
return vx+vy;
}
float __attribute__ ((__target__ ("sse3")))
mySum_3(float vx, float vy) {
return vx+vy;
}
float __attribute__ ((__target__ ("arch=nehalem")))
mySum_4(float vx, float vy) {
return vx+vy;
}
float __attribute__ ((__target__ ("fma")))
mySum_fma(float vx, float vy) {
return vx+vy;
}
float __attribute__ ((__target__ ("avx512f")))
mySum_512(float vx, float vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("default")))
mySum(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("sse3")))
mySum_3(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("arch=nehalem")))
mySum_4(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("arch=haswell")))
mySum(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("arch=bdver1")))
mySum_amd(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x4_t __attribute__ ((__target__ ("avx512f")))
mySum_512(float32x4_t vx, float32x4_t vy) {
return vx+vy;
}
float32x8_t __attribute__ ((__target__ ("arch=haswell")))
mySum_avx2(float32x8_t vx, float32x8_t vy) {
return vx+vy;
}
float32x8_t __attribute__ ((__target__ ("avx512f")))
mySum_512(float32x8_t vx, float32x8_t vy) {
return vx+vy;
}
/*
float32x16_t __attribute__ ((__target__ ("sse3")))
mySum(float32x16_t vx, float32x16_t vy) {
return vx+vy;
}
*/
/*
float32x16_t __attribute__ ((__target__ ("avx512f")))
mySum(float32x16_t vx, float32x16_t vy) {
return vx+vy;
}
*/
int main() {
float a=1, b=-1;
float c= mySum(a,b);
float32x4_t x{0,1,2,3};
float32x4_t y = x+1;
float32x4_t z = mySum(x,y);
return c*z[0]>2;
}
| true |
583dbb7924083ecbfb392016c498d923eb1e39a1 | C++ | RazorzMcLazorz/C-Console-Projects | /Calendar Operations/Calendar Operations/Driver.cpp | UTF-8 | 1,386 | 3.0625 | 3 | [] | no_license | #include "Vector2.h"
using namespace std;
int main()
{
// type of day
int day = 0, mon = 0;
string ay, mo;
Vector2 Month(0, 0);
Vector2 Day(0, 0);
Vector2 Year(2017, 2000);
helo:
int hi = 0;
cout << mo << " ,";
cout << ay << " " << Day.x << " ,";
cout << Year.x << endl;
cin >> hi;
switch (mon)
{
case 1:
mo = "January";
break;
case 2:
mo = "Febuary";
break;
case 3:
mo = "March";
break;
case 4:
mo = "April";
break;
case 5:
mo = "May";
break;
case 6:
mo = "June";
break;
case 7:
mo = "July";
break;
case 8:
mo = "August";
break;
case 9:
mo = "September";
break;
case 10:
mo = "October";
break;
case 11:
mo = "November";
break;
case 12:
mo = "December";
break;
}
switch (day)
{
case 1:
ay = "Sunday";
break;
case 2:
ay = "Monday";
break;
case 3:
ay = "Tuesday";
break;
case 4:
ay = "Wednesday";
break;
case 5:
ay = "Thursday";
break;
case 6:
ay = "Friday";
break;
case 7:
ay = "Saturday";
break;
}
if (day = 7)
day = 1;
if (mon = 12)
mon = 1;
if (hi >= 1)
{
Day.x++;
hi = 0;
}
if (Day.x == 31)
{
Day.x = 1;
Month.x++;
}
if (Month.x == 13)
{
Month.x = 1;
Year.x++;
}
goto helo;
system("PAUSE");
return 0;
} | true |
65ee6cbf1bbdd47aa9539e39adc1f1cf12b58065 | C++ | lheckemann/namic-sandbox | /MistSlicer/Applications/CLI/UtahBSpline/ImageTransform.cxx | UTF-8 | 2,492 | 2.671875 | 3 | [
"LicenseRef-scancode-3dslicer-1.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive |
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include <fstream>
#include "Point2D.h"
#include "Point3D.h"
#include "BSpline3D.h"
#include "BSpline2D.h"
#include "ParametricImageTransformation3D.h"
#include "ParametricImageTransformation2D.h"
#define PRECISION double
#define DIMENSION 3
#if DIMENSION == 3
typedef Point3D< PRECISION > TControlPoint;
typedef BSpline3D<TControlPoint> TParametric;
typedef ParametricImageTransformation3D<TParametric> TTransformation;
#else
typedef Point2D< PRECISION > TControlPoint;
typedef BSpline2D<TControlPoint> TParametric;
typedef ParametricImageTransformation2D<TParametric> TTransformation;
#endif
typedef TTransformation::Image Image;
typedef TTransformation::ImagePointer ImagePointer;
typedef Image::RegionType ImageRegion;
typedef Image::IndexType ImageIndex;
typedef Image::SizeType ImageSize;
typedef itk::ImageFileReader<Image> ImageReader;
typedef ImageReader::Pointer ImageReaderPointer;
typedef itk::ImageFileWriter<Image> ImageWriter;
typedef ImageWriter::Pointer ImageWriterPointer;
int main(int argc, char **argv){
try{
if(argc != 5){
std::cout << "Usage:" << std::endl;
std::cout << argv[0] << " inputimage outputfilename transformfile istTransform";
std::cout << "isTransform" << std::endl;
return 0;
}
bool isTransform = atoi(argv[4]) !=0 ;
//Read Input Image
ImageReaderPointer imageReader = ImageReader::New();
imageReader->SetFileName( argv[1] );
imageReader->Update();
ImagePointer input = imageReader->GetOutput();
ImageRegion region = input->GetLargestPossibleRegion();
ImageSize regionSize = region.GetSize();
ImageIndex regionIndex = region.GetIndex();
//read surface
TTransformation transform;
std::ifstream file;
file.open(argv[3]);
if(isTransform){
file >> transform;
}
else{
TParametric surface;
file >> surface;
transform.SetParametric(surface);
transform.SetRange(region);
}
file.close();
transform.SetImage(input);
//Setup Image transformation
std::cout << "Starting transformation" << std::endl;
ImagePointer output = transform.Transform();
std::cout << "Finished transformation" << std::endl;
//Write ouput image
ImageWriterPointer imageWriter = ImageWriter::New();
imageWriter->SetFileName(argv[2]);
imageWriter->SetInput(output);
imageWriter->Update();
imageWriter->Write();
return 0;
}
catch(const char *err){
std::cout << err << std::endl;
}
}
| true |
354c0db7e1609ac20453a2d0acd507522d036f7e | C++ | WRodewald/GPOsc | /src/GPVarianceKernel.cpp | UTF-8 | 252 | 2.65625 | 3 | [] | no_license | #include "..\include\GPVarianceKernel.h"
using namespace GP;
GP::VarianceKernel::VarianceKernel(float sigma)
: sigma(sigma)
{
}
float VarianceKernel::valueAt(float x, float y) const
{
return std::exp(-(x - y) * (x - y) / (2.f * sigma *sigma ));
}
| true |
76c0d396bce05fd146b0f789778b3f28642b8a92 | C++ | jlbren/hamper | /GenomeHash.cpp | UTF-8 | 16,070 | 2.703125 | 3 | [] | no_license | /******************************************************
Code Written and Developed @ Loyola Unviersity Chicago
Jonathon Brenner, Catherine Putonti 2015
www.putonti-lab.com/software
******************************************************/
#include <vector>
#include <bitset>
#include <cstring>
#include <fstream>
#include <iostream>
#include <cstddef>
#include "GenomeHash.h"
#include "stdint.h"
#include <algorithm>
#include <iterator>
using namespace std;
/************************************ CONSTRUCTOR ************************************
Functionality:
Sets up the arrays
Parameters:
file_path: name of the file for which you are screening for (intended target)
query_path: name of the file of reads
kmer: word size
mm: number of mismatches in seed to consider
u_threshold: user defined threshold (between 0 and 1)
Return:
NULL
*************************************************************************************/
GenomeHash::GenomeHash(char * file_path, char * query_path, int kmer, int mm, float u_threshold)
{
query_name = query_path;
file_name = file_path;
word_size = kmer;
num_mm = mm;
threshold=u_threshold;
max_size=1;
for(int i=0; i<word_size; i++) max_size=max_size*4;
cout << "Reading: " << file_name << endl;
if(get_words_host())
Create();
else
cout<<"Error reading target genome"<<endl;
}
/*************************************************************************************
Functionality:
Gets the words from the host file
Parameters:
None
Return:
True if correctly read
*************************************************************************************/
bool GenomeHash:: get_words_host()
{
char * word=new char [word_size+1];
int i,j;
unsigned int len;
ifstream in;
in.open(file_name);
if(!in.is_open()) {
cout << "The file could not be opened. Check the location.\n";
return false;
}
//gets the length
string str_word,line,header;
getline(in,header); //gets header
len=0;
while(in.peek()!=EOF)
{
getline(in,str_word);
if(str_word[0]!='>')
len+=str_word.size();
}
cout << "len=" << len << endl;
subj_size=len;
in.clear();
in.close();
htU = new NodeU [len];
unsigned long long max_size=1;
for(int i=0; i<word_size; i++)
max_size=max_size*4; //calculates = 4^word_size
htS = new NodeS [max_size];
int ii=0;
in.open(file_name);
getline(in,header); //gets header
cout << header << endl;
len=0;
char c;
while(in.peek()!=EOF)
{
for(i=0; i<word_size; i++)
{
in>>c;
if(c<97) c+=32;
htU[ii].word[i]=c;
}
ii++;
str_word="";
while(!(in.peek()=='>' || in.peek()==EOF))
{
getline(in,line);
str_word+=line;
for(i=0;i<(str_word.length()-word_size+1);i++)
{
for(j=0;j<word_size-1;j++)
htU[ii].word[j]=htU[ii-1].word[j+1];
c=str_word[i];
if(c<97) c+=32;
htU[ii].word[word_size-1]=c;
ii++;
}
//adjust str_word
j=str_word.length()-word_size+1;
if(!(in.peek()=='>' || in.peek()==EOF || j<(word_size-1))) str_word.erase(0,j);
}
if(in.peek()!=EOF)
{
getline(in,header); //gets header
cout << header << endl;
}
}
subj_size=ii;
in.clear();
in.close();
return true;
}
/*************************************************************************************
Functionality:
Calls hash function and comparisons; reports to console # results
Parameters:
None
Return:
NULL
*************************************************************************************/
void GenomeHash::Create()
{
Hash();
compare_query_multi();
cout << results.size() << " results found." << endl;
}
/*************************************************************************************
Functionality:
Populates the htS array
Parameters:
None
Return:
NULL
*************************************************************************************/
void GenomeHash::Hash()
{
unsigned long long hash_val;
for (int i = 0; i <subj_size; i++)
{
hash_val=word_to_decimal(htU[i].word);
if(! (hash_val==0 && htU[i].word[0]!='a'))
{
htS[hash_val].num_occ=true;
htS[hash_val].ptr.push_back(&htU[i]);
}
}
}
/*************************************************************************************
Functionality:
Hash function, converts word to integer
Parameters:
word: nucleotide sequence
Return:
integer value of word
*************************************************************************************/
unsigned long long GenomeHash::word_to_decimal(string word)
{
int word_size=word.length();
unsigned long long val = 0; // 4 bytes = 32 bits = 16 chars
char c;
unsigned char temp;
int i=0;
c=word.at(i);
switch(c)
{
case 'a':
temp=0;
break; //shifts 00 for a
case 't':
temp=1;
break; //shifts 10 for t
case 'c':
temp=2;
break;//shifts 01 for c
case 'g':
temp=3;
break;//shifts 11 for g
default: return 0;
}
val=temp;
for (i=1; i<word_size; i++)
{
val=val<<2;
c=word.at(i);
switch(c)
{
case 'a':
temp=0;
break; //shifts 00 for a
case 't':
temp=1;
break; //shifts 10 for t
case 'c':
temp=2;
break;//shifts 01 for c
case 'g':
temp=3;
break;//shifts 11 for g
default: return 0;
}
val+=(int)temp;
}
if (val>max_size)
cout <<"Out of range: " + word <<endl;
return val;
}
/*************************************************************************************
Functionality:
Compares the query/read sequence(s) to the target arrays
Parameters:
None
Return:
True if completed correctly; false if the file cannot be opened
*************************************************************************************/
bool GenomeHash:: compare_query_multi()
{
ifstream in;
in.open(query_name);
if(!in.is_open())
{
cout << "The read file could not be opened. Check the location.\n";
return false;
}
int i,j,len;
char * word=new char [word_size+1];
cout << "Reading: " << query_name << endl;
string str_word,line,header;
getline(in,header); //gets header
while(in.peek()!=EOF)
{
len=0;
str_word="";
while( !(in.peek()=='>' || in.peek()==EOF))
{
getline(in,line);
len+=line.size();
str_word+=line;
}
min_match_size_threshold=len*threshold;
for(i=0; i<word_size; i++)
{
word[i]=str_word[i];
if(word[i]<97) word[i]+=32; //makes it lowercase
}
word[word_size]='\0';
words.push_back(word);
for(i=1; i<(len-word_size+1); i++) //read until the end of the file
{
//shift
for(j=0; j<(word_size-1); j++) word[j]=word[j+1];
word[(word_size-1)]=str_word[word_size+i-1];
if(word[word_size-1]<97) word[word_size-1]+=32; //makes it lowercase
word[word_size]='\0';
words.push_back(word);
}
query_size=words.size();
bool hit=false;
for (uint64_t ii=0; ii<query_size;ii++) // forward strand of query
{
UINT64 current_word = word_to_decimal(words[ii]);
ii = get_match(header, current_word, ii, num_mm, '+',hit);
if(hit) {ii=query_size;}
}
if(!hit)
{
//consider reverse complement of the query sequence
get_reverse_complement();
for (uint64_t ii =0; ii<query_size;ii++) // reverse strand of query
{
UINT64 current_word = word_to_decimal(words[ii]);
ii = get_match(header, current_word, ii, num_mm, '-',hit);
if(hit) {ii=query_size;}
}
}
words.clear();
if(in.peek()!=EOF)
{
getline(in,header); //gets header
}
}
in.clear();
in.close();
Get_Results();
return true;
}
/*************************************************************************************
Functionality:
Calculates the location of the word in unsorted table of target genome
Parameters:
word: the integer representation of the nucleotide word
pointer_index: which particular pointer in the array of pointers
Return:
True if completed correctly; false if the file cannot be opened
*************************************************************************************/
unsigned long long GenomeHash:: ptr_to_index(uint64_t word, int pointer_index)
{
ptrdiff_t z;
NodeU * base = htU;
NodeU * s=htS[word].ptr[pointer_index];
z=s-base;
return (uint64_t)z;
}
/*************************************************************************************
Functionality:
Identifies matches between target and reads meeting the threshold
Parameters:
header: the sequence being considred
current_word: the seed word
i: index
mm: number of mismatches
strand: +/- strand being considered
hit: boolean value passed by reference if a match is found
Return:
index in sequence to next be considered if match found or not
*************************************************************************************/
unsigned long long GenomeHash:: get_match(string header, unsigned long long current_word, uint64_t i, int mm, char strand, bool &hit)
{ // pass in query index, word; return new index
string match;
double mismatches;
double percent_mm=0;
double match_size = 0;
uint64_t start;
uint64_t ii=0;
uint64_t min_ii=query_size;
hit=false;
if(current_word<0 || current_word>max_size) return 0;
if (htS[current_word].num_occ)
{
//loop through for each instance of query word in the subject sequence
for(int np=0; np<htS[current_word].ptr.size(); np++)
{
NodeO temp;
uint64_t index = ptr_to_index(current_word,np); // calculate index of current word in unsorted table of target genome
match = htU[index].word;
mismatches=0;
percent_mm=0;
start=i;
ii=i;
//ii is position within the query (words), index is position within the subject
//jump start => match=2*word_size
while (((ii-start)<=word_size) && (ii<(query_size-1)) && (index<(subj_size-1)))
{
ii++; // increment query position
index +=1; // increment target position
match+=htU[index].word[word_size-1]; // add next char to match
if (words[ii]!=htU[index].word)
mismatches++;
}
match_size=match.size();
percent_mm = mismatches/match_size;
//if jump started match meets the threshold, continue to grow the word
if(percent_mm<=threshold)
{
while ((percent_mm<=threshold) && (ii<(query_size-1)) && (index<(subj_size-1)))
{
ii++; // increment query position
index +=1; // increment target position
match+=htU[index].word[word_size-1]; // add next char to match
match_size = match.size();
if (words[ii]!=htU[index].word)
{
mismatches++;
percent_mm = mismatches/match_size;
}
}
//if the match meets the user specified threshold (for length)
if (match_size>=min_match_size_threshold)
{
temp.header=header;
results.push_back(temp);
hit=true;
return ii;
}
if(ii<min_ii) min_ii=ii;
}
else
return i;
}
}
else
return i;
return min_ii;
}
/*************************************************************************************
Functionality:
Writes out results
Parameters:
None
Return:
NULL
*************************************************************************************/
void GenomeHash:: Get_Results()
{
ofstream out_map; ofstream out_dont;
char file[1000];
sprintf(file,"%s.map",query_name);
out_map.open(file);
sprintf(file,"%s.unmapped",query_name);
out_dont.open(file);
ifstream in;
in.open(query_name);
string line;
int i=0;
while(in.peek()!=EOF)
{
getline(in,line);
if(line[0]=='>') //new read
{
if(line==results[i].header) //mapped
{
out_map<<line<<endl;
while(!(in.peek()=='>'||in.peek()==EOF))
{
getline(in,line);
out_map<<line<<endl;
}
i++;
}
else
{
out_dont<<line<<endl;
while(!(in.peek()=='>'||in.peek()==EOF))
{
getline(in,line);
out_dont<<line<<endl;
}
}
}
}
out_map.clear(); out_map.close();
out_dont.clear(); out_dont.close();
in.clear(); in.close();
}
/*************************************************************************************
Functionality:
Checks if the word occurs within the htS array
Parameters:
index: index in htS to be checked
Return:
NULL
*************************************************************************************/
bool GenomeHash::check_word(unsigned long long index){
if (htS[index].num_occ)
return true;
else return false;
}
/*************************************************************************************
Functionality:
Creates the vector of words for the complementary strand of the sequence
Parameters:
None
Return:
NULL
*************************************************************************************/
void GenomeHash:: get_reverse_complement()
{
vector<string> rc;
string rev_word;
for(int j=query_size-1; j>=0; j--)
{
rev_word=words[j];
reverse(rev_word.begin(), rev_word.end());
for(int i=0; i<rev_word.size(); i++)
{
switch(rev_word[i]){
case 'a': rev_word[i]='t'; break;
case 't': rev_word[i]='a'; break;
case 'c': rev_word[i]='g'; break;
case 'g': rev_word[i]='c'; break;
default: rev_word[i]='n';
}
}
rc.push_back(rev_word);
}
words.clear();
words.swap(rc);
}
| true |
543329bfc845764fdd590ff61accecb0b37837e4 | C++ | fyjet/gps32 | /lib/Geodesic/Geodesic.cpp | UTF-8 | 1,789 | 3.359375 | 3 | [] | no_license | /*
* Class to compute distance and bearing from geographical coordinates
*
* formulas and explanation, see https://www.movable-type.co.uk/scripts/latlong.html
*/
#include "Arduino.h"
#include "math.h"
#include "Geodesic.h"
Geodesic::Geodesic(float destination_latitude,float destination_longitude)
{
_destination_latitude=destination_latitude;
_destination_longitude=destination_longitude;
}
float Geodesic::bearing(float from_latitude,float from_longitude)
{
float teta_from_latitude = radians(from_latitude);
float teta_destination_latitude = radians(_destination_latitude);
float delta_longitude = radians(_destination_longitude-from_longitude);
float y = sin(delta_longitude) * cos(teta_destination_latitude);
float x = cos(teta_from_latitude)*sin(teta_destination_latitude) - sin(teta_from_latitude)*cos(teta_destination_latitude)*cos(delta_longitude);
float brng = atan2(y,x);
brng = degrees(brng);// radians to degrees
brng = fmod(brng + 360, 360 );
return brng;
}
float Geodesic::distance(float from_latitude,float from_longitude)
{
float radius = 6371; // hearth radius, in kilometers
float delta_latitude = radians(_destination_latitude - from_latitude);
float delta_longitude = radians(_destination_longitude - from_longitude);
// compute distance with help of haversine formula
float a = (sin(delta_latitude/2.0)*sin(delta_latitude/2.0)) + cos(radians(from_latitude)) * cos(radians(_destination_latitude)) * (sin(delta_longitude/2.0)*sin(delta_longitude/2.0));
float c = 2.0 * asin(sqrtf(a));
float distance = radius * c;
return distance;
}
void Geodesic::setDestination(float destination_latitude,float destination_longitude)
{
_destination_latitude=destination_latitude;
_destination_longitude=destination_longitude;
}
| true |
dfe3a7ae9bea710b0073d0788656d3b406bf1488 | C++ | xwj95/Airwriting | /src/Task.cpp | UTF-8 | 3,644 | 2.75 | 3 | [] | no_license | //
// Task.cpp
// Airwriting
//
// Created by 徐炜杰 on 15/12/4.
// Copyright © 2015年 徐炜杰. All rights reserved.
//
#include "Task.h"
#include "Canvas.h"
Task *Task::instance = new Task();
Task::Task() {
cvImage = cvCreateImage(cvSize(COMPRESS_M * COMPRESS_K, COMPRESS_N * COMPRESS_K), 8, 3);
cvZero(cvImage);
cvNamedWindow(title.data(), 0);
cvMoveWindow(title.data(), CHARACTER_WINDOW_X, CHARACTER_WINDOW_Y);
}
Task::~Task() {
while (!tasks.empty()) {
popTask();
}
cvReleaseImage(&cvImage);
cvDestroyAllWindows();
}
Task* Task::getInstance() {
if (!instance) {
instance = new Task();
}
return instance;
}
unsigned long Task::getSize() {
return tasks.size();
}
double** Task::getTask(unsigned int m, unsigned int n) {
if (!tasks.empty()) {
return compress(tasks.front(), m, n);
}
return NULL;
}
void Task::pushTask() {
double **canvas = Canvas::getInstance()->getCanvas();
int m = Canvas::getInstance()->getm();
int n = Canvas::getInstance()->getn();
double **image = new double*[m];
for (int i = 0; i < m; ++i) {
image[i] = new double[n];
for (int j = 0; j < n; ++j) {
image[i][j] = canvas[i][j];
}
}
tasks.push(image);
Canvas::getInstance()->clear();
}
void Task::popTask() {
if (tasks.empty()) {
return;
}
double **image = tasks.front();
tasks.pop();
if (!image) {
return;
}
for (int i = 0; i < Canvas::getInstance()->getm(); ++i) {
delete image[i];
}
delete image;
}
double** Task::compress(double **image, unsigned int m, unsigned int n) {
double **image_compressed = new double*[m];
for (int i = 0; i < m; ++i) {
image_compressed[i] = new double[n];
}
unsigned m_origin = Canvas::getInstance()->getm();
unsigned n_origin = Canvas::getInstance()->getn();
unsigned m_pooling = m_origin / m;
unsigned n_pooling = n_origin / n;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
image_compressed[i][j] = 0;
for (int p = 0; p < m_pooling; ++p) {
for (int q = 0; q < n_pooling; ++q) {
double value = image[i * m_pooling + p][j * n_pooling + q];
if ((value == value) && (value > image_compressed[i][j])) {
image_compressed[i][j] += image[i * m_pooling + p][j * n_pooling + q];
}
}
}
image_compressed[i][j] = image_compressed[i][j];
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (image_compressed[i][j] < 1e-7) {
image_compressed[i][j] = 0;
}
if (image_compressed[i][j] > 1 - 1e-7) {
image_compressed[i][j] = 1;
}
for (int k1 = 0; k1 < COMPRESS_K; ++k1) {
for (int k2 = 0; k2 < COMPRESS_K; ++k2) {
cvSet2D(cvImage, i * COMPRESS_K + k1, j * COMPRESS_K + k2, CV_RGB(image_compressed[i][j] * 255, image_compressed[i][j] * 255, image_compressed[i][j] * 255));
}
}
}
}
return image_compressed;
}
void Task::release(double **image, unsigned int m, unsigned int n) {
for (int i = 0; i < m; ++i) {
delete image[i];
}
delete image;
}
void Task::show() {
while (displaying) {
cvShowImage(title.data(), cvImage);
cvWaitKey(10);
}
}
void Task::start() {
displaying = true;
}
void Task::stop() {
displaying = false;
}
| true |
a5dd73d17f14cc2a22c183c4c540df122180baa5 | C++ | sureshyhap/C-plus-plus-Primer | /Chapter 9/15/15.cpp | UTF-8 | 259 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<int> v1 {1, 2, 3, 4, 5}, v2 {1, 2, 3, 4, 5};
if (v1 == v2) {
std::cout << "They are equal\n";
}
else {
std::cout << "They are unequal\n";
}
return 0;
}
| true |
d04172c467e0c545e5b694fd573e6309f740fc28 | C++ | kakigori12345/My-Creating-Games | /MonsterFactory.cpp | SHIFT_JIS | 5,954 | 2.5625 | 3 | [] | no_license | #include "GameLib/Framework.h"
#include "MonsterFactory.h"
#include "Action.h"
#include "ContentReader.h"
#include <string>
using namespace std;
using namespace GameLib;
const char* MonsterFactory::filename = "data/monster_book.txt";
const char* MonsterFactory::defaultName = "Default";
MonsterFactory::MonsterFactory()
{
ContentReader* cr = new ContentReader(filename);
cr->readStart();
mNumOfMonsters = cr->getNumOfDataFrames();
mMonsters = new Monster[mNumOfMonsters];
//ǂݍMonsteř^ĂBƂ肠eqWȂǂ͖Ēlꍞł
for (int i = 0; i < mNumOfMonsters; ++i)
{
string name = cr->getNameOfDataFrame(i);
const char* target = name.c_str();
//X^[̊ep[^
Parameters temp_params;
//todo:insert ip[^VɒljȂҏWKvj
temp_params.parent = cr->getData_str(target, "parent");
temp_params.health = static_cast<int>(cr->getData(target, "health"));
temp_params.power = static_cast<int>(cr->getData(target, "power"));
temp_params.speed = static_cast<int>(cr->getData(target, "speed"));
temp_params.defence = static_cast<int>(cr->getData(target, "defence"));
temp_params.capture = static_cast<int>(cr->getData(target, "capture"));
temp_params.weapon = cr->getData_str(target, "weapon");
temp_params.parts = static_cast<int>(cr->getData(target, "parts"));
temp_params.scale = cr->getData(target, "scale");
temp_params.image = cr->getData_str(target, "image");
//X^[AIɊւp[^
ParameterAI temp_paramAI;
//todo:insert ip[^VɒljȂҏWKvj
temp_paramAI.attack = static_cast<int>(cr->getData(target, "attack"));
temp_paramAI.attackMagic = static_cast<int>(cr->getData(target, "attackMagic"));
temp_paramAI.moveToEnemy = static_cast<int>(cr->getData(target, "moveToEnemy"));
temp_paramAI.playerLove = static_cast<int>(cr->getData(target, "playerLove"));
temp_paramAI.runawayFromEnemy = static_cast<int>(cr->getData(target, "runawayFromEnemy"));
temp_paramAI.runawayHP = static_cast<int>(cr->getData(target, "runawayHP"));
//
mMonsters[i].setName(name);
mMonsters[i].setParameter(temp_params);
mMonsters[i].setParameterAI(temp_paramAI);
}
//eqW̏
//lݒ肳Ă邩ǂ肷邽߂̒萔
string NullDataS = ContentReader::NullDataStr;
float NullDataF = ContentReader::NullDataFloat;
int NullDataI = static_cast<int>( NullDataF );
for (int i = 0; i < mNumOfMonsters; ++i)
{
//pMonsterparent̒l猈߂
Parameters targetParam = *mMonsters[i].getParameter();
string parentName = targetParam.parent;
ParameterAI targetParamAI = *mMonsters[i].getParameterAI();
//parentݒ肳ĂȂȂftHglŕ₤
if (parentName == NullDataS)
parentName = defaultName;
//pp[^T
Parameters resetParam;
ParameterAI resetParamAI;
for (int j = 0; j < mNumOfMonsters; ++j)
{
//
if (mMonsters[j].getName() == parentName) {
resetParam = *mMonsters[j].getParameter();
resetParamAI = *mMonsters[j].getParameterAI();
break;
}
}
//pKvȃp[^̂p
//todo:insert ip[^VɒljȂҏWKvj
if (targetParam.health == NullDataI)
targetParam.health = resetParam.health;
if (targetParam.power == NullDataI)
targetParam.power = resetParam.power;
if (targetParam.speed == NullDataI)
targetParam.speed = resetParam.speed;
if (targetParam.defence == NullDataI)
targetParam.defence = resetParam.defence;
if (targetParam.capture == NullDataI)
targetParam.capture = resetParam.capture;
if (targetParam.weapon == NullDataS)
targetParam.weapon = resetParam.weapon;
if (targetParam.parts == NullDataI)
targetParam.parts = resetParam.parts;
if (targetParam.scale == NullDataF)
targetParam.scale = resetParam.scale;
if (targetParam.image == NullDataS)
targetParam.image = resetParam.image;
if (targetParamAI.attack == NullDataI)
targetParamAI.attack = resetParamAI.attack;
if (targetParamAI.attackMagic == NullDataI)
targetParamAI.attackMagic = resetParamAI.attackMagic;
if (targetParamAI.moveToEnemy == NullDataI)
targetParamAI.moveToEnemy = resetParamAI.moveToEnemy;
if (targetParamAI.playerLove == NullDataI)
targetParamAI.playerLove = resetParamAI.playerLove;
if (targetParamAI.runawayFromEnemy == NullDataI)
targetParamAI.runawayFromEnemy = resetParamAI.runawayFromEnemy;
if (targetParamAI.runawayHP == NullDataI)
targetParamAI.runawayHP = resetParamAI.runawayHP;
//ŌɍXV
mMonsters[i].setParameter(targetParam);
mMonsters[i].setParameterAI(targetParamAI);
}
delete cr;
cr = nullptr;
//̑ݒ
for (int i = 0; i < mNumOfMonsters; ++i)
{
//fZbgĂ
mMonsters[i].setModel( mMonsters[i].getParameter()->image.c_str() );
//f̑傫
mMonsters[i].setScale(mMonsters[i].getParameter()->scale);
}
}
MonsterFactory::~MonsterFactory()
{
delete[] mMonsters;
mMonsters = nullptr;
}
Monster** MonsterFactory::spawnMonster(const char* monster, int num)
{
//܂͎w̖OMonsterT
int target = 0;
while(target < mNumOfMonsters){
if (mMonsters[target].getName() == monster)
break;
target++;
}
if (target == mNumOfMonsters)
HALT("File::MonsterFactory.cpp [spawnMonster] (That's monster is not exist) Error");
//w肳ꂽMonster
Monster** reply;
reply = new Monster*[num];
for (int i = 0; i < num; ++i)
{
reply[i] = mMonsters[target].spawnMe();
}
return reply;
} | true |
e2c817e34b7d85ab8bf7fafc21330ebec552d9ac | C++ | bearxiong99/arduino-m5451-current-driver | /latest/apps/ccshield_m5451_test/ccshield_m5451_test.cpp | UTF-8 | 5,934 | 2.640625 | 3 | [] | no_license | #include <CCShield.h>
/*
* Constant-Current Shield M5451 LED driver chip test and example
* Author: G. Andrew Stone
* Public Domain
*/
#include "WProgram.h"
void setup();
void loop();
int myClockPin = 3; // Arduino pin that goes to the clock on all M5451 chips
int mySerDataPin = 9; // 7; //9; // Arduino pin that goes to data on one M5451 chip
int mySerDataPin2 = 5; //8; //10; // Arduino pin that goes to data on another M5451 chip (if you don't have 2, set this to an unused digital pin)
int myBrightnessPin = 11; // What Arduino pin goes to the brightness ping on the M5451s
int ledPin = 13; // The normal arduino example LED
void setup() // run once, when the sketch starts
{
}
class StepperL298N
{
public:
unsigned long int cnt;
// uint8_t pins[4];
uint8_t pinShift;
uint8_t curState;
uint8_t* lut;
CCShield& brd;
StepperL298N(CCShield& brd, uint8_t pinShift);
void step(uint8_t dir);
void halfStep(uint8_t yes) { if (yes) lut = halfStepLut; else lut = fullStepLut;}
void start() { curState = 0xa;}
void free() { curState = 0; }
void brake() { curState = 0; }
uint8_t fullStepLut[16];
uint8_t halfStepLut[16];
};
StepperL298N::StepperL298N(CCShield& thebrd, uint8_t pinshift):brd(thebrd)
{
cnt = 0;
// pins[0] = pin1; pins[1] = pin2; pins[2]=pin3; pins[3] = pin4;
pinShift = pinshift;
lut = fullStepLut;
// for (int i=0;i<4;i++)
// pinMode(pins[i], OUTPUT); // sets the digital pin as output
memset(&fullStepLut,sizeof(uint8_t)*16,0);
memset(&halfStepLut,sizeof(uint8_t)*16,0);
// High nibble goes one way, low the other
fullStepLut[0] = 0;
// 1010 -> 1001 -> 0101 -> 0110
fullStepLut[0xa] = 0x9 | 0x60;
fullStepLut[0x9] = 0x5 | 0xa0;
fullStepLut[0x5] = 0x6 | 0x90;
fullStepLut[0x6] = 0xa | 0x50;
halfStepLut[0] = 0;
// 1010 -> 1000 -> 1001 -> 0001 -> 0101 -> 0100 -> 0110 -> 0010
halfStepLut[0xa] = 0x8 | 0x20;
halfStepLut[0x8] = 0x9 | 0xa0;
halfStepLut[0x9] = 0x1 | 0x80;
halfStepLut[0x1] = 0x5 | 0x90;
halfStepLut[0x5] = 0x4 | 0x10;
halfStepLut[0x4] = 0x6 | 0x50;
halfStepLut[0x6] = 0x2 | 0x40;
halfStepLut[0x2] = 0xa | 0x60;
}
void StepperL298N::step(uint8_t dir)
{
cnt+=1;
curState = lut[curState];
// Depending on the direction, go one way or the other.
if (dir) curState &= 0xf;
else curState >>= 4;
#if 0
for (int i=1,j=0;i<16;i<<=1,j++)
{
uint8_t lvl = LOW;
if (i&curState) lvl=HIGH;
digitalWrite(pins[j],lvl);
}
#endif
brd.set(curState<<pinShift,cnt,0);
}
void LedDemo(CCShield& leds)
{
int i;
uint8_t j;
for (i=0;i<5;i++)
{
leds.set(0xffffffff,0xffffffff,0xff); // All on
digitalWrite(ledPin,1);
//bling(ON);
delay(i*250);
leds.set(0,0,0); // All off
digitalWrite(ledPin,0);
//bling(OFF);
delay(500);
}
for (i=5;i>=0;i--)
{
for (j=0;j<70;j++)
{
// Set one LED on indexed by J
leds.set(1L<<j,(j>=32) ? 1L<<(j-32):0,(j>=64) ? 1L<<(j-64):0 );
delay(20*i);
}
}
#if 1
// ALL FADE using M5451 Brightness feature
leds.set(0xffffffff,0xffffffff,0xff); /* ALL ON */
delay(1000);
for (j=1;j<2;j++)
{
for (i=0;i<256;i++)
{
leds.setBrightness(i&255);
delay(j*10);
}
for (i=255;i>=0;i--)
{
leds.setBrightness(i&255);
delay(j*10);
}
}
#endif
leds.setBrightness(255);
}
void BrightnessDemo(CCShield& brd)
{
unsigned long int j;
int i;
FlickerBrightness leds(brd);
brd.set(0xffffffff,0xffffffff,0xff); /* ALL ON */
delay(250);
brd.set(0,0,0); /* ALL OFF */
delay(250);
// Linear per-LED brightness method
if (1) for (j=0;j<4096;j++)
{
for (i=0;i<CCShield_NUMOUTS;i++)
{
int k = j*10;
if (i&1)
{
leds.brightness[i] = abs((k&(CCShield_MAX_BRIGHTNESS*2-1))-CCShield_MAX_BRIGHTNESS);
}
else
leds.brightness[i] = CCShield_MAX_BRIGHTNESS - abs((k&(CCShield_MAX_BRIGHTNESS*2-1))-CCShield_MAX_BRIGHTNESS);
}
for (i=0;i<10;i++) leds.loop();
}
// MARQUEE
for (i=0;i<CCShield_NUMOUTS;i++) // Clear all LEDs to black
{
leds.brightness[i]=0;
}
// Turn on a couple to make a "comet" with dimming tail
leds.brightness[0] = CCShield_MAX_BRIGHTNESS-1;
leds.brightness[1] = CCShield_MAX_BRIGHTNESS/2;
leds.brightness[2] = CCShield_MAX_BRIGHTNESS/4;
leds.brightness[3] = CCShield_MAX_BRIGHTNESS/8;
leds.brightness[4] = CCShield_MAX_BRIGHTNESS/16;
leds.brightness[5] = CCShield_MAX_BRIGHTNESS/64;
leds.brightness[6] = CCShield_MAX_BRIGHTNESS/100;
for (j=0;j<100;j++)
{
leds.shift(1);
for (i=0;i<150;i++) leds.loop();
}
for (j=0;j<100;j++)
{
leds.shift(-1);
for (i=0;i<100;i++) leds.loop();
}
}
void loop() // run over and over again
{
unsigned long int j;
CCShield out(myClockPin,mySerDataPin,mySerDataPin2, myBrightnessPin);
out.setBrightness(255);
LedDemo(out);
#if 0
BrightnessDemo(out);
out.set(0xffffffff,0xffffffff,0xff); /* ALL ON */
delay(1000);
out.set(0,0,0); /* ALL ON */
#endif
#if 0
StepperL298N motor(out,1);
motor.halfStep(true);
motor.start();
for (j=0;j<3000;j++)
{
motor.step((j>>9)&1);
//digitalWrite(ledPin, j&1); // sets the LED on
//delay(2+(1000-j)/100);
//digitalWrite(ledPin, LOW); // sets the LED off
//delay(3000);
delay(4);
}
motor.halfStep(false);
motor.start();
for (j=0;j<3000;j++)
{
motor.step((j>>9)&1);
//digitalWrite(ledPin, j&1); // sets the LED on
//delay(2+(1000-j)/100);
//digitalWrite(ledPin, LOW); // sets the LED off
delay(5);
}
#endif
}
int main(void)
{
init();
setup();
for (;;)
loop();
return 0;
}
| true |
0468a51d81a8d365ba9fbb5d2cbd72488a41357a | C++ | keisuke-kanao/my-UVa-solutions | /Contest Volumes/Volume 110 (11000-11099)/UVa_11086_Composite_Prime.cpp | UTF-8 | 1,697 | 3.3125 | 3 | [] | no_license |
/*
UVa 11086 - Composite Prime
To build using Visual Studio 2012:
cl -EHsc -O2 UVa_11086_Composite_Prime.cpp
*/
/*
4
3 4 6 8
3 3 is a prime number
4 = 2 * 2
6 = 2 * 3
8 = 2 * 4 4 is an element in M
5
12 13 21 22 23
12 = 3 * 4 4 is an element in M
13 13 is a prime number
21 = 3 * 7
22 = 3 * 11
23 23 is a prime number
*/
#include <iostream>
#include <cmath>
using namespace std;
const int n_max = 1048576;
bool not_primes[n_max + 1]; // not_primes[i] is true if i is not a prime
bool not_composite_primes[n_max + 1]; // composite_primes[i] is true if i is not a composite prime
void sieve_of_eratosthenes()
{
not_primes[0] = not_primes[1] = true;
for (int i = 2, e = static_cast<int>(sqrt(static_cast<double>(n_max))); i <= e; i++)
if (!not_primes[i]) {
for (int j = i * i; j <= n_max; j += i)
not_primes[j] = true;
}
}
void composite_primes()
{
not_composite_primes[0] = not_composite_primes[1] = not_composite_primes[2] = not_composite_primes[3] = true;
for (int i = 4; i <= n_max; i++)
if (not_primes[i] && !not_composite_primes[i]) {
for (int j = i * 2; j <= n_max; j += i)
not_composite_primes[j] = true;
}
}
int main()
{
sieve_of_eratosthenes();
composite_primes();
#ifdef DEBUG
int nr_composite_primes = 0;
for (int i = 4; i <= n_max; i++)
if (not_primes[i] && !not_composite_primes[i])
nr_composite_primes++;
cout << nr_composite_primes << endl; // 219759
#endif
int K;
while (cin >> K) {
int nr = 0;
while (K--) {
int n;
cin >> n;
if (not_primes[n] && !not_composite_primes[n])
nr++;
}
cout << nr << endl;
}
return 0;
}
| true |
2efd0ca6d6065eba8e0a40f0dbe5b071b4795bbe | C++ | shugo256/AlgorithmLibrary | /DataStructures/doubling.cpp | UTF-8 | 1,678 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <string>
using ll = long long;
using namespace std;
/*
verified on 2019/10/16
https://atcoder.jp/contests/arc060/submissions/7988691
*/
#define LOG_MAX 30
// 1つ先が無い(木の根など)場合、値を負かn以上とする
template <typename T>
class Doubling {
const size_t n;
vector<vector<T>> next;
public:
Doubling() {}
Doubling(vector<T> first_row)
: n(first_row.size()),
next(LOG_MAX, vector<T>(n)) {
copy(first_row.begin(), first_row.end(), next[0].begin());
for (size_t i=1; i<LOG_MAX; i++) {
for (size_t j=0; j<n; j++) {
next[i][j] = (
(0 <= next[i-1][j] && (size_t)next[i-1][j] < n)
? next[i-1][(size_t)next[i-1][j]]
: next[i-1][j]
);
}
}
}
// iからstep回移動して到達できる場所をO(log(n))で返す
T n_step(T i, int step=1) {
for (int k=LOG_MAX-1; k>=0; k--) {
if ((step >> k) & 1) i = next[(size_t)k][(size_t)i];
if (i < 0 || n <= (size_t)i) break;
}
return i;
}
// 任意のi, sについて next[s][i] >= i or next[s][i] == -1
// が成り立つ時のみ使用可能
// iからj(jからi)に行くまでの距離をO(log(n))で計算
T dist(T i, T j) {
if (i > j) swap(i, j);
int d = 0;
for (int k=LOG_MAX-1; k>=0 && i < j; k--) {
if (next[k][i] < j) {
i = next[k][i];
d += (1 << k);
}
}
return d + 1;
}
}; | true |
77e650321f19fcdf3d7fac5d10b68fb40179d7f2 | C++ | greenfox-zerda-sparta/juliabaki | /week_05/day_1_jukebox/Song.cpp | UTF-8 | 514 | 3.203125 | 3 | [] | no_license | #include "Song.h"
Song::Song(string artist_of_song, string title) {
this->artist_of_song = artist_of_song;
this->title = title;
this->genre = "";
this->sum_rating = 0;
this->rating_counter = 0;
}
Song::~Song() {}
string Song::getName() {
return artist_of_song + ", " + title;
}
float Song::getAverageRating() {
float averageRating = 0;
if(sum_rating == 0 || rating_counter == 0){
averageRating = -1;
} else {
averageRating = sum_rating / rating_counter;
}
return averageRating;
}
| true |
ea25491f439d8521866568d3ec675b4d34edc8c8 | C++ | donovan680/UAC-bypass | /testDll/Main.cpp | UTF-8 | 1,138 | 2.5625 | 3 | [] | no_license | #include <windows.h>
#include <iostream>
#include <fstream>
#include <string>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, VOID* reserved)
{
OutputDebugString(TEXT("Testing output Debug string"));
std::ifstream infile;
char tempBuf[MAX_PATH];
GetTempPathA(MAX_PATH, tempBuf);
std::string tempFolder = tempBuf;
tempFolder += "\\clientlocationx12.txt";
infile.open(tempFolder.c_str());
std::string startDirectory;
std::string exePath;
if (infile.is_open())
{
while (!infile.eof())
{
std::getline(infile, startDirectory);
break;
}
}
infile.close();
exePath += startDirectory + "\\tutclient.exe";
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
STARTUPINFOA lpStartupInfo;
PROCESS_INFORMATION lpProcessInfo;
memset(&lpStartupInfo, 0, sizeof(lpStartupInfo));
memset(&lpProcessInfo, 0, sizeof(lpProcessInfo));
/* Create the process */
if (!CreateProcessA(exePath.c_str(), NULL, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, startDirectory.c_str(), &lpStartupInfo, &lpProcessInfo))
{
std::cout << "Not Worknig" << GetLastError() << std::endl;
}
break;
}
return TRUE;
} | true |
0e67a480c61bf9a9557af17a5a83613107dc483b | C++ | nathanesau-competitive/Algorithms | /cpp/tests/graph_algorithms_test.h | UTF-8 | 1,401 | 2.953125 | 3 | [
"WTFPL"
] | permissive | #ifndef TESTGRAPHALGORITHMS_H
#define TESTGRAPHALGORITHMS_H
#include "../graphs/graph_algorithms.h"
#include <assert.h>
#ifndef ASSERT_RAISES
#define ASSERT_RAISES
template <class Type>
void assertRaises(Type &&f)
{
try
{
f();
assert(false);
}
catch (exception &)
{
assert(true);
}
}
#endif
class GraphAlgorithmsTest
{
Graph<string> gr;
//DiGraph<string> digr;
public:
GraphAlgorithmsTest()
{
}
void setUp()
{
gr = Graph<string>();
gr.add_nodes({ "s", "a", "b", "c", "d", "e", "f", "g", "h", "j", "k", "l" });
gr.add_edges({ {"s", "a"}, {"s", "b"}, {"a", "c"}, {"c", "e"} });
gr.add_edges({ {"e", "d" }, { "d", "b" }, { "a", "b" }, { "c", "d" } });
gr.add_edges({ {"g", "h"}, {"f", "g" } });
gr.add_edges({ {"j", "k"}, {"j", "l" } });
}
void test_bfs_undirected_graph()
{
setUp();
assert(GraphAlgorithms<string>::BFS(gr, "s").size() == 6);
assert(GraphAlgorithms<string>::BFS(gr, "j").size() == 3);
assert(GraphAlgorithms<string>::BFS(gr, "g").size() == 3);
}
void test_dfs_undirected_graph()
{
setUp();
assert(GraphAlgorithms<string>::DFS(gr, "s").size() == 6);
assert(GraphAlgorithms<string>::DFS(gr, "j").size() == 3);
assert(GraphAlgorithms<string>::DFS(gr, "g").size() == 3);
}
};
void RunGraphAlgorithmsTest()
{
GraphAlgorithmsTest gr_test;
gr_test.test_bfs_undirected_graph();
gr_test.test_dfs_undirected_graph();
}
#endif | true |
c84e98aa05aca0fd22d193670cc2a9310ee0304f | C++ | TomashuTTTT7/c4stl | /src/c4/hash.hpp | UTF-8 | 1,812 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef _C4_HASH_HPP_
#define _C4_HASH_HPP_
#include "c4/config.hpp"
#include <climits>
C4_BEGIN_NAMESPACE(c4)
/** @see http://aras-p.info/blog/2016/08/02/Hash-Functions-all-the-way-down/ */
C4_BEGIN_NAMESPACE(detail)
/** @see this was taken from a stack overflow answer. get the link and put it here. */
template< typename ResultT, ResultT OffsetBasis, ResultT Prime >
class basic_fnv1a final
{
static_assert(std::is_unsigned<ResultT>::value, "need unsigned integer");
public:
using result_type = ResultT;
private:
result_type state_ {};
public:
C4_CONSTEXPR14 basic_fnv1a() noexcept : state_ {OffsetBasis}
{
}
C4_CONSTEXPR14 void update(const void *const data, const size_t size) noexcept
{
const auto cdata = static_cast<const unsigned char *>(data);
auto acc = this->state_;
for(size_t i = 0; i < size; ++i)
{
const auto next = size_t {cdata[i]};
acc = (acc ^ next) * Prime;
}
this->state_ = acc;
}
C4_CONSTEXPR14 result_type digest() const noexcept
{
return this->state_;
}
};
using fnv1a_32 = basic_fnv1a< uint32_t, UINT32_C(2166136261), UINT32_C(16777619)>;
using fnv1a_64 = basic_fnv1a< uint64_t, UINT64_C(14695981039346656037), UINT64_C(1099511628211)>;
template< size_t Bits > struct fnv1a;
template<> struct fnv1a<32> { using type = fnv1a_32; };
template<> struct fnv1a<64> { using type = fnv1a_64; };
C4_END_NAMESPACE(detail)
template< size_t Bits >
using fnv1a_t = typename detail::fnv1a<Bits>::type;
C4_CONSTEXPR14 inline size_t hash_bytes(const void *const data, const size_t size) noexcept
{
auto fn = fnv1a_t< CHAR_BIT * sizeof(size_t) > {};
fn.update(data, size);
return fn.digest();
}
C4_END_NAMESPACE(c4)
#endif // _C4_HASH_HPP_
| true |
36b95e0b32eaaa11bd58665e3786feaa04a88feb | C++ | MarufurRahman/Object-Oriented-Programming-CPP | /Source/simple_cls_and_obj.cpp | UTF-8 | 321 | 3.4375 | 3 | [] | no_license | // Create a simple class and object
// Programmed by Marufur Rahman
#include <iostream>
using namespace std;
class Hello
{
public:
void sayHello()
{
cout << "Hello World" << endl;
}
};
int main()
{
Hello classObject1;
classObject1.sayHello();
return 0;
}
| true |