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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b798a141f860b38b1c0d2319eca35c95c1b20798 | C++ | Riibit/SEP | /GameHandler.h | UTF-8 | 7,526 | 3 | 3 | [] | no_license | //------------------------------------------------------------------------------
// GameHandler.h
//
// Group: Group 15666, study assistant Hasan Durmaz
//
// Authors: Milan Drinic 1431883
// Christopher Hinterer 1432027
// Julian Rudolf 1331657
//------------------------------------------------------------------------------
//
#ifndef GAMEHANDLER_H
#define GAMEHANDLER_H
#include <string>
#include <vector>
#include <memory>
class EnvironmentalCondition;
class Command;
//------------------------------------------------------------------------------
// GameHandler Class
// Class that runs the various methods of the game.
//
class GameHandler
{
public:
//--------------------------------------------------------------------------
// Constructor
GameHandler();
//--------------------------------------------------------------------------
// Destructor
~GameHandler();
//--------------------------------------------------------------------------
// Initialize Initializes the games processes
//
// @return int Returns the corresponding return value.
//
int initialize(int argc, char *argv[]);
//--------------------------------------------------------------------------
// play executes the prompt method and is used to terminate the
// programm.
//
// @return int Returns the corresponding return value.
//
int play();
//--------------------------------------------------------------------------
// resetStandardRecipe Resets the recipe to its standard values before
// every round.
//
void resetStandardRecipe();
//--------------------------------------------------------------------------
// Adds the expenditures to the expenses
void addExpenses(unsigned int expenditures);
//--------------------------------------------------------------------------
// Calculates the current balance
void calculateBalance();
//--------------------------------------------------------------------------
// Setter Methods
void setInterfaceParameters(std::vector<std::string>*
interface_parameters);
void setInterfaceCommand(std::string* command_name);
void setResourceLemon(unsigned int lemon_value);
void setResourceSugar(unsigned int sugar_value);
void setResourceMoney(unsigned int money_value);
void setResourceIncome(unsigned int value);
void setResourceLemonade(unsigned int amount);
void setCustomerSatisfaction(int satisfaction);
void setResourceBalance(int balance);
void setResourceExpense(unsigned int expense);
void setPriceLemon(unsigned int price_lemon);
void setPriceSugar(unsigned int price_sugar);
void setPriceLemonade(unsigned int price_lemonade);
void setRecipe(unsigned int lemon, unsigned int sugar, unsigned int water);
//--------------------------------------------------------------------------
// Getter Methods
unsigned int getResourceLemon();
unsigned int getResourceSugar();
unsigned int getResourceMoney();
unsigned int getExpenses();
unsigned int getResourceIncome();
unsigned int getResourceLemonade();
int getResourceBalance();
unsigned int getPriceLemonade();
unsigned int getPriceLemon();
unsigned int getPriceSugar();
unsigned int getRecipeLemon();
unsigned int getRecipeSugar();
unsigned int getRecipeWater();
int getCustomerSatisfaction();
float getSatisfactionFactor();
const std::unique_ptr<EnvironmentalCondition>& getCondition() const;
//--------------------------------------------------------------------------
// endOfLife Method
// Sets the variable game_quit_ to true so that the program terminates
//
void endOfLife();
//--------------------------------------------------------------------------
// The message if the parameters are invalid at start
static const std::string ERR_PROGRAM_START;
//--------------------------------------------------------------------------
// Error if no matching command was found
static const std::string ERR_UNKNOWN_COMMAND;
//--------------------------------------------------------------------------
// The standard recipe for the lemonade
static const int STANDARD_RECIPE_LEMON = 6;
static const int STANDARD_RECIPE_SUGAR = 6;
static const int STANDARD_RECIPE_WATER = 88;
private:
//--------------------------------------------------------------------------
// Private copy constructor
GameHandler(const GameHandler& original);
//--------------------------------------------------------------------------
// Private assignment operator
GameHandler& operator=(const GameHandler& original);
//--------------------------------------------------------------------------
// The initial values of resources available to the player
static const int LEMONS_INITIAL_VALUE = 100;
static const int SUGAR_INITIAL_VALUE = 100;
static const int MONEY_INITIAL_VALUE = 5000;
static const int ZERO_INITIAL_VALUE = 0;
//--------------------------------------------------------------------------
// The percentage value of the customers satisfaction
int customer_satisfaction_ = 100;
//--------------------------------------------------------------------------
// The object that contains the Environmental Condition
std::unique_ptr<EnvironmentalCondition> environment_condition_;
//--------------------------------------------------------------------------
// The resources available to the player
struct GameResources
{
unsigned int lemons;
unsigned int sugar;
unsigned int money;
int balance;
unsigned int income;
unsigned int expenses;
unsigned int lemonade;
} resources_;
//--------------------------------------------------------------------------
// The composition of the current recipe
struct Recipe
{
unsigned int lemon;
unsigned int sugar;
unsigned int water;
} recipe_;
//--------------------------------------------------------------------------
// The name of the command that was given in stdin
std::string* command_name_;
//--------------------------------------------------------------------------
// The interface parameters given in stdin
std::vector<std::string>* interface_parameters_;
//--------------------------------------------------------------------------
// Vector with all command object initialized at construction
std::vector<std::unique_ptr<Command>> commands_;
//--------------------------------------------------------------------------
// The bool that ends the game if true. to be set in the endOfLife method
bool game_quit_;
//--------------------------------------------------------------------------
// The price of a lemonade
unsigned int price_lemonade_;
//--------------------------------------------------------------------------
// The price of a lemon
unsigned int price_lemon_;
//--------------------------------------------------------------------------
// The price of a sugar
unsigned int price_sugar_;
//--------------------------------------------------------------------------
// Compares the first arg with the commands and checks the if the number of
// parameters are correct.
//
// @return Returns the correspondent return value.
//
int resolveCommand();
};
#endif //GAMEHANDLER_H | true |
519e47caea7a9d2db52dfed0d2ceefbfb23e6ce6 | C++ | lsqyling/PrimerAdvanced | /part_1_foundation/chapter_3_sva.cpp | UTF-8 | 24,352 | 3.546875 | 4 | [
"CC0-1.0"
] | permissive | //
// Created by shiqing on 19-4-18.
//
#include "../common/CommonHeaders.h"
#include "Sales_item.h"
/*
* Exercise 3.1:
* Rewrite the exercises from § 1.4.1 (p. 13) and § 2.6.2 (p. 76)
* with appropriate using declarations.
*
* already be done.
*/
void initializingStrings() {
string s1;//default initialization; s1 is the empty string
string s2 = s1;//s2 is a copy of s1
string s3 = "hiya";// s3 is a copy of the string literal
string s4(10, 'c');// s4 is cccccccccc
string s5 = "hiya";//copy initialization
string s6("hiya");//direct initialization
string s7(10, 'c');// direct initialization; s7 is cccccccccc
string s8 = string(10, 'c');//copy initialization ,s8 is ccccccccccc
}
/*
* Exercise 3.2:
* Write a program to read the standard input a line at a time.
* Modify your program to read a word at a time.
* Answer:@see inAndOut();
*/
void inAndOut() {
cout << "Enter two strings: " << endl;
string s1, s2;
cin >> s1 >> s2;
cout << s1 << s2 << endl;
cout << "continue..." << endl;
string s;
while (cin >> s && s[0] != 'n') {
cout << s << endl;
}
cout << "continue...." << endl;
string line;
while (getline(cin, line) && line[0] != 'n') {
cout << line << endl;
}
}
/*
* Exercise 3.3:
* Explain how whitespace characters are handled in the string input operator and in the getline function.
* For code like is >> s, input is separated by whitespaces while reading into string s.
* For code like getline(is, s) input is separated by newline \n while reading into string s. Other whitespaces are ignored.
* For code like getline(is, s, delim)input is separated by delim while reading into string s. All whitespaces are ignored.
*
*/
/*
* Exercise 3.4: Write a program to read two strings and report whether the
* strings are equal. If not, report which of the two is larger. Now, change
* the program to report whether the strings have the same length, and if
* not, report which is longer.
* Answer:@see compareStrings();
*/
void compareStrings() {
cout << "Enter two strings:" << endl;
string s1, s2;
cin >> s1 >> s2;
if (s1 == s2) {
cout << s1 << endl;
} else {
cout << (s1 < s2 ? s2 : s1) << endl;
}
if (s1.size() < s2.size()) {
cout << s2 << endl;
}
}
/*
* Exercise 3.5: Write a program to read strings from the standard input,
* concatenating what is read into one large string. Print the concatenated
* string. Next, change the program to separate adjacent input strings by a space.
* Answer:@see joinStrings();
*/
void joinStrings() {
cout << "please input words: " << endl;
string s, out, separate;
while (cin >> s && s[0] != 'n') {
out += s;
separate += (" " + s);
}
cout << out << endl;
cout << separate << endl;
}
/*
* Exercise 3.6:
* Use a range for to change all the characters in a string to X.
* Answer:@see charToX();
*/
/*
* Exercise 3.7:
* What would happen if you define the loop control variable in
* the previous exercise as type char? Predict the results and then change your
* program to use a char to see if you were right.
* Answer:@see charToX();
*/
/*
* Exercise 3.8:
* Rewrite the program in the first exercise, first using a while
* and again using a traditional for loop. Which of the three approaches do
* you prefer and why?
* Answer:@see charToX();
*/
void charToX() {
cout << "Please input a world, and then look up output." << endl;
string s;
cin >> s;
string cs(s), original(s);
decltype(s.size()) n = 0;
while (!s.empty() && n < s.size()) {
s[n] = 'X';
++n;
}
for (auto &c : cs) {
c = 'X';
}
cout << "inputs is " << original << ", result is " << s << endl;
cout << "inputs is " << original << ", result is " << cs << endl;
}
/*
* Exercise 3.9:
* What does the following program do? Is it valid? If not, why not?
* string s;
* cout << s[0] << endl;
* Answer:
* This code was dereferencing and printing the first item stored in s.
* Since s is empty, such operation is invalid, a.k.a. undefined behavior.
*/
/*
* Exercise 3.10:
* Write a program that reads a string of characters including
* punctuation and writes what was read but with the punctuation removed.
* @see interceptPunctuation();
*/
void interceptPunctuation() {
cout << "please input a string of characters including punctuation?" << endl;
string s, result;
getline(cin, s);
for (const auto c : s) {
if (!ispunct(c)) {
result += c;
}
}
cout << "\nthe original string is: \n" << s << "\nthe result is " << result << endl;
}
/*
* Exercise 3.11:
* Is the following range for legal? If so, what is the type of c?
* const string s = "Keep out!";
* for (auto &c : s) { ... }
*
* c is const char &.
*/
/*
* Exercise 3.12:
* Which, if any, of the following vector definitions are in error?
* For those that are legal, explain what the definition does.
* For those that are not legal, explain why they are illegal.
* vector<vector<int>> ivec; // legal(c++11), vectors.
* vector<string> svec = ivec; // illegal, different type.
* vector<string> svec(10, "null"); // legal, vector have 10 strings: "null".
*/
/*
* Exercise 3.13:
* How many elements are there in each of the following vectors? What are the values of the elements?
* vector<int> v1; // size:0, no values.
* vector<int> v2(10); // size:10, value:0
* vector<int> v3(10, 42); // size:10, value:42
* vector<int> v4{ 10 }; // size:1, value:10
* vector<int> v5{ 10, 42 }; // size:2, value:10, 42
* vector<string> v6{ 10 }; // size:10, value:""
* vector<string> v7{ 10, "hi" }; // size:10, value:"hi"
*/
void initializingVectors() {
vector<int> ivec;// ivec holds objects of type int
vector<Sales_item> salesVec;// holds Sales_items
vector<vector<string>> file;// vector whose elements are vectors
vector<string> svec;
vector<int> ivec2(ivec);// copy elements of ivec into ivec2
vector<int> ivec3 = ivec2;//copy elements of ivec2 into ivec3;
// vector<string> sevc1(ivec2);Error:svec1 holds strings, not ints
vector<string> articles = {"a", "b", "c", "d"};
vector<string> v1{"a", "an", "the", "people"};
// vector<string> v2("a", "b", "c");Error:
{
vector<int> ivec(10, -1);// ten int elements, each initialized to -1
vector<string> sevc(10, "hi");// ten string elements, each initialized to hi
}
{
vector<int> ivec(10);// ten int elements,each initialized to 0
vector<string> svec(10);// ten string elements ,each initialized to empty string
vector<int> v1(10);
vector<int> v2{10};
vector<int> v3(10, 1);
vector<int> v4{10, 1};
vector<string> v5{"hi"};
// vector<string> v6("hi");
vector<string> v7{10};// v7 has ten default-initialized elements
vector<string> v8{10, "hi"};//v8 has ten elements with value "hi"
}
}
/*
* Exercise 3.14:
* Write a program to read a sequence of ints from cin and store those values in a vector.
* Answer @see addNumbsToVector();
*/
void addNumbsToVector() {
cout << "enter a set of integers: " << endl;
vector<int> iv;
int x = 0;
while (cin >> x && x != -1) {
iv.push_back(x);
}
for (auto &e : iv) {
cout << e << " ";
}
cout << endl;
}
/*
* Exercise 3.15:
* Repeat the previous program but read strings this time.
* Answer @see addStringsToVector();
*/
void addStringsToVector() {
cout << "enter a set of strings: " << endl;
vector<string> sv;
string s;
while (cin >> s && s[0] != 'n') {
sv.push_back(s);
}
for (auto &e : sv) {
cout << e << " ";
}
cout << endl;
}
/*
* Exercise 3.16:
* Write a program to print the size and contents of the
* vectors from exercise 3.13. Check whether your answers to that exercise
* were correct. If not, restudy § 3.3.1 (p. 97) until you understand why you
* were wrong.
* already be done.
*/
/*
* Exercise 3.17:
* Read a sequence of words from cin and store the values a
* vector. After you’ve read all the words, process the vector and change
* each word to uppercase. Print the transformed elements, eight words to a line.
*
* Answer: @see toUpperFromVector();
*
*/
void toUpperFromVector() {
cout << "enter a sequence of words: " << endl;
string s;
vector<string> sv;
while (cin >> s && s[0] != 'n') {
sv.push_back(s);
}
for (auto &word : sv) {
for (auto &c : word) {
c = toupper(c);
}
}
for (const auto &word : sv) {
cout << word << endl;
}
}
/*
* Exercise 3.18:
* Is the following program legal? If not, how might you fix it?
* vector<int> ivec;
* ivec[0] = 42;
* vector<int> ivec = {42};
*/
/*
* Exercise 3.19:
* List three ways to define a vector and give it ten elements,
* each with the value 42. Indicate whether there is a preferred way to do so and why.
* vector<int> iv(10, 42);
* vector<int> ivv = {42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
* vector<int> ivvv;
* for (int i = 0; i != 10; ++i) {
* ivvv.push_back(42);
* }
*/
/*
* Exercise 3.20:
* Read a set of integers into a vector. Print the sum of each
* pair of adjacent elements. Change your program so that it prints the sum of
* the first and last elements, followed by the sum of the second and second-to-
* last, and so on.
* @see sumOfTwoElements();
*/
void sumOfTwoElements() {
cout << "enter a set of integers: " << endl;
vector<int> iv;
int n;
while (cin >> n && n != -1) {
iv.push_back(n);
}
auto sz = iv.size();
for (decltype(sz) i = 0; i < sz; ++i) {
if (sz == 1) {
cout << iv[i] << " ";
break;
}
cout << iv[i] + iv[++i] << " ";
if (i == sz - 2) {
cout << iv[++i] << " ";
}
}
cout << endl;
for (decltype(sz) j = 0, k = sz - 1; j <= k; ++j, --k) {
if (j == k) {
cout << iv[j] << " ";
break;
}
cout << iv[j] + iv[k] << " ";
}
cout << endl;
}
/*
* Exercise 3.21:
* Redo the first exercise from § 3.3.3 (p. 105) using iterators.
* @see toUpperFirstParagraph();
*/
/*
* Exercise 3.22:
* Revise the loop that printed the first paragraph in text to
* instead change the elements in text that correspond to the first paragraph
* to all uppercase. After you’ve updated text, print its contents.
* @see toUpperFirstParagraph();
*/
void toUpperFirstParagraph() {
cout << "enter lines for text: " << endl;
string line;
vector<string> vs;
while (getline(cin, line) && line[0] != 'n') {
vs.push_back(line);
}
vector<string> result;
bool flag = false;
for (auto beg = vs.begin(); beg != vs.end() && !beg->empty(); ++beg) {
for (auto b = beg->begin(); b != beg->end(); ++b) {
if (isspace(*b) && isspace(*(b + 1))) {
flag = true;
break;
}
*b = toupper(*b);
}
if (flag) {
break;
}
result.push_back(*beg);
}
for (auto beg = result.begin(); beg != result.end() && !beg->empty(); ++beg) {
cout << *beg << " " << endl;
}
}
/*
* Exercise 3.23:
* Write a program to create a vector with ten int elements.
* Using an iterator, assign each element a value that is twice its current value.
* Test your program by printing the vector.
* @see toDouble();
*/
void toDouble() {
vector<int> iv = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for (auto beg = iv.begin(); beg != iv.end(); ++beg) {
*beg = *beg * 2;
}
for (const auto &i : iv) {
cout << i << " ";
}
cout << endl;
}
/*
* Exercise 3.24:
* Redo the last exercise from § 3.3.3 (p. 105) using iterators.
* Answer:Non-best practice,if you need best practices please check @sumOfTwoElements();
*/
/*
* Exercise 3.25:
* Rewrite the grade clustering program from § 3.3.3 (p. 104) using iterators instead of subscripts.
* Answer:Non-best practice,if you need best practices please check @sumOfTwoElements();
*/
/*
* Exercise 3.26:
* In the binary search program on page 112, why did we write mid=beg+(end-beg)/2; instead of mid=(beg+end) /2;?
* Answer: There's no operator + for adding two iterators.
*/
void initializingArrays() {
unsigned cnt = 42;
constexpr unsigned sz = 42;
int array[10];
int *parr[sz];
string bad[cnt];// error: cnt is not a constant expression, but the compiler didn't report an error.
int ia1[sz] = {0, 1, 2}; //The compiler performs value initialization. 0 1 2 0 0 ...
for (int i = 0; i != sz; ++i) {
cout << ia1[i] << " ";
}
cout << endl;
int ia2[] = {0, 1, 3};
int ia3[5] = {0, 1, 2};
string a4[3] = {"hi", "bye"};
// int ia5[2] = {0, 1 ,2};error: too many initializers for ‘int [2]’
{
char a1[] = {'C', '+', '+'}; // list initialization, no null
char a2[] = {'C', '+', '+', '\0'}; // list initialization, explicit null
char a3[] = "C++"; // null terminator added
// automatically
// const char a4[6] = "Daniel"; // error: no space for the null!
const char a4[7] = "Daniel";
}
{
int a[] = {0, 1, 2};
// int a2[] = a;cannot initialize one array with another
int a2[3];
// a2 = a;cannot assign one array to another
}
{
int arr[10];
int *ptr[10];// ptrs is an array of ten pointers to int
// int &refs[10];// error: no arrays of references
int (*Parry)[10] = &arr;// Parry points to an array of ten ints
int (&arrRef)[10] = arr;// arrRef refers to an array of ten ints
int *(&array)[10] = ptr;// array is a reference to an array of ten pointers
}
{
int a[10];
for (int i = 0; i != 10; ++i) {
a[i] = i;
}
int copyArr[10] = {};
for (int j = 0; j != 10; ++j) {
copyArr[j] = a[j];
}
vector<int> iv(begin(a), end(a));
for (auto &e : iv) {
cout << e << " ";
}
cout << endl;
for (const auto &p : a) {
cout << p << " ";
}
cout << endl;
}
}
/*
* Exercise 3.27:
* Assuming txt_size is a function that takes no arguments and returns an int value,
* which of the following definitions are illegal? Explain why.
* unsigned buf_size = 1024;
* int ia[buf_size]; // illegal, The dimension value must be a constant expression.
* int ia[4 * 7 - 14]; // legal
* int ia[txt_size()]; // illegal, The dimension value must be a constant expression.
* char st[11] = "fundamental"; // illegal, the string's size is 12.
*/
/*
* Exercise 3.28:
* What are the values in the following arrays?
* string sa[10]; //all elements are empty strings
* int ia[10]; //all elements are 0
int main()
{
string sa2[10]; //all elements are empty strings
int ia2[10]; //all elements are undefined
}
*/
/*
* Exercise 3.29:
* List some of the drawbacks of using an array instead of a vector.
* Size is fixed at compiling time.
* No API as that of vector.
* Bug prone.
*/
/*
* Exercise 3.30:
* Identify the indexing errors in the following code:
* constexpr size_t array_size = 10;
* int ia[array_size];
* for (size_t ix = 1; ix <= array_size; ++ix)
* ia[ix] = ix;
* Answer:
* When ix equal to 10, the expression ia[ix] becomes a UB, as it is trying to dereference an element out of range.
*/
/*
* Exercise 3.31:
* Write a program to define an array of ten ints. Give each
* element the same value as its position in the array.
* @see initializingArrays();
*/
/*
* Exercise 3.32:
* Copy the array you defined in the previous exercise into
* another array. Rewrite your program to use vectors.
* @see initializingArrays();
*/
/*
* Exercise 3.33:
* What would happen if we did not initialize the scores array
* in the program on page 116?
*
* Answer:1768841540 27750 258715648 1251937268 2 0 1 0 4201073 1 3174787314
*/
void countScores() {
unsigned scores[11];
unsigned grade;
while (cin >> grade && grade != -1) {
if (grade <= 100) {
++scores[grade / 10];
}
}
for (auto &c : scores) {
cout << c << " ";
}
cout << endl;
}
/*
* Note:
* In most expressions, when we use an object of array type, we are really
* using a pointer to the first element in that array.
*/
void pointerToArrays() {
string numbs[] = {"one", "two", "three", "four"};
string *p = numbs; // or string *p = &numbs[0];
int ia[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
auto ia2(ia);//ia2 is an int* that points to the first element in ia
// ia2 = 42;error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]
decltype(ia) ia3 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
// ia3 = p;Error:cannot assign an int* to an array
ia3[4] = 5;// ok:assigns the value of i to an element in ia3
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *pp = arr;
++pp;
cout << *pp << endl;
int *e = &arr[10];
for (int *b = arr; b != e; ++b) {
cout << *b << " ";
}
cout << endl;
int *beg = begin(ia);
int *last = end(ia);
int array[10];
for (int *p = array; p != end(array); ++p) {
*p = 0;
}
for (auto &e : array) {
cout << e << " ";
}
cout << endl;
}
/*
* Exercise 3.34:
* Given that p1 and p2 point to elements in the same array, what does the following code do?
* Are there values of p1 or p2 that make this code illegal?
* p1 += p2 - p1;
*
* Answer:
* It moves p1 with the offset p2 - p1. After this statement, p1 and p2 points to the same address.
* Any legal value p1, p2 make this code legal.
*/
/*
* Exercise 3.35:
* Using pointers, write a program to set the elements in an array to zero.j
* @see pointerToArrays();
*/
/*
* Exercise 3.36:
* Write a program to compare two arrays for equality.
* Write a similar program to compare two vectors.
*
* @see compareIntArrays();
*/
bool compareIntArrays(int *a, int *b, int n) {
for (int *i = a, *j = b; n > 0; --n) {
if (*i++ != *j++) {
return false;
}
}
return true;
}
#include <cstring>
void cStyleStrings() {
char ca[] = {'C', '+', '+'};
cout << strlen(ca) << endl; //error: disaster: ca isn't null terminated,but the compiler didn't report the error;
string s1 = "A string example";
string s2 = "A different string";
if (s1 < s2) cout << s1 << endl;
const char cal[] = "A string example";
const char ca2[] = "A different string";
// if (cal < ca2) {} // undefined: compares two unrelated addresses
}
/*
* Exercise 3.37:
* What does the following program do?
* const char ca[] = { 'h', 'e', 'l', 'l', 'o' };
* const char *cp = ca;
* while (*cp) {
* cout << *cp << endl;
* ++cp;
* }
* Answer:
* This code will print all characters in ca, afterwards as no \0 appended,
* UB would happen.
* For most cases, the while loop here won't be terminated as expected and many rubbish would be printed out.
*/
/*
* Exercise 3.38:
* In this section, we noted that it was not only illegal but
* meaningless to try to add two pointers. Why would adding two pointers be meaningless?
*
* Answer:
* Pointer addition is forbidden in C++, you can only subtract two pointers.
* The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers.
* Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down".
* Adding a pointer to a pointer is something which is hard to explain.
* What would the resulting pointer represent?
* If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses,
* you can cast the two pointers to int, add ints, and cast back to a pointer.
* Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.
*/
/*
* Exercise 3.39:
* Write a program to compare two strings.
* Now write a program to compare the values of two C-style character strings.
* @see compareCStyleStrings();
*/
/*
* Exercise 3.40: Write a program to define two character arrays initialized
* from string literals. Now define a third character array to hold the
* concatenation of the two arrays. Use strcpy and strcat to copy the two
* arrays into the third.
* @see compareCStyleStrings();
*/
void compareCStyleStrings() {
const char *s1 = "hello world", *s2 = "hello world yield";
cout << (strcmp(s1, s2) >= 0 ? s1 : s2) << endl;
string s3("hello world"), s4("hello world yield");
cout << (s3 <= s4 ? s4 : s3) << endl;
char s5[50];
char *t = strcat(s5, s1);
char *t1 = strcpy(s5, s2);
strcpy(s5, t1);
char *p = s5;
while (*p) {
cout << *p;
++p;
}
cout << endl;
const char *str = s3.c_str(); //ok
}
void multidimensionalArrays() {
int arr[10][20][30] = {11};
int ia[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
// explicitly initialize row 0; the remaining elements are value initialized
int ix[3][4] = {0, 3, 6, 9};
// initializes the elements of the first row. The remaining elements are initialized to 0.
ia[2][3] = arr[0][0][0];
int (&row)[4] = ia[1];// binds row to the second four-element array in ia
constexpr size_t rowCnt = 3, colCnt = 4;
int ib[rowCnt][colCnt];
for (size_t i = 0; i != rowCnt; ++i) {
for (size_t j = 0; j != colCnt; ++j) {
ib[i][j] = i * rowCnt + j;
}
}
size_t cnt = 0;
for (auto &row : ib) {
for (auto &col : row) {
col = cnt;
++cnt;
}
}
for (const auto &row : ib) {
for (auto col : row) {
cout << col << " ";
}
cout << endl;
}
int (*p)[4] = ia;// p points to an array of four ints
p = &ia[2];// p now points to the last element in ia
for (auto p = ia; p != ia + 3; ++p) {
for (auto q = *p; q != *p + 4; ++q) {
cout << *q << " ";
}
cout << endl;
}
cout << endl;
for (auto p = begin(ia); p != end(ia); ++p) {
for (auto q = begin(*p); q != end(*p); ++q) {
cout << *q << " ";
}
cout << endl;
}
cout << endl;
}
/*
* Exercise 3.43:
* Write three different versions of a program to print the
* elements of ia. One version should use a range for to manage the
* iteration, the other two should use an ordinary for loop in one case using
* subscripts and in the other using pointers. In all three programs write all the
* types directly. That is, do not use a type alias, auto, or decltype to
* simplify the code.
*
* @see multidimensionalArrays();
*/
/*
* Exercise 3.44:
* Rewrite the programs from the previous exercises using a
* type alias for the type of the loop control variables.
* @see multidimensionalArrays();
*/
/*
* Exercise 3.45: Rewrite the programs again, this time using auto.
* @see multidimensionalArrays();
*/
void applyStringsApi() {
interceptPunctuation();
charToX();
joinStrings();
compareStrings();
inAndOut();
initializingStrings();
cStyleStrings();
compareCStyleStrings();
}
void applyArrays() {
initializingArrays();
pointerToArrays();
int a[] = {1, 2, 3}, b[] = {1, 2, 3};
cout << compareIntArrays(a, b, 3) << endl;
int a1[] = {1}, b1[] = {0};
cout << compareIntArrays(a1, b1, 1) << endl;
}
void applyVectorsApi() {
countScores();
sumOfTwoElements();
toUpperFromVector();
initializingVectors();
addNumbsToVector();
addStringsToVector();
toDouble();
toUpperFirstParagraph();
}
int main() {
// applyStringsApi();
compareCStyleStrings();
multidimensionalArrays();
return 0;
}
| true |
593dfca93b9962bb3178de51c6f064688c0cc1a3 | C++ | OKullmann/oklibrary | /Satisfiability/Algorithms/Backtracking/GenericBacktracking.hpp | UTF-8 | 2,541 | 2.578125 | 3 | [] | no_license | // Oliver Kullmann, 21.11.2006 (Swansea)
/* Copyright 2006 - 2007 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Satisfiability/Algorithms/Backtracking/GenericBacktracking.hpp
\brief Generic backtracking (DPLL-like) solvers
*/
#ifndef GENERICBACKTRACKING_JJhb171Yh
#define GENERICBACKTRACKING_JJhb171Yh
#include <boost/logic/tribool.hpp>
namespace OKlib {
namespace SATAlgorithms {
/*!
\class Backtracking
\brief Generic backtracking solver (first prototype)
Backtracking<ExtProblem, Red, Heur, Vis> has the following template parameters:
- ExtProblem ist a class with the problem and the current partial assignment
- Red is the reduction for every node
- Heur is the heuristics (the branching literal)
- Vis is the (decision-)visitor
\todo Update
*/
template <class ExtProblem, class Red, class Heur, class Vis>
struct Backtracking {
typedef ExtProblem extended_problem_type;
typedef Red reduction_type;
typedef Heur heuristics_type;
typedef Vis visitor_type;
extended_problem_type& P;
reduction_type r;
heuristics_type h;
visitor_type& vis;
const bool all;
Backtracking(extended_problem_type& problem, reduction_type reduction, heuristics_type heuristics, visitor_type& visitor, const bool all_solutions = false) :
P(problem), r(reduction), h(heuristics), vis(visitor), all(all_solutions) {}
boost::logic::tribool operator()() {
{
const boost::logic::tribool initial_decision = r(P);
if (initial_decision) { vis.satisfied(P); P.undo(); return true; }
else if (not initial_decision) { vis.falsified(P); P.undo(); return false; }
}
typedef typename heuristics_type::literal_type literal_type;
const literal_type& l(h(P));
P.add_assignment(l); // do we have failed-literal reduction?
{
const boost::logic::tribool first_branch = Backtracking::operator()();
P.undo(); if (first_branch and not all) return true;
}
P.add_negated_assignment(l);
{
const boost::logic::tribool second_branch = Backtracking::operator()();
P.undo(); return second_branch;
}
}
};
}
}
#endif
| true |
a33554e49c9e0e211c173b9d588ece928f2250fd | C++ | JRProd/ResourceManager | /ResourceManager.h | UTF-8 | 1,062 | 3.15625 | 3 | [] | no_license | /* ########## RESOURCE MANAGER APPLICATION ##########
* The ResourceManager module is used to manage nodes
* and their connections. User can add or change a
* node's usable bit by deleting the node.
*
* The toString function can print out the nodes and
* their connections as a list of requirements for
* nodes, or as a adjecency matrix showing connections
*
* Aurthor - Jake Rowland
* Date - November 5, 2107
*/
#ifndef RESOURCE_MANAGER
#define RESOURCE_MANAGER
#include "ResourceNode.h"
class ResourceManager {
private:
std::vector<ResourceNode*> nodes;
ResourceNode* findNode(std::string resource);
// Functions to generate the matrix
std::string generateGraphBlock(int maxResouceLength, std::string resource) const;
std::string generateGraphBreak(int maxResouceLength, int numOfResources) const;
public:
ResourceManager();
~ResourceManager();
void addNode(std::string resource, std::string requirement);
void deleteNode(std::string resource);
std::string toString(bool asMatrix) const;
};
#endif
| true |
68679f37e098eb4eba5d875a34469793438d4973 | C++ | eaindra-wp/OOP-2-In-Class-Assignments | /Assignment 1/Solution 1/Solution 1/testcomplex.cpp | UTF-8 | 1,614 | 3.734375 | 4 | [] | no_license | /*
CH08-320143
a1_p1_testcomplex.cpp
Eaindra Wun Pyae
e.wunpyae@jacobs-university.de
*/
#include <fstream>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include "Complex.h"
using namespace std;
int main()
{
Complex c1,c2,cadd,csub,cmul;
//input for the first file and check error
ifstream in1("in1.txt",ios::in);
if(!in1.good())
{
cerr << "Error opening input file 1" << endl;
exit(1);
}
//input for the second file and check error
ifstream in2("in2.txt",ios::in);
if(!in2.good())
{
cerr << "Error opening input file 2" << endl;
exit(2);
}
//output file and check for error
ofstream out("output.txt",ios::out);
if(!out.good())
{
cerr << "Error opening output file" << endl;
exit(3);
}
//input the values read to the object
in1 >> c1;
in2 >> c2;
cout << "Result from the first file: ";
cout << c1;
cout << "Result from the second file: ";
cout << c2;
//print the results on the screen<<
cadd = c1 + c2;
cout << "Result of addition file: ";
cout << cadd;
csub = c1 - c2;
cout << "Result of subtraction file: ";
cout << csub;
cmul = c1 * c2;
cout << "Result of multiplication file: ";
cout << cmul;
//write the result in the new file
out << "Addition: " << c1 + c2 << endl;
out << "Subtraction: " <<c1 - c2 << endl;
out << "Multiplication: " << c1 * c2 << endl;
//close the files
in1.close();
in2.close();
out.close();
return 0;
}
| true |
1e722e6aa353d7e6811cc273b9b7cbbbfadceb42 | C++ | justinlee957/scrabble | /tests/mytest.cpp | UTF-8 | 14,914 | 2.90625 | 3 | [] | no_license | #include "gtest/gtest.h"
#include <iostream>
#include <string>
#include <algorithm>
#include "scrabble_config.h"
#include "board.h"
#include "dictionary.h"
#include "tile_kind.h"
#include "human_player.h"
#include "computer_player.h"
#define DICT_PATH "config/english-dictionary.txt"
using namespace std;
// Helper functions for placing words in get_anchors() and get_move() tests
void print_words(PlaceResult res, Move m){
std::cout << m.row + 1 << ' ' << m.column + 1 << ' ';
if (m.direction == Direction::ACROSS)
std::cout << "- ";
else
std::cout << "| ";
for (auto word : res.words)
std::cout << word << " ";
std::cout << std::endl;
}
void place_simple_word(Board &b) {
vector<TileKind> t;
t.push_back(TileKind('H', 1));
t.push_back(TileKind('I', 1));
Move m = Move(t, 7, 7, Direction::ACROSS);
b.place(m);
}
void place_two_words(Board &b) {
vector<TileKind> t1;
t1.push_back(TileKind('H', 1));
t1.push_back(TileKind('I', 1));
Move m1 = Move(t1, 7, 7, Direction::ACROSS);
b.place(m1);
vector<TileKind> t2;
t2.push_back(TileKind('A', 1));
t2.push_back(TileKind('A', 1));
Move m2 = Move(t2, 5, 7, Direction::DOWN);
b.place(m2);
}
void place_long_word(Board &b) {
vector<TileKind> t1;
t1.push_back(TileKind('B', 1));
t1.push_back(TileKind('L', 1));
t1.push_back(TileKind('I', 1));
t1.push_back(TileKind('Z', 1));
t1.push_back(TileKind('Z', 1));
t1.push_back(TileKind('A', 1));
t1.push_back(TileKind('R', 1));
t1.push_back(TileKind('D', 1));
Move m1 = Move(t1, 7, 7, Direction::ACROSS);
b.place(m1);
}
void place_concave_words(Board &b) {
vector<TileKind> t1;
t1.push_back(TileKind('A', 1));
t1.push_back(TileKind('U', 1));
t1.push_back(TileKind('N', 1));
t1.push_back(TileKind('T', 1));
t1.push_back(TileKind('Y', 1));
Move m1 = Move(t1, 7, 7, Direction::ACROSS);
b.place(m1);
vector<TileKind> t2;
t2.push_back(TileKind('B', 1));
t2.push_back(TileKind('E', 1));
t2.push_back(TileKind('R', 1));
Move m2 = Move(t2, 5, 7, Direction::DOWN);
b.place(m2);
vector<TileKind> t3;
t3.push_back(TileKind('A', 1));
t3.push_back(TileKind('N', 1));
t3.push_back(TileKind('L', 1));
t3.push_back(TileKind('E', 1));
t3.push_back(TileKind('R', 1));
Move m3 = Move(t3, 5, 10, Direction::DOWN);
b.place(m3);
vector<TileKind> t4;
t4.push_back(TileKind('I', 1));
Move m4 = Move(t4, 6, 9, Direction::DOWN);
b.place(m4);
}
class ComputerPlayerTest : public testing::Test {
protected:
ComputerPlayerTest() {}
virtual ~ComputerPlayerTest() {}
void crappy_print_hand();
void test_pts(PlaceResult res, unsigned int exp_pts);
};
void ComputerPlayerTest::test_pts(PlaceResult res, unsigned int exp_pts) {
bool pass = false;
if(res.points == exp_pts) {
pass = true;
} else if(res.points == exp_pts+50) {
pass = true;
}
if(!pass) {
std::cerr << "TEST FAILED: res.points = " << res.points << std::endl;
std::cerr << " EXPECTED: " << exp_pts << " or " << exp_pts+50 << std::endl;
}
EXPECT_TRUE(pass);
}
TEST_F(ComputerPlayerTest, empty_no_multipliers_no_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
vector<TileKind> t;
t.push_back(TileKind('A', 3));
t.push_back(TileKind('B', 1));
t.push_back(TileKind('F', 2));
t.push_back(TileKind('T', 1));
t.push_back(TileKind('N', 3));
t.push_back(TileKind('O', 7));
t.push_back(TileKind('S', 4));
cpu.add_tiles(t);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 8 8 - batons
test_pts(res, 19);
}
// Multipliers make no difference from the first move... so have a free one :)
TEST_F(ComputerPlayerTest, empty_with_multipliers_no_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
vector<TileKind> t;
t.push_back(TileKind('A', 3));
t.push_back(TileKind('B', 1));
t.push_back(TileKind('F', 2));
t.push_back(TileKind('T', 1));
t.push_back(TileKind('N', 3));
t.push_back(TileKind('O', 7));
t.push_back(TileKind('S', 4));
cpu.add_tiles(t);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 8 8 - batons
test_pts(res, 19);
}
TEST_F(ComputerPlayerTest, empty_no_multipliers_one_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
vector<TileKind> t;
t.push_back(TileKind('A', 3));
t.push_back(TileKind('B', 1));
t.push_back(TileKind('F', 2));
t.push_back(TileKind('T', 1));
t.push_back(TileKind('N', 3));
t.push_back(TileKind('?', 1));
t.push_back(TileKind('S', 4));
cpu.add_tiles(t);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 8 8 - faints
test_pts(res, 14);
}
TEST_F(ComputerPlayerTest, empty_no_multipliers_two_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
vector<TileKind> t;
t.push_back(TileKind('?', 1));
t.push_back(TileKind('B', 1));
t.push_back(TileKind('?', 1));
t.push_back(TileKind('T', 1));
t.push_back(TileKind('N', 3));
t.push_back(TileKind('O', 7));
t.push_back(TileKind('S', 4));
cpu.add_tiles(t);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 8 8 - bastion
test_pts(res, 18);
}
TEST_F(ComputerPlayerTest, simple_no_multipliers_no_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_simple_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 9 5 - ho in batons
test_pts(res, 31);
}
TEST_F(ComputerPlayerTest, simple_no_multipliers_one_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_simple_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 9 7 - ho in confab
test_pts(res, 29);
}
TEST_F(ComputerPlayerTest, simple_with_multipliers_no_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_simple_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 7 6 - ah si boast
test_pts(res, 40);
}
TEST_F(ComputerPlayerTest, simple_with_multipliers_one_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_simple_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 6 10 | hit oaten
test_pts(res, 38);
}
TEST_F(ComputerPlayerTest, two_words_no_multipliers_no_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_two_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 2 7 | na sa batons
test_pts(res, 28);
}
TEST_F(ComputerPlayerTest, two_words_no_multipliers_one_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_two_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 4 9 | an at fontina
test_pts(res, 24);
}
TEST_F(ComputerPlayerTest, two_words_with_multipliers_no_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_two_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 6 5 - sonata
test_pts(res, 39);
}
TEST_F(ComputerPlayerTest, two_words_with_multipliers_one_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_two_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 6 10 | hit oaten
test_pts(res, 38);
}
TEST_F(ComputerPlayerTest, long_no_multipliers_no_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_long_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 2));
t0.push_back(TileKind('B', 3));
t0.push_back(TileKind('K', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 7 7 - ob al si boas
test_pts(res, 32);
}
TEST_F(ComputerPlayerTest, long_with_multipliers_no_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_long_word(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 2));
t0.push_back(TileKind('B', 3));
t0.push_back(TileKind('K', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 9 6 - bb lo it sabot
test_pts(res, 47);
}
TEST_F(ComputerPlayerTest, concave_words_no_multipliers_no_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_concave_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 10 10 | se or sofa
test_pts(res, 29);
}
TEST_F(ComputerPlayerTest, concave_words_no_multipliers_one_blank) {
Board b = Board::read("config/board0.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_concave_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 5 7 | ab ne jaunty or banjo
test_pts(res, 37);
}
TEST_F(ComputerPlayerTest, concave_words_with_multipliers_no_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_concave_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('S', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 11 12 | rf fatso
test_pts(res, 51);
}
TEST_F(ComputerPlayerTest, concave_words_with_multipliers_one_blank) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 7);
place_concave_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('B', 1));
t0.push_back(TileKind('F', 2));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('N', 3));
t0.push_back(TileKind('O', 7));
t0.push_back(TileKind('?', 1));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 5 7 | ab ne jaunty or banjo
test_pts(res, 57);
}
TEST_F(ComputerPlayerTest, stress_test) {
Board b = Board::read("config/standard-board.txt");
Dictionary d = Dictionary::read(DICT_PATH);
ComputerPlayer cpu("cpu", 10);
place_concave_words(b);
//b.print(cout);
vector<TileKind> t0;
t0.push_back(TileKind('A', 3));
t0.push_back(TileKind('?', 1));
t0.push_back(TileKind('T', 1));
t0.push_back(TileKind('M', 3));
t0.push_back(TileKind('?', 1));
t0.push_back(TileKind('S', 4));
t0.push_back(TileKind('Z', 7));
t0.push_back(TileKind('P', 2));
t0.push_back(TileKind('D', 3));
t0.push_back(TileKind('F', 4));
cpu.add_tiles(t0);
Move m = cpu.get_move(b, d);
PlaceResult res = b.test_place(m);
// 3 10 | ma el se flamines
test_pts(res, 57);
}
| true |
7c0162e182f9df70324de4177067b010b5698674 | C++ | whitebluepants/OJ-Practice | /PAT-乙级/1015.cpp | UTF-8 | 2,130 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
using namespace std;
int read()
{
char ch = getchar();
int f = 1;
int x = 0;
while(ch < '0' || ch > '9'){if(ch == '-')f = 0;ch = getchar();}
while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}
return f?x:x*-1;
}
struct node
{
int number;
int de;
int cai;
};
int i,j,k,l;
node ans1[100001];
node ans2[100001];
node ans3[100001];
node ans4[100001];
bool cmp(node a,node b)
{
if(a.de + a.cai == b.de + b.cai)
{
if(a.de == b.de)
{
return a.number < b.number;
}
return a.de > b.de;
}
return a.de + a.cai > b.de + b.cai;
}
int main()
{
int n = read(),m = read(),h = read();
for(int t = 0;t < n;t ++)
{
int a = read(),b = read(),c = read();
if(b >= m && c >= m)
{
if(b >= h && c >= h)
{
ans1[i].number = a;
ans1[i].de = b;
ans1[i ++].cai = c;
}
else if(b >= h)
{
ans2[j].number = a;
ans2[j].de = b;
ans2[j ++].cai = c;
}
else if(b < h && c < h && b >= c)
{
ans3[k].number = a;
ans3[k].de = b;
ans3[k ++].cai = c;
}
else
{
ans4[l].number = a;
ans4[l].de = b;
ans4[l ++].cai = c;
}
}
}
sort(ans1,ans1 + i,cmp);
sort(ans2,ans2 + j,cmp);
sort(ans3,ans3 + k,cmp);
sort(ans4,ans4 + l,cmp);
printf("%d\n",i + j + k + l);
for(int t = 0;t < i;t ++)
{
printf("%08d %d %d\n",ans1[t].number,ans1[t].de,ans1[t].cai);
}
for(int t = 0;t < j;t ++)
{
printf("%08d %d %d\n",ans2[t].number,ans2[t].de,ans2[t].cai);
}
for(int t = 0;t < k;t ++)
{
printf("%08d %d %d\n",ans3[t].number,ans3[t].de,ans3[t].cai);
}
for(int t = 0;t < l;t ++)
{
printf("%08d %d %d\n",ans4[t].number,ans4[t].de,ans4[t].cai);
}
return 0;
} | true |
7b7bf03c7f049ccfdeee0ede686f37578ec3ea36 | C++ | cobraone/xfalcon | /tools/interfaces/collection.h | UTF-8 | 1,093 | 2.875 | 3 | [] | no_license | #ifndef COLLECTION_H
#define COLLECTION_H
#include "indexable.h"
#include "tools/exceptions.h"
namespace unity
{
namespace tools
{
namespace interfaces
{
template <typename Tindex, typename Tdata> struct Line
{
Tindex lname;
Tdata ldata;
Line()
{
}
Line(Tindex index, Tdata data)
{
lname = index;
ldata = data;
}
};
template <typename Tindex, typename Tdata> class Collection: public Indexable<Tindex, Tdata>
{
protected:
Collection()
{
}
virtual ~Collection()
{
}
public:
virtual bool exist(const Tindex &lname) = 0;
virtual Collection<Tindex, Tdata> &add(const Line<Tindex, Tdata> &line) = 0;
virtual Collection<Tindex, Tdata> &add(Tindex index, Tdata data) = 0;
virtual Tdata getFirst() { return NULL; }
virtual Tdata getNext() { return NULL; }
virtual Tdata getData(const Tindex &lname) = 0;
virtual Collection<Tindex, Tdata> &del(/*const Tindex &index*/)
{
warning("unity::tools::interfaces::Collection::del", W__NOT_YET_IMPLEMENTED);
return *this;
}
};
}
}
}
#endif // COLLECTION_H
| true |
bf3cee4fa3490b3b420828f724028291cda034f1 | C++ | wangq277/ofWeek6_2 | /src/ofApp.cpp | UTF-8 | 5,385 | 2.59375 | 3 | [] | no_license | #include "ofApp.h"
ofFbo fbo;
//ofImage leaf;
//--------------------------------------------------------------
vector<Line> leaves;
Line::Line(){
//leafImg.load("leaf.png");
// while(!leafImg.getWidth()); // loop here till loaded
//loc -= ofPoint(leafImg.getWidth()/2, leafImg.getHeight()/2);
// sTime = ofGetElapsedTimef();
// sWeight = ofRandom(0.1, 0.4);
// fallSpeed = ofRandom(2, 8);
}
void Line :: setup(){
loc = ofPoint(0,0,0);
sWeight= ofRandom(1,1.5);
n = ofRandom(0.1,2);
a = ofRandom(0.2,0.3);
b = ofRandom(0.3,0.4);
c = ofRandom(0.4,0.5);
rX = ofRandom(45);
rY = ofRandom(60);
rZ = ofRandom(30);
color.set(ofRandom(255),ofRandom(255),ofRandom(255));
fbo.allocate(ofGetWindowWidth(),ofGetWindowHeight());
fbo.begin();
ofClear(255,255,255,0);
fbo.end();
}
//--------------------------------------------------------------
void Line::update(){
// rX++;
// if(ofGetFrameNum()%3 == 0)
// rY++;
// if(ofGetFrameNum()%7 ==0)
// rZ++;
sTime = ofGetElapsedTimef()*n;
rX = ofSignedNoise(sTime * 0.2) * 400.0; // rotate +- 400deg
rY = ofSignedNoise(sTime * 0.3) * 400.0;
rZ = ofSignedNoise(sTime * 0.1) * 400.0;
scale = (1 - ofNoise(sTime * 0.2)) * sWeight;
dScaleX = (1 - ofNoise(sTime * a)) * ofRandom(1,10);
dScaleY = (1 - ofNoise(sTime * b)) * ofRandom(1,10);
dScaleZ = (1 - ofNoise(sTime * c)) * ofRandom(1,10);
//fallWiggle = ofSignedNoise(sTime * 0.6) * ofRandom(20, 70);
loc += ofPoint(dScaleX, dScaleY, dScaleZ);
}
//--------------------------------------------------------------
void Line::draw() {
fbo.begin();
ofSetColor(255, 255, 255, 5);
ofDrawRectangle(0, 0, ofGetWidth(), ofGetHeight());
//float z = ofSignedNoise((ofGetElapsedTimef() + sTime) * 0.9) * 400;
ofPushMatrix();
ofTranslate(loc.x, loc.y, loc.z);
// ofScale(dScaleX, dScaleY, dScaleZ); // can be 3 dimensional
ofScale(dScaleX, dScaleY, dScaleZ);
ofRotateX(rX);
ofRotateY(rY);
ofRotateZ(rZ);
// leafImg.draw(0 - leafImg.getWidth()/2, 0 - leafImg.getHeight()/2); // draw at new 0,0
ofSetColor(color);
ofDrawLine(-10, 0, 10, 0);
ofPopMatrix();
fbo.end();
ofSetColor(255);
fbo.draw(0,0);
}
void ofApp::setup(){
// leaf.load("leaf.png");
// fbo.allocate(ofGetWidth(), ofGetHeight()); // higher precision alpha (no artifacts)
//
// fbo.begin();
// ofClear(255,255,255, 0);
// fbo.end();
for(int i=0; i<5; i++){
Line newLine;
newLine.setup();
leaves.push_back(newLine);
}
}
//float rX = 0;
//float rY = 0;
//float rZ = 0;
//----------------------------------------------------------------------------
void ofApp::update(){
for(int i; i < leaves.size(); i++) {
leaves[i].update();
if (leaves[i].loc.y > ofGetHeight()) { // age it out
leaves.erase(leaves.begin() + i);
Line newLine;
newLine.setup();
leaves.push_back(newLine);
// if(leaves[i].loc.y<0||leaves[i].loc.y>ofGetWindowHeight()||leaves[i].loc.x<0|leaves[i].loc.x>ofGetWindowWidth()){
// leaves.erase(leaves.begin()+i);
// Line newLine;
// newLine.setup();
// leaves.push_back(newLine);
}
}
}
void ofApp::draw(){
ofBackground(255);
//
// fbo.begin();
// ofSetColor(255,255,255, 10);
// ofDrawRectangle(0,0,ofGetWidth(),ofGetHeight());
//
// ofPushMatrix();
// ofTranslate(ofGetWidth()/2, ofGetHeight()/2);
//
// ofScale(0.3, 0.3, 0.3); //can be 3 dimensional
//
//// ofRotateX(rX);
//// ofRotateY(rY);
//// ofRotateZ(rZ);
// // leaf.draw(0 - leaf.getWidth()/2, 0 - leaf.getHeight()/2); //draw at new 0,0
// ofSetColor(0);
// ofDrawLine(-60, 500, 60, 500);
// ofDrawLine(-120, 500, 120, 500);
// ofPopMatrix();
for(int i=0; i<leaves.size(); i++){
leaves[i].draw();
}
// fbo.end();
// fbo.draw(0,0);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| true |
c520bccae10f44d2cf5f0a3021e285a6673df8f9 | C++ | nkunal1992/Coding_Practice | /GeeksForGeeks/Array/17_floor_ceil_in_sorted_array.cpp | UTF-8 | 1,682 | 4.28125 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
/*
floor(x) : largest element in array smaller than x
ceil(x) : smallest element in array greater than x
Approach : use binary search
*/
int ceil(int *a, int n, int x){
int start = 0, end = n-1, mid;
while(start <= end){
mid = (start + end)/2;
if(x < a[start]) // first element itself is ceil
return a[start];
if(x > a[end]) //ceil doesn't exist
return -1;
if(a[mid] == x) //element itself is ceil
return a[mid];
else if(x < a[mid]){ //ceil lies in left part
if(mid-1 <= start && x >= a[mid-1])
return a[mid];
else
end = mid-1;
}
else{ //ceil lies in right part
if(mid+1 <= end && x < a[mid+1])
return a[mid+1];
else
start = mid+1;
}
}
}
int floor(int *a, int n, int x){
int start = 0, end = n-1, mid;
while(start <= end){
if(x < a[start]) return -1;
if(x > a[end]) return a[end];
mid = (start + end)/2;
if(a[mid] == x)
return a[mid];
else if(x < a[mid]){ //floor lies in left side
if(mid-1 >= start && x > a[mid-1])
return a[mid-1];
else
end = mid-1;
}
else{// floor lies on right side
if(mid+1 <= end && x <= a[mid+1])
return a[mid];
else
start = mid+1;
}
}
}
int main(){
int arr[] = {1,2,8,10,10,12,19};
int n = sizeof(arr)/sizeof(arr[0]);
cout<<floor(arr,n,5)<<endl;
} | true |
4255fd8ffd2f1287e716c03b6b2db886c0c02f19 | C++ | mikim42/OCW | /ocw_src/players.cpp | UTF-8 | 11,220 | 2.625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* players.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mikim <mikim@student.42.us.org> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/05/10 15:58:55 by mikim #+# #+# */
/* Updated: 2019/05/11 10:27:14 by mikim ### ########.fr */
/* */
/* ************************************************************************** */
/* ************************************************************************** */
/* Mingyun Kim */
/* https://www.github.com/mikim42 */
/* ************************************************************************** */
#include <ocw.hpp>
// Michael
bool movable(char b, int n)
{
char c = 'a' + n - 1;
return (b != '*' && b != c);
}
int minDist(int p1, int p2)
{
int y1, x1;
GET_POS(p1, y1, x1);
int y2, x2;
GET_POS(p2, y2, x2);
return static_cast<int>(floor(sqrt(pow(static_cast<double>(x2 - x1), 2) + pow(static_cast<double>(y2 - y1), 2))));
}
std::vector<int> getEnemies(int myId)
{
std::vector<int> enemies;
for (int p = 1; p <= PLAYER_NUM; ++p)
{
if (p == myId)
continue;
enemies.emplace_back(p);
}
return enemies;
}
int closestPlayer(int myId)
{
int closestPlayer = 0, dist = 0, tmp;
std::vector<int> enemies = getEnemies(myId);
for (int p = 0; p < static_cast<int>(enemies.size()); ++p)
{
int enemy = enemies[p];
tmp = minDist(myId, enemy);
if (!closestPlayer || tmp < dist)
{
closestPlayer = enemy;
dist = tmp;
}
}
return closestPlayer;
}
// Michael
bool inBounds(int x, int y)
{
return (x >= 0 && y >= 0 && x < WIDTH && y < HEIGHT);
}
int closestDirection(int myId, int enemyId)
{
int myY, myX, enemyY, enemyX;
GET_POS(myId, myY, myX);
GET_POS(enemyId, enemyY, enemyX);
if (abs(enemyX - myX) > abs(enemyY - myY))
{
//Further away on X-axis
if (enemyX > myX)
{
//Move right
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
//Try to move vertically to avoid obstacles
if (enemyY > myY)
{
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
}
else
{
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
}
//Stuck
return LEFT;
}
else
{
//Move left
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
//Try to move vertically to avoid obstacles
if (enemyY > myY)
{
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
}
else
{
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
}
//Stuck
return RIGHT;
}
}
else if (abs(enemyY - myY) > abs(enemyX - myX))
{
//Further away on Y-axis
if (enemyY > myY)
{
//Move down
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
//Try to move horizontally to avoid obstacles
if (enemyX > myY)
{
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
}
else
{
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
}
//Stuck
return UP;
}
else
{
//Move up
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
//Try to move horizontally to avoid obstacles
if (enemyX > myY)
{
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
}
else
{
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
}
//Stuck
return DOWN;
}
}
else if (abs(enemyX - myX) == abs(enemyY -myY))
{
//Equal distance, default to direction map is larger in
if (WIDTH > HEIGHT)
{
//Further away on X-axis
if (enemyX > myX)
{
//Move right
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
//Try to move vertically to avoid obstacles
if (enemyY > myY)
{
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
}
else
{
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
}
//Stuck
return LEFT;
}
else
{
//Move left
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
//Try to move vertically to avoid obstacles
if (enemyY > myY)
{
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
}
else
{
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
}
//Stuck
return RIGHT;
}
}
else
{
//If taller or equal, move on y-axis
//Further away on Y-axis
if (enemyY > myY)
{
//Move down
if (inBounds(myX, myY + 1) && movable(MAP[myY + 1][myX], myId))
return DOWN;
//Try to move horizontally to avoid obstacles
if (enemyX > myY)
{
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
}
else
{
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
}
//We're stuck
return UP;
}
else
{
//Move up
if (inBounds(myX, myY - 1) && movable(MAP[myY - 1][myX], myId))
return UP;
//Try to move horizontally to avoid obstacles
if (enemyX > myY)
{
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
}
else
{
if (inBounds(myX - 1, myY) && movable(MAP[myY][myX - 1], myId))
return LEFT;
if (inBounds(myX + 1, myY) && movable(MAP[myY][myX + 1], myId))
return RIGHT;
}
//Stuck
return DOWN;
}
}
}
return rand() % 4 + 1;
}
//PLAYER FUNCTION "dat-boi" Michael
int player1(void)
{
int myId, closestId;
myId = GET_PLAYER_NUMBER("dat-boi");
closestId = closestPlayer(myId);
if (closestId)
return closestDirection(myId, closestId);
return rand() % 4 + 1;
}
// Wen clorox
int player5(void)
{
int my_num;
int x,y;
my_num = GET_PLAYER_NUMBER("clorox");
GET_POS(my_num, y, x);
//left bound
if(x == 0 && y < HEIGHT - 1)
return DOWN;
else if(y == 0 && x < WIDTH - 1)
return RIGHT;
else if(x == WIDTH - 1 && y < HEIGHT - 1)
return DOWN;
else if(y == HEIGHT - 1 && x == 0)
return RIGHT;
else if(y == HEIGHT - 1 && x < WIDTH - 1)
return UP;
else if(y > 0 && y < HEIGHT - 1 && x > 0 && x < WIDTH - 1)
return LEFT;
else
return UP;
}
//Bhavi bot
int player4(void)
{
int my_num;
int x, y;
int a=0;
my_num = GET_PLAYER_NUMBER("bot");
GET_POS(my_num, y, x);
if (x==a )
{
if(y==a )
return RIGHT;
else
return UP;
}
else if(y==a )
{
if(x==WIDTH-1 )
return DOWN;
else
return RIGHT;
}
else if(x==WIDTH-1 )
{
if(y==HEIGHT-1)
return LEFT;
else
return DOWN;
}
else
return LEFT;
}
// Josh terminator
int player3(void)
{
int my_num, y, x;
bool previous = false;
my_num = GET_PLAYER_NUMBER("Terminator");
GET_POS(my_num, y, x);
if (!previous)
{
if (y > 0 && x > 0 && movable(MAP[y - 1][x], my_num))//check boundary
{
std::cout << "You're a Seg Fault";
previous = true;
return RIGHT;
}
if (y < HEIGHT - 1 && x < WIDTH - 1 && movable(MAP[y + 1][x], my_num)) //check boudnary
{
std::cout << "You're a Seg Fault";
previous = true;
return UP;
}
if (x > 0 && movable(MAP[y][x - 1], my_num))
{
std::cout << "You're a Seg Fault ";
return DOWN;
}
}
std::cout << "You're a Seg Fault";
return LEFT;
}
// Anthony
int player2(void)
{
int my_num;
int x, y;
char my_letter;
char e_letter;
//MAP 2d array
my_num = GET_PLAYER_NUMBER("Anthony");
// get player letter
switch(my_num)
{
case 1: my_letter = 'A'; break;
case 2: my_letter = 'B'; break;
case 3: my_letter = 'C'; break;
case 4: my_letter = 'D'; break;
}
// search players !myself
for(int i=0; i< WIDTH; i++) {
for(int j=0; j< HEIGHT; j++) {
if(MAP[i][j] == 'A' && MAP[i][j] != my_letter)
e_letter = 'A';
else if(MAP[i][j] == 'B' && MAP[i][j] != my_letter)
e_letter = 'B';
else if(MAP[i][j] == 'C' && MAP[i][j] != my_letter)
e_letter = 'C';
else if(MAP[i][j] == 'D' && MAP[i][j] != my_letter)
e_letter = 'D';
}
}
// get and set current position
GET_POS(my_num, y, x);
// search for dots first
//~ if(y > 0 && MAP[y-1][x] == '.' && movable(MAP[y - 1][x], my_num))
//~ return UP;
//~ else if (y < HEIGHT - 1 && movable(MAP[y + 1][x], my_num) && MAP[y + 1][x] == '.')
//~ return DOWN;
//~ else if (x > 0 && movable(MAP[y][x - 1], my_num) && MAP[y][x - 1] == '.')
//~ return LEFT;
//~ else if (x > 0 && movable(MAP[y][x + 1], my_num) && MAP[y][x + 1] == '.')
//~ return RIGHT;
// look for enemy taken spots
if(y > 0 && MAP[y-1][x] == e_letter && movable(MAP[y - 1][x], my_num))
return UP;
else if (y < HEIGHT - 1 && movable(MAP[y + 1][x], my_num) && MAP[y + 1][x] == e_letter)
return DOWN;
else if (x > 0 && movable(MAP[y][x - 1], my_num) && MAP[y][x - 1] == e_letter)
return LEFT;
else if (x > 0 && movable(MAP[y][x + 1], my_num) && MAP[y][x + 1] == e_letter)
return RIGHT;
// default
if (y > 0 && movable(MAP[y - 1][x], my_num))
return UP;
else if (y < HEIGHT - 1 && movable(MAP[y + 1][x], my_num))
return DOWN;
else if (x > 0 && movable(MAP[y][x - 1], my_num))
return LEFT;
else
return RIGHT;
}
| true |
7eb2d3c3c52ced957abc59966b99b6ac1b7cf3a7 | C++ | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/arc013/D/2068853.cpp | UTF-8 | 5,575 | 2.734375 | 3 | [] | no_license | #include <algorithm>
#include <cmath>
#include <complex>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using ll = long long int;
#define int ll
const int MOD = 1e9 + 7;
const int INF = 1e15 + 373;
#define rep(i, n) for (int i = 0; i < (n); ++i)
template <typename T>
using vector2 = vector<vector<T>>;
template <typename T>
vector2<T> init_vector2(size_t n0, size_t n1, T e = T()) {
return vector2<T>(n0, vector<T>(n1, e));
}
template <typename T>
using vector3 = vector<vector<vector<T>>>;
template <typename T>
vector3<T> init_vector3(size_t n0, size_t n1, size_t n2, T e = T()) {
return vector3<T>(n0, vector2<T>(n1, vector<T>(n2, e)));
}
template <typename T1, typename T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& p) {
os << "(" << p.first << ", " << p.second << ")";
return os;
}
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v) {
os << "[";
for (T e : v) {
os << e << ", ";
}
os << "]";
return os;
}
map<int, int> compress(const vector<int>& a) {
vector<int> b(a);
sort(b.begin(), b.end());
b.erase(unique(b.begin(), b.end()), b.end());
map<int, int> c;
int m = b.size();
rep(i, m) { c[b[i]] = i; }
return c;
}
/********************************************************************************/
class edge {
public:
int from;
int to;
int cost;
int rev;
edge() : from(0), to(0), cost(0), rev(0) {}
edge(int from, int to, int cost, int rev)
: from(from), to(to), cost(cost), rev(rev) {}
bool operator==(const edge& e) const {
return from == e.from && to == e.to && cost == e.cost;
}
bool operator<(const edge& e) const {
if (cost != e.cost) {
return cost < e.cost;
}
return from == e.from ? to < e.to : from < e.from;
}
};
void add_edge(vector2<edge>& g, int from, int to, int cost) {
g[from].push_back(edge(from, to, cost, g[to].size()));
g[to].push_back(edge(to, from, 0, g[from].size() - 1));
}
vector2<edge> build_graph(int m, const vector<pair<int, int>>& ps) {
vector2<edge> g(2 * m + 2);
int s = 2 * m;
int t = 2 * m + 1;
for (const pair<int, int>& p : ps) {
add_edge(g, p.first, p.second + m, 1);
add_edge(g, p.second, p.first + m, 1);
}
rep(i, m) {
add_edge(g, s, i, 1);
add_edge(g, i + m, t, 1);
}
return g;
}
vector<int> bfs(int n, const vector2<edge>& g, int s) {
vector<int> dep(n, -1);
dep[s] = 0;
queue<int> q;
q.push(s);
while (!q.empty()) {
int v = q.front();
q.pop();
for (const edge& e : g[v]) {
if (e.cost > 0 && dep[e.to] == -1) {
dep[e.to] = dep[v] + 1;
q.push(e.to);
}
}
}
return dep;
}
int dfs(int n, vector2<edge>& g, const vector<int>& dep, int v, int t, int f,
vector<int>& itr) {
if (v == t) {
return f;
}
for (; itr[v] < (int)g[v].size(); itr[v]++) {
const edge& e = g[v][itr[v]];
if (e.cost > 0 && dep[v] < dep[e.to]) {
int ans = dfs(n, g, dep, e.to, t, min(f, e.cost), itr);
if (ans > 0) {
g[v][itr[v]].cost -= ans;
g[e.to][e.rev].cost += ans;
return ans;
}
}
}
return 0;
}
int maxflow(int n, const vector2<edge>& g_, int s, int t) {
vector2<edge> g(g_);
int ans = 0;
while (1) {
vector<int> dep = bfs(n, g, s);
if(dep[t] == -1){
break;
}
vector<int> itr(n);
while (1) {
int flow = dfs(n, g, dep, s, t, INF, itr);
if(flow == 0){
break;
}
ans += flow;
}
}
return ans;
}
signed main() {
int n;
cin >> n;
vector<int> xs(n);
vector<int> ys(n);
vector<int> zs(n);
rep(i, n) { cin >> xs[i] >> ys[i] >> zs[i]; }
vector<pair<int, int>> ps;
rep(i, n) {
int x = xs[i];
int y = ys[i];
int z = zs[i];
for (int j = 1; j < x; j++) {
int v0 = j * y * z;
int v1 = (x - j) * y * z;
ps.push_back(make_pair(min(v0, v1), max(v0, v1)));
}
for (int j = 1; j < y; j++) {
int v0 = x * j * z;
int v1 = x * (y - j) * z;
ps.push_back(make_pair(min(v0, v1), max(v0, v1)));
}
for (int j = 1; j < z; j++) {
int v0 = x * y * j;
int v1 = x * y * (z - j);
ps.push_back(make_pair(min(v0, v1), max(v0, v1)));
}
}
sort(ps.begin(), ps.end());
ps.erase(unique(ps.begin(), ps.end()), ps.end());
vector<int> vs;
for (const pair<int, int>& p : ps) {
vs.push_back(p.first);
vs.push_back(p.second);
}
map<int, int> cmap = compress(vs);
rep(i, (int)ps.size()) {
ps[i].first = cmap[ps[i].first];
ps[i].second = cmap[ps[i].second];
}
int m = cmap.size();
vector2<edge> g = build_graph(m, ps);
int ans = maxflow(g.size(), g, 2 * m, 2 * m + 1);
cout << ans + (2 * m - 2 * ans) << endl;
return 0;
} | true |
cef5c5fcbb298c1b16fa582f73efeacf09a022db | C++ | BenW0/humidity-sensor | /simpleStats.h | UTF-8 | 2,402 | 3.359375 | 3 | [
"MIT"
] | permissive |
#include <string>
#ifndef SIMPLE_STATS_BUFFER_SIZE
#define SIMPLE_STATS_BUFFER_SIZE 128
#endif
struct SampleType
{
float temp;
float humidity;
void PrintOut() const
{
Serial.print("Temp: ");
Serial.print(temp);
Serial.print(" Humidity: ");
Serial.print(humidity);
}
String AsString() const
{
return "Temp = " + String(temp) + "; Humidity = " + String(humidity);
}
void KeepMax(SampleType const &other)
{
temp = max(temp, other.temp);
humidity = max(humidity, other.humidity);
}
void KeepMin(SampleType const &other)
{
temp = min(temp, other.temp);
humidity = min(humidity, other.humidity);
}
SampleType operator+(SampleType const &other) const
{
return {temp + other.temp, humidity + other.humidity};
}
void operator+=(SampleType const &other)
{
temp += other.temp;
humidity += other.humidity;
}
SampleType operator*(float other) const
{
return {temp * other, humidity * other};
}
SampleType operator/(float denom) const
{
return {temp / denom, humidity / denom};
}
};
const SampleType ZeroSample{0., 0.};
const SampleType SmallSample{-200, -1};
const SampleType LargeSample{2000, 101};
class SimpleStats
{
public:
using callback_t = void(*)(const SampleType&, const SampleType&, const SampleType&, const uint16_t&);
SimpleStats(callback_t callback_) : callback(callback_)
{
count = 0;
}
void Log(SampleType sample)
{
buffer[count++] = sample;
if (count == SIMPLE_STATS_BUFFER_SIZE - 1)
{
callback(GetAverage(), GetMin(), GetMax(), badSamples);
count = 0;
badSamples = 0;
}
}
void LogBadSample()
{
badSamples++;
}
SampleType GetMin() const
{
SampleType minVal = LargeSample;
for(uint16_t i = 0; i < count; ++i)
{
minVal.KeepMin(buffer[i]);
}
return minVal;
}
SampleType GetMax() const
{
SampleType maxVal = SmallSample;
for (uint16_t i = 0; i < count; ++i)
{
maxVal.KeepMax(buffer[i]);
}
return maxVal;
}
SampleType GetAverage() const
{
SampleType val = ZeroSample;
if (count == 0)
return val;
for (uint16_t i = 0; i < count; ++i)
{
val += buffer[i];
}
return val / count;
}
private :
callback_t callback;
SampleType buffer[SIMPLE_STATS_BUFFER_SIZE];
uint16_t count{0};
uint16_t badSamples{0};
};
| true |
4f2727ea87811affe0ae0153c5221d00765e6c90 | C++ | fabrizio-indirli/WhistleDrivenRobot | /receiver/src/communication/USBSerialCommunication.h | UTF-8 | 665 | 2.71875 | 3 | [] | no_license | #include <Arduino.h>
#include "SerialCommunication.h"
#ifndef USBSERIALCOMMUNICATION_H_
#define USBSERIALCOMMUNICATION_H_
/**
* This object is used to handle a USB serial connection.
* This class doesn't need any proper objects since all the require information
* is on the Serial object of Arduino. This class exists only to standardize
* the connection with the Bluetooth one.
*/
class USBSerialCommunication : public SerialCommunication {
public:
USBSerialCommunication();
void updateBuffer();
void print(String* string);
private:
/**
* This is the baud rate of the serial channel.
*/
static const int BR = 9600;
};
#endif | true |
1798242f6206824f5e56b2c957e9ad4992c72ef9 | C++ | zhj12138/CalcMethods-HITSZ-2021 | /Homework/2-2.cpp | UTF-8 | 486 | 2.765625 | 3 | [] | no_license | //
// Created by 15502 on 2021/3/15.
//
#include<bits/stdc++.h>
using namespace std;
const double a = 115;
const double e = 1e-7;
double iter(double x){
return 1.5 * x - 1 / (2 * a) * x * x * x;
}
int main() {
double x1 = 10, x2;
cout << setprecision(10);
while(true){
x2 = iter(x1);
cout << x2 << endl;
// cout << abs(x2 - x1) << endl;
if(abs(x2 - x1) < e) break;
x1 = x2;
}
cout << "ans: " << x2 << endl;
return 0;
}
| true |
79c047c4ffc1fd650a49b7d48a7fc663d4c795e9 | C++ | FKgk/BOJ | /1256.cpp | UTF-8 | 715 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <algorithm>
#define MAX_K 1000000010
using namespace std;
int N, M, K;
int pascal[202][202];
void calPascal()
{
for (int i = 0; i <= N + M; i++)
{
pascal[i][0] = pascal[i][i] = 1;
for (int j = 1; j < i; j++)
pascal[i][j] = min(MAX_K, pascal[i - 1][j - 1] + pascal[i - 1][j]);
}
}
string solve(int n, int m, int skip)
{
if (n == 0)
return string(m, 'z');
if (skip <= pascal[n + m - 1][n - 1])
return "a" + solve(n - 1, m, skip);
return "z" + solve(n, m - 1, skip - pascal[n + m - 1][n - 1]);
}
int main(void)
{
cin >> N >> M >> K;
calPascal();
if (pascal[N + M][N] < K)
cout << "-1" << endl;
else
cout << solve(N, M, K);
return 0;
}
| true |
c222611eb5fd42daa66b50fd1de7ff30e5827aa5 | C++ | bowles123/CS-1410-Projects | /BankLineSimulation/BankLineSimulator.cpp | UTF-8 | 2,695 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include "BankLineSimulator.h"
BankLineSimulator::BankLineSimulator()
{
currentTime = 0;
serviceEndTime = 0;
longest = 0;
maxLength = 0;
customers = 0;
servicingCustomer = false;
firstCustomer = true;
}
bool BankLineSimulator::endOfDay()
{
return currentTime >= businessTime;
}
void BankLineSimulator::displayDay()
{
std::cout << "The longest a customer waited was: " << longest << " minutes." << std::endl;
std::cout << "The biggest the line got was: " << maxLength << " people at a time." << std::endl;
std::cout << "The total amount of customers was: " << customers << " customers." << std::endl;
}
void BankLineSimulator::displayGreeting()
{
std::cout << "Hello, this program simulates a line at a bank" << std::endl;
std::cout << "How long would you like to run the simulation? (480 = 8 hours): ";
std::cin >> businessTime;
}
int BankLineSimulator::randomInt()
{
return (rand() % 4) + 1;
}
void BankLineSimulator::addCustomer()
{
line.push(currentTime);
customers++;
nextArrival = randomInt() + currentTime;
// Output for the first customer.
if (!firstCustomer)
std::cout << "Another customer arrived at " << currentTime << " minutes." << std::endl;
else
{
std::cout << "The first customer arrived at " << currentTime << " minutes." << std::endl;
firstCustomer = false;
}
}
void BankLineSimulator::completeCustomerService()
{
servicingCustomer = false;
std::cout << "Customer was finshed being serviced at " << currentTime << " minutes." << std::endl;
}
int BankLineSimulator::getCustomerWaitTime()
{
servicingCustomer = true;
int waitTime = currentTime - line.front();
serviceEndTime = currentTime + randomInt();
line.pop();
return waitTime;
}
void BankLineSimulator::simulateLine()
{
srand(time(0));
displayGreeting();
nextArrival = randomInt();
// Run the program as long as the day isn't over or someone is still being serviced.
while (!endOfDay() || servicingCustomer)
{
// Add customer to the queue.
if (currentTime >= nextArrival && !endOfDay())
addCustomer();
// If it's time to service a customer pull them from the queue.
if (currentTime >= serviceEndTime && servicingCustomer)
completeCustomerService();
// Get the wait time of the customer if there is no one being serviced and the line is empty.
if (!servicingCustomer && !line.empty())
{
int time = getCustomerWaitTime();
if (time > longest)
longest = time;
}
// Find the biggest the line ever got.
if (line.size() > maxLength)
maxLength = line.size();
// Check to see if the day is over, if it is then finish servicing customers until the queue is empty.
endOfDay();
currentTime++;
}
displayDay();
} | true |
06d5e6315c30089cbf49660a0ae685b577e8d908 | C++ | wdudek82/learning-cpp | /second/main.cpp | UTF-8 | 977 | 3.5625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int students;
int candies;
int percapita;
int remains;
int main() {
cout << "How many students: ";
cin >> students;
cout << "How many candies: ";
cin >> candies;
percapita = candies / (students - 1);
remains = candies % (students - 1);
cout << "Each student will have " << percapita << " candies; " << remains << " remains" << endl;
if (remains >= 5) {
cout << "It quite much!";
} else {
cout << "Not that much!";
}
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << "Print: " << i << endl;
}
while (remains > 0) {
remains--;
cout << "Omnomnom (one down), " << remains << " remains" << endl;
}
cout << "Ate them all!" << endl;
return 0;
switch (remains) {
case 7:
cout << "Enough!";
break;
default:
cout << "Ble...";
}
} | true |
84ea5df1246bca10c8266892bd06845ec4206b92 | C++ | eoma/gm-engine | /src/Core/Utilities/BufferOperations.cpp | UTF-8 | 599 | 2.5625 | 3 | [] | no_license | #include "GM/Core/Utilities/BufferOperations.h"
namespace GM {
namespace Core {
void BufferOperations::upload_unsafe(const GLenum target,
const std::function<void(void *destination, size_t size)> &upload_function,
GLsizeiptr length, GLintptr offset)
{
// Assume the buffer is bound
void *destination = glMapBufferRange(target, offset, length,
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_RANGE_BIT);
if (destination == nullptr) {
throw clan::Exception("Unable to map buffer range!");
}
upload_function(destination, length);
glUnmapBuffer(target);
}
} // namespace Core
} // namespace GM
| true |
f9b386e200add2c010dd1b344dc1b5eb57650dbf | C++ | asw221/thresh | /src/RandWalkParam.h | UTF-8 | 2,157 | 3.328125 | 3 | [] | no_license |
#ifndef _RAND_WALK_PARAM_
#define _RAND_WALK_PARAM_
#include <algorithm>
#include <cmath>
using namespace std;
template < typename T = double >
class RandWalkParam
{
private:
T Kernel; // jumping kernel
T firstMoment; // var's approx 1st moment for updating kernel
T secondMoment; // var's approx 2nd moment for updating kernel
double scale; // kernel scaling factor
double p; // jumping probability
int n; // number of iterations since last update
public:
RandWalkParam() {
p = 0.0;
n = 0;
scale = 1.0;
};
RandWalkParam(const T &Kern) {
scale = 1.0;
setKernel(Kern);
};
// Sets the data used to update the jumping kernel to 0. Does NOT
// zero the kernel itself nor the kernel scaling constant
void clear() {
p = 0.0;
n = 0;
firstMoment *= 0;
secondMoment *= 0;
};
void updateParams(const T &data, const double &prob) {
n++;
p += prob;
firstMoment += data;
secondMoment += data * data;
};
void updateKernel() {
T fm = getFirstMoment();
Kernel = sqrt(getSecondMoment() - (fm * fm));
};
void setScale(const double &sc) {
scale = sc;
};
void setKernel(const T &Kern) {
Kernel = Kern;
firstMoment = Kern;
secondMoment = Kern;
clear();
};
double getProb() const {
return (p / max(n, 1));
};
int getN() const {
return (n);
};
T getKernel() const {
return (Kernel * scale);
};
T getFirstMoment() const {
return (firstMoment / max(n, 1));
};
T getSecondMoment() const {
return (secondMoment / max(n - 1, 1));
};
double getScale() const {
return (scale);
};
// void print () const {
// cout << "Kernel:" << std::endl << getKernel() << std::endl
// << "First Moment:" << std::endl << getFirstMoment() << std::endl
// << "Second Moment:" << std::endl << getSecondMoment() << std::endl
// << "scale:" << std::endl << getScale() << std::endl
// << "p:" << std::endl << getProb() << std::endl
// << "N:" << std::endl << getN() << std::endl << std::endl;
// };
};
#endif // _RAND_WALK_PARAM_
| true |
d2ef1c9223a092e397d9ac0c9e758e99efeb84aa | C++ | fachinformatiker/DIY_modular_Arduino | /arduino_janky_sequencer/arduino_janky_sequencer.ino | UTF-8 | 1,268 | 3.40625 | 3 | [] | no_license | /*
* A janky sort of sequencer module. It takes a trigger and an analog signal.
* When the trigger goes high it samples a 6-bit value from the analog signal and uses those bits to toggle its outputs ON/OFF. Outputs are spit out on PORTB.
* It also has the option to read a second analog signal and use some bitwise operators to manipulate to outputs.
*
* MODULE FINISHED. No optimizations necessary.
*/
//pins
const byte inputPins[2] = {A0, A1};
const byte modePin = A2;
const byte triggerPin = 17;
//state variables
bool trigger = 0;
byte output = 0;
byte in1 = 0;
byte in2 = 0;
byte mode = 0;
void read_trigger() {
if (digitalRead(triggerPin) == true and trigger == false) {
in1 = analogRead(inputPins[0]) >> 4;
in2 = analogRead(inputPins[1]) >> 4;
trigger = true;
}
else if (digitalRead(triggerPin) == false and trigger == true) {
trigger = false;
}
}
void setup() {
for (byte i=8;i<14;i++) {
pinMode(i, OUTPUT);
}
}
void loop() {
read_trigger();
mode = analogRead(modePin) >> 8;
if (mode == 0) { output = in1; }
else if (mode == 1) { output = in1 | in2; }
else if (mode == 2) { output = in1 & in2; }
else { output = in1 ^ in2; }
PORTB = output;
}
| true |
b4f7854c5a8053f5b15680aebd0efef6e287cc4f | C++ | ray1944/verifybed | /c-cpp/refofarr.cpp | UTF-8 | 399 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int arr[10] = {1, 2, 3, 4};
int * const & rarr = arr;
//int const * & rarr1 = arr;
//int * & rarr2 = arr;
int const* const & rarr3 = arr; //const array
int idx;
rarr [9] = 13;
for(idx = 0 ; idx < 10; idx++) {
cout << rarr[idx] << " ";
}
cout << endl;
// rarr3[3] = 5;
return 0;
} | true |
2e4a4c7b09f650429c4349970af19bb4c02c914e | C++ | xucaimao/netlesson | /pa3/exam-08.cpp | UTF-8 | 949 | 3.4375 | 3 | [] | no_license | // 程序设计与算法(三)期末考试(2018秋季)
// 008:编程填空:还是Fun和Do
// Created by Administrator on 2018-11-10.
//填写代码,使输出结果为
//A::Fun
//B::Do
//C::Fun
//C::Do
//A::Fun
//B::Do
//
#include <iostream>
using namespace std;
class A {
public:
virtual void Fun() {
cout << "A::Fun" << endl;
};
virtual void Do() {
cout << "A::Do" << endl;
}
};
// 在此处补充你的代码
class B:public A{
public:
void Do() {
cout << "B::Do" << endl;
}
};
class C:public B{
public:
virtual void Fun() {
cout << "C::Fun" << endl;
};
virtual void Do() {
cout << "C::Do" << endl;
}
};
//这里的&很关键,没有的话,这个p就是执行A类型的了
void Call1(A &p)
{
p.Fun();
p.Do();
}
void Call2(B p) {
p.Fun();
p.Do();
}
int main() {
C c;
B b;
Call1(b);
Call1(c);
Call2(c);
return 0;
} | true |
d0d61f95e58fe2500ea5975411d55a8e60173eca | C++ | aashreyj/oops-lab | /operator_overloading/matrix.cpp | UTF-8 | 4,054 | 3.84375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class matrix
{
public:
int **mat;
matrix() //constructor
{
int i, j;
mat = new int* [3];
for(i = 0; i < 3; i++)
mat[i] = new int [3];
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
mat[i][j] = 0;
}
matrix(const matrix &a) //copy constructor
{
int i, j;
mat = new int* [3];
for(i = 0; i < 3; i++)
mat[i] = new int [3];
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
mat[i][j] = a.mat[i][j];
}
~matrix() //destructor
{
int i;
for(i = 0; i < 3; i++)
delete[] mat[i];
delete[] mat;
}
void input(void);
void display(void);
matrix operator+(matrix&); //addition
matrix operator-(matrix&); //subtraction
matrix operator!(void); //transpose
matrix operator-(void); //negation
int operator~(void); //determinant
};
void matrix::input()
{
int i, j;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
{
cout<<"Enter value: ";
cin>>mat[i][j];
}
}
void matrix::display()
{
int i,j;
for(i = 0; i < 3; i++)
{
for(j = 0;j < 3; j++)
cout<<mat[i][j]<<" ";
cout<<endl;
}
}
matrix matrix::operator+(matrix &b)
{
matrix result;
int i, j;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
result.mat[i][j] = mat[i][j] + b.mat[i][j];
return result;
}
matrix matrix::operator-(matrix &b)
{
matrix result;
int i, j;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
result.mat[i][j] = mat[i][j] - b.mat[i][j];
return result;
}
matrix matrix::operator-()
{
matrix result;
int i, j;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
result.mat[i][j] = -mat[i][j];
return result;
}
matrix matrix::operator!()
{
matrix result;
int i, j;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
result.mat[i][j] = mat[j][i];
return result;
}
int matrix::operator~()
{
return (mat[0][0] * (mat[1][1]*mat[2][2] - mat[1][2]*mat[2][1])) - (mat[0][1] * (mat[1][0]*mat[2][2] - mat[1][2]*mat[2][0])) + (mat[0][2] * (mat[1][0]*mat[2][1] - mat[1][1]*mat[2][0]));
}
int main()
{
int choice;
matrix a;
cout<<"Input for first matrix:\n";
a.input();
cout<<"\nFirst matrix is: \n";
a.display();
do
{
cout<<"\n1. Add \n2. Subtract \n3. Transpose \n4. Determinant \n5. Negation\n";
cout<<"\nEnter your choice: ";
cin>>choice;
switch (choice)
{
case 1:{
matrix b;
cout<<"\nInput for second matrix:\n";
b.input();
cout<<"\nSecond matrix is: \n";
b.display();
matrix result(a + b);
cout<<"\nThe sum matrix is: \n";
result.display();
break;
}
case 2:{
matrix b;
cout<<"\nInput for second matrix:\n";
b.input();
cout<<"\nSecond matrix is: \n";
b.display();
matrix result(a - b);
cout<<"\nThe difference matrix is: \n";
result.display();
break;
}
case 3:{
matrix result(!a);
cout<<"\nThe transpose matrix is: \n";
result.display();
break;
}
case 4: {
int det = ~a;
cout<<"Determinant of the matrix is :"<<det;
break;
}
case 5: {
matrix result(-a);
cout<<"Negation of the matrix is :\n";
result.display();
break;
}
}
cout<<"\nDo you want to continue? ";
cin>>choice;
}while(choice);
} | true |
13ed295b75d944f6c5b707e98b121a572c800106 | C++ | zzhhch/pat | /PAT-B/1028 人口普查(20).cpp | UTF-8 | 1,048 | 3.09375 | 3 | [] | no_license | #include<stdio.h>
struct People
{
char name[6];
int yy;
int mm;
int dd;
}pp[100010],max,min;
bool Islegal(People a)
{
if(a.yy<2014&&a.yy>1814)
return true;
else if((a.yy==2014&&a.mm<9)||(a.yy==1814&&a.mm>9))
return true;
else if((a.yy==2014&&a.mm==9&&a.dd<=6)||(a.yy==1814&&a.mm==9&&a.dd>=6))
return true;
else
return false;
}
bool Ismore(People a,People b)
{
if(a.yy<b.yy)
return true;
else if((a.yy==b.yy)&&(a.mm<b.mm))
return true;
else if((a.yy==b.yy)&&(a.mm==b.mm)&&(a.dd<b.dd))
return true;
else
return false;
}
int main()
{
int n,minn,maxn,count=0;
scanf("%d",&n);
max.yy=1814;
min.yy=2014;
max.mm=min.mm=9;
max.dd=min.dd=6;
for(int i=0;i<n;i++)
{
scanf("%s %d/%d/%d",pp[i].name,&pp[i].yy,&pp[i].mm,&pp[i].dd);
if(Islegal(pp[i]))
{
count++;
if(Ismore(pp[i],max))
{
maxn=i;
max=pp[i];
}
if(Ismore(min,pp[i]))
{
minn=i;
min=pp[i];
}
}
}
if(count==0)
printf("0\n");
else
printf("%d %s %s\n",count,pp[maxn].name,pp[minn].name);
return 0;
}
| true |
deb9625309fa56b890235aadde0356852edcf0ab | C++ | AnabaenaQing/Source-Code_ShaderX_GPU-Pro_GPU-Zen | /GPU Zen2/03_Shadows/02_Parallax-Corrected Cached Shadow Maps/Demo/Src/Core/Math/x86/AABB.h | UTF-8 | 1,258 | 2.71875 | 3 | [
"MIT"
] | permissive | #ifndef __AABB2D_H
#define __AABB2D_H
class AABB2D : public Vec4
{
public:
finline AABB2D() { }
finline AABB2D(const Vec2& Min, const Vec2& Max) { r = _mm_shuffle_ps(Min.r, Max.r, _MM_SHUFFLE(1,0,1,0)); }
finline AABB2D(const AABB2D& a) { r = a.r; }
finline AABB2D(const Vec4& a) { r = a.r; }
finline const AABB2D& operator = (const AABB2D& a) { r = a.r; return *this; }
finline const Vec2 GetMin() const { return r; }
finline const Vec2 GetMax() const { return SWZ_ZWXY(r); }
finline const Vec2 Size() const { return _mm_sub_ps(SWZ_ZWXY(r), r); }
finline const Vec2 Center() const { return _mm_mul_ps(_mm_set1_ps(0.5f), _mm_add_ps(SWZ_ZWXY(r), r)); }
static finline bool IsIntersecting(const AABB2D& a, const AABB2D& b)
{
__m128 t = SWZ_ZWXY(b.r);
return ((_mm_movemask_ps(_mm_cmpge_ps(t, a.r))&3) | (_mm_movemask_ps(_mm_cmple_ps(t, a.r))&12))==15;
}
static finline float GetOverlapArea(const AABB2D& a, const AABB2D& b)
{
__m128 t0 = _mm_min_ps(a.r, b.r);
__m128 t1 = _mm_max_ps(_mm_setzero_ps(), _mm_sub_ps(SWZ_ZWXY(t0), _mm_max_ps(a.r, b.r)));
return _mm_cvtss_f32(_mm_mul_ss(t1, SWZ_YYYY(t1)));
}
};
#endif //#ifndef __AABB2D_H
| true |
62dd7e39b174f70505c25083964a122d1da02074 | C++ | glory9/miscellaneous | /getting-average-c++.cpp | UTF-8 | 692 | 3.75 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main(){
str aNumber, c1, c2, c3, c4, c5;
int g1, g2, g3, g4, g5, average;
cout << "Input A#" << endl;
cin >> aNumber >> endl;
cout << "Enter 5 of your courses separated by space" << endl;
cin >> c1 >> c2 >> c3 >> c4 >> c5 >> endl;
cout << "Enter the grades of each course in the same order separated by space"
<< endl;
cin >> g1 >> g2 >> g3 >> g4 >> g5 >> endl;
average = (g1 + g2 + g3 + g4 + g5) / 5;
cout << "A# " << aNumber << endl;
cout << "Your grades are " << c1, g1 << c2, g2 << c3, g3 << c4, g4 << c5, g5
<< endl;
cout << "Your average grade is " << average << endl;
return 0
}
| true |
932bdd1049a8ac70d3cad3c9342c09af34e79ce7 | C++ | rabeehk/Algorithm-Lab | /week8/maximizeit.cpp | UTF-8 | 2,055 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cassert>
#include<CGAL/basic.h>
#include<CGAL/QP_models.h>
#include<CGAL/QP_functions.h>
using namespace std;
// choose exact integral type
#ifdef CGAL_USE_GMP
#include<CGAL/Gmpzf.h>
typedef CGAL::Gmpzf ET;
#else
#include <CGAL/MP_Float.h>
typedef CGAL::MP_Float ET;
#endif
// program and solution types
typedef CGAL::Quadratic_program<int> Program;/////
typedef CGAL::Quadratic_program_solution<ET> Solution;
double ceil_to_double(const CGAL::Quotient<CGAL::Gmpzf> & x){
double a = ceil(CGAL::to_double(x));
while(a<x) a+=1;
while(a-1 >= x) a-=1;
return a;
}
double floor_to_double(const CGAL::Quotient<CGAL::Gmpzf> & x){
double a = floor(CGAL::to_double(x));
while(a>x) a-=1;
while(a+1 <= x) a+=1;
return a;
}
int main(){
int p; cin>>p;
while(p !=0){
int a,b; cin>>a>>b;
if(p==1){
Program lp(CGAL::SMALLER, true, 0, false, 0);
lp.set_a(0, 0, 1);
lp.set_a(1, 0, 1);
lp.set_b(0, 4);
lp.set_a(0, 1 ,4);
lp.set_a(1, 1, 2);
lp.set_b(1, a*b);
lp.set_a(0, 2, -1);
lp.set_a(1, 2, 1);
lp.set_b(2, 1);
lp.set_d(0, 0,2*a);
lp.set_c(1, -b);
Solution s = CGAL::solve_quadratic_program(lp, ET());
if(s.is_optimal() && s.objective_value() <= 0)////
cout << (long)floor_to_double(-s.objective_value()) << endl;
else if(s.is_unbounded())
cout << "unbounded\n";
else
cout << "no\n";
}
else{
Program lp(CGAL::LARGER, false, 0, true, 0);
lp.set_a(0, 0, 1);
lp.set_a(1, 0, 1);
lp.set_b(0, -4);
lp.set_a(0, 1 ,4);
lp.set_a(1, 1 ,2);
lp.set_a(2, 1 ,1);
lp.set_b(1, -a*b);
lp.set_a(0, 2 ,-1);
lp.set_a(1, 2 ,1);
lp.set_b(2, -1);
lp.set_d(0,0, 2*a);
lp.set_c(1, b);
lp.set_d(2,2, 2);//// multiply by 2
lp.set_l(2, true, 0);
lp.set_u(2, false, 0);///
Solution s = CGAL::solve_quadratic_program(lp, ET());
if(s.is_optimal())
cout <<(long) ceil_to_double(s.objective_value()) << endl;
else if(s.is_unbounded())
cout <<"unbounded\n";
else
cout <<"no\n";
}
cin >> p;
}
return 0;
}
| true |
f262f0da5cc586f5f8385cec198ac65b5de10506 | C++ | CedricZhang9516/g2esoft | /g2esoft-master/TreeProc/include/Factory.h | UTF-8 | 2,044 | 3.265625 | 3 | [] | no_license | // Factory.h
// Factory & FactoryBase class
// Please note that the
#ifndef TREEPROC_FACTORY_H
#define TREEPROC_FACTORY_H
#include <map>
#include <string>
#include <string.h>
namespace TreeProc{
template<class T> class ObjectFactory;
template <class T> class FactoryBase{
protected:
FactoryBase(){}
public:
virtual T * get(const char *name) = 0; // pure virtual OK?
virtual ~FactoryBase(){}
};
template<class base, class T> class Factory : public FactoryBase<base>{
public:
Factory(const char *name){TreeProc::ObjectFactory<base>::instance()->registerFactory(name,this);_procName = name;}
~Factory(){}
virtual base * get(const char *name) {return static_cast<base *>(new T(_procName.c_str(), name));}
private:
std::string _procName;
};
template<class T> class ObjectFactory{
typedef typename std::map<std::string, TreeProc::FactoryBase<T> *> FactoryMapType;
private:
ObjectFactory(){}
public:
~ObjectFactory(){}
static ObjectFactory<T> * instance(){if(_instance)return _instance; else {_instance = new ObjectFactory<T>; return _instance;}}
void registerFactory(const char *name, TreeProc::FactoryBase<T> *factory){
if(_factoryMap.find(name) != _factoryMap.end()){
throw("ObjectFactgory::registerFactory(): factory already registered.");
}
_factoryMap[name] = factory;
}
T * makeObject(const char *procName, const char *instanceName){
//FactoryMapType::iterator it;
typename FactoryMapType::iterator it;
if((it = _factoryMap.find(procName)) == _factoryMap.end()){
throw("ObjectFactory::makeObject(): object cannot found in the factory.");
}
if(strlen(instanceName) == 0)
instanceName = procName;
return it->second->get(instanceName);
}
private:
static ObjectFactory<T> * _instance;
FactoryMapType _factoryMap;
};
template<class T> ObjectFactory<T> * ObjectFactory<T>::_instance = 0;
}
#endif
| true |
eb26074c0a9e60d39d8c444ba9479dfd02764360 | C++ | marcoafo/OpenXLSX | /Examples/Demo1.cpp | UTF-8 | 6,681 | 3.65625 | 4 | [
"BSD-3-Clause"
] | permissive | #include <OpenXLSX.hpp>
#include <iostream>
#include <cmath>
using namespace std;
using namespace OpenXLSX;
int main()
{
cout << "********************************************************************************\n";
cout << "DEMO PROGRAM #01: Basic Usage\n";
cout << "********************************************************************************\n";
// This example program illustrates basic usage of OpenXLSX, for example creation of a new workbook, and read/write
// of cell values.
// First, create a new document and access the sheet named 'Sheet1'.
// New documents contain a single worksheet named 'Sheet1'
XLDocument doc;
doc.create("./Demo01.xlsx");
auto wks = doc.workbook().worksheet("Sheet1");
// The individual cells can be accessed by using the .cell() method on the worksheet object.
// The .cell() method can take the cell address as a string, or alternatively take a XLCellReference
// object. By using an XLCellReference object, the cells can be accessed by row/column coordinates.
// The .cell() method returns an XLCell object.
// The .value() method of an XLCell object can be used for both getting and setting the cell value.
// Setting the value of a cell can be done by using the assignment operator on the .value() method
// as shown below. Alternatively, a .set() can be used. The cell values can be floating point numbers,
// integers, strings, and booleans. It can also accept XLDateTime objects, but this requires special
// handling (see later).
wks.cell("A1").value() = 3.14159265358979323846;
wks.cell("B1").value() = 42;
wks.cell("C1").value() = " Hello OpenXLSX! ";
wks.cell("D1").value() = true;
wks.cell("E1").value() = std::sqrt(-2); // Result is NAN, resulting in an error value in the Excel spreadsheet.
// As mentioned, the .value() method can also be used for getting tha value of a cell.
// The .value() method returns a proxy object that cannot be copied or assigned, but
// it can be implicitly converted to an XLCellValue object, as shown below.
// Unfortunately, it is not possible to use the 'auto' keyword, so the XLCellValue
// type has to be explicitly stated.
XLCellValue A1 = wks.cell("A1").value();
XLCellValue B1 = wks.cell("B1").value();
XLCellValue C1 = wks.cell("C1").value();
XLCellValue D1 = wks.cell("D1").value();
XLCellValue E1 = wks.cell("E1").value();
// The cell value can be implicitly converted to a basic c++ type. However, if the type does not
// match the type contained in the XLCellValue object (if, for example, floating point value is
// assigned to a std::string), then an XLValueTypeError exception will be thrown.
// To check which type is contained, use the .type() method, which will return a XLValueType enum
// representing the type. As a convenience, the .typeAsString() method returns the type as a string,
// which can be useful when printing to console.
double vA1 = wks.cell("A1").value();
int vB1 = wks.cell("B1").value();
std::string vC1 = wks.cell("C1").value();
bool vD1 = wks.cell("D1").value();
double vE1 = wks.cell("E1").value();
cout << "Cell A1: (" << A1.typeAsString() << ") " << vA1 << endl;
cout << "Cell B1: (" << B1.typeAsString() << ") " << vB1 << endl;
cout << "Cell C1: (" << C1.typeAsString() << ") " << vC1 << endl;
cout << "Cell D1: (" << D1.typeAsString() << ") " << vD1 << endl;
cout << "Cell E1: (" << E1.typeAsString() << ") " << vE1 << endl << endl;
// Instead of using implicit (or explicit) conversion, the underlying value can also be retrieved
// using the .get() method. This is a templated member function, which takes the desired type
// as a template argument.
cout << "Cell A1: (" << A1.typeAsString() << ") " << A1.get<double>() << endl;
cout << "Cell B1: (" << B1.typeAsString() << ") " << B1.get<int64_t>() << endl;
cout << "Cell C1: (" << C1.typeAsString() << ") " << C1.get<std::string>() << endl;
cout << "Cell D1: (" << D1.typeAsString() << ") " << D1.get<bool>() << endl;
cout << "Cell E1: (" << E1.typeAsString() << ") " << E1.get<double>() << endl << endl;
// XLCellValue objects can also be copied and assigned to other cells. This following line
// will copy and assign the value of cell C1 to cell E1. Note tha only the value is copied;
// other cell properties of the target cell remain unchanged.
wks.cell("F1").value() = wks.cell(XLCellReference("C1")).value();
XLCellValue F1 = wks.cell("F1").value();
cout << "Cell F1: (" << F1.typeAsString() << ") " << F1.get<std::string_view>() << endl << endl;
// Date/time values is a special case. In Excel, date/time values are essentially just a
// 64-bit floating point value, that is rendered as a date/time string using special
// formatting. When retrieving the cell value, it is just a floating point value,
// and there is no way to identify it as a date/time value.
// If, however, you know it to be a date time value, or if you want to assign a date/time
// value to a cell, you can use the XLDateTime class, which falilitates conversion between
// Excel date/time serial numbers, and the std::tm struct, that is used to store
// date/time data. See https://en.cppreference.com/w/cpp/chrono/c/tm for more information.
// An XLDateTime object can be created from a std::tm object:
std::tm tm;
tm.tm_year = 121;
tm.tm_mon = 8;
tm.tm_mday = 1;
tm.tm_hour = 12;
tm.tm_min = 0;
tm.tm_sec = 0;
XLDateTime dt (tm);
// XLDateTime dt (43791.583333333299);
// The std::tm object can be assigned to a cell value in the same way as shown previously.
wks.cell("G1").value() = dt;
// And as seen previously, an XLCellValue object can be retrieved. However, the object
// will just contain a floating point value; there is no way to identify it as a date/time value.
XLCellValue G1 = wks.cell("G1").value();
cout << "Cell G1: (" << G1.typeAsString() << ") " << G1.get<double>() << endl;
// If it is known to be a date/time value, the cell value can be converted to an XLDateTime object.
auto result = G1.get<XLDateTime>();
// The Excel date/time serial number can be retrieved using the .serial() method.
cout << "Cell G1: (" << G1.typeAsString() << ") " << result.serial() << endl;
// Using the .tm() method, the corresponding std::tm object can be retrieved.
auto tmo = result.tm();
cout << "Cell G1: (" << G1.typeAsString() << ") " << std::asctime(&tmo);
doc.save();
doc.close();
return 0;
} | true |
bae47272915721ddbe6dace44f48304039c9539e | C++ | ankity6413/CP-Cipher | /sort012.cpp | UTF-8 | 632 | 3.609375 | 4 | [] | no_license | #include<iostream>
using namespace std;
void sort(int *a,int n);
int main(){
int n;
cout<<"Enter No of elements";
cin>>n;
int a[n];
cout<<"Enter elements";
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,n);
for(int i=0;i<n;i++)
cout<<a[i];
return 0;
}
void sort(int *a,int n){
int zero=0,one=0;
for (int i=0;i<n;i++){
if(a[i]==0)
zero++;
if(a[i]==1)
one++;
}
for(int i=0;i<zero;i++){
a[i]=0;
}
for(int i=zero;i<one;i++)
a[i]=1;
for(int i=one;i<n;i++)
a[i]=2;
}
| true |
5e259979ad3abf1e0e6810acc14cdf991abbba50 | C++ | PriyanshuSingh/CompProg | /spoj/prosort2.cpp | UTF-8 | 1,287 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
using namespace std;
const int MAX = 100001;
// boolean isPrime[100001]={true};
// int sp[100001];
// void initSieve(){
// for(int i=2; i<50001; i++){
// if(isPrime[i]){
// for(int j=2*i; j<100001; j+=i){
// isPrime[j] = false;
// }
// }
// }
// }
bool v[MAX]={false};
int len, sp[MAX];
void Sieve(){
for (int i = 2; i < MAX; i += 2) sp[i] = 2;//even numbers have smallest prime factor 2
for (long long int i = 3; i < MAX; i += 2){
if (!v[i]){
sp[i] = i;
for (long long int j = i; (j*i) < MAX; j += 2){
if (!v[j*i]) v[j*i] = true, sp[j*i] = i;
}
}
}
}
vector<int> fac(int b){
vector<int> f;
while(sp[b] != b){
f.push_back(sp[b]);
b = b/sp[b];
}
f.push_back(sp[b]);
return f;
}
long long int foo(int n, int prime){
int sum=0;
while(n/prime != 0){
sum+= n/prime;
n=n/prime;
}
return sum;
}
int main(){
vector<int> factor;
int T;
int n,b;
long long int min,temp;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
scanf("%d",&b);
factor = fac(b);
min = foo(n,factor[0]);
for(int i=1; i < factor.size(); i++){
temp = foo(n,factor[i]);
if(min > temp) min = temp;
}
printf("%lld\n",temp);
}
}
| true |
5601e708f40d20d1948b6cd249dc4b492b96a82a | C++ | wenrurumon/GoSprada | /src/tictactoe::rawgame.cpp | UTF-8 | 2,381 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <math.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace std;
using namespace arma;
//[[Rcpp::export]]
mat gamelog(){
mat x = randu(3,3);
int xsize = x.size();
vector<int> rlt(xsize);
for(int i = 0; i < xsize; i++){
int ge_count = 0;
for(int j = 0; j < xsize; j++){
if(x[j]>x[i]){
ge_count += 1;
}
}
rlt[i] = ge_count;
}
mat x2 = zeros(2,5);
for(int i = 0; i < xsize; i++){
x2[i] = rlt[i]+1;
}
return x2;
}
//[[Rcpp::export]]
mat gamerlt(mat xlog){
mat x = zeros(3,3);
int xsize = x.size();
int player = 1;
for(int i = 0; i<xsize; i++){
if(xlog[i]==0){
break;
}
x[xlog[i]-1] = player;
player = player * -1;
}
return x;
}
//macro
vec csum(const mat & X){
int nCols = X.n_cols;
vec out(nCols);
for(int i = 0; i < nCols; i++){
out(i) = sum(X.col(i));
}
return(out);
}
vec rsum(const mat & X){
int nRows = X.n_rows;
vec out(nRows);
for(int i = 0; i < nRows; i++){
out(i) = sum(X.row(i));
}
return(out);
}
//[[Rcpp::export]]
vector<int> gamescore(mat x){
vector<int> score(8);
vec cscore = csum(x);
vec rscore = rsum(x);
int diag1 = x[0] + x[4] + x[8];
int diag2 = x[2] + x[4] + x[6];
for(int i=0; i < 3; i++){
score[i] = cscore[i];
score[i+3] = rscore[i];
}
score[7] = diag1; score[8] = diag2;
return score;
}
//[[Rcpp::export]]
int callwin(mat x){
mat rlt = gamerlt(x);
vector<int> score = gamescore(rlt);
int win = 0;
for(int i = 0; i < 8; i++){
if(abs(score[i])==3){
win = score[i]/3;
break;
}
}
return win;
}
//[[Rcpp::export]]
mat game(){
mat xlog = gamelog();
mat xlog2 = zeros(2,5);
for(int i = 0; i < 9; i++ ){
xlog2[i] = xlog[i];
cout << xlog2 << endl;
int win = callwin(xlog2);
if(win!=0){
cout << win << " win" << endl;
break;
}
}
return xlog2;
}
//[[Rcpp::export]]
SEXP game2(){
mat xlog = gamelog();
mat xlog2 = zeros(2,5);
for(int i = 0; i < 9; i++ ){
xlog2[i] = xlog[i];
int win = callwin(xlog2);
if(win!=0){
break;
}
}
int win = callwin(xlog2);
return List::create(Named("winner")=win,
Named("gamelog")=xlog2,
Named("gamerlt")=gamerlt(xlog2));
}
| true |
24557a7c03a45bd444901fa6d9b25148417c3eb9 | C++ | feqiu1129/css487finalproject | /Project4/src/CHoNI.cpp | UTF-8 | 7,281 | 2.859375 | 3 | [] | no_license |
/**********************************************************************************************\
Implementation of SIFT is based on the code from http://blogs.oregonstate.edu/hess/code/SIFT/
Below is the original copyright.
// Copyright (c) 2006-2010, Rob Hess <hess@eecs.oregonstate.edu>
// All rights reserved.
\**********************************************************************************************/
#include "CHoNI.h"
namespace cv
{
//------------------------------------descriptorSize()---------------------------------
// ! returns the descriptor size in floats
//Precondition: None
//Postcondition: the descriptor size is returned in floats
//-------------------------------------------------------------------------------------
int CHoNI::descriptorSize() const {
return 3 * SIFT_DESCR_WIDTH * SIFT_DESCR_WIDTH * SIFT_DESCR_HIST_BINS;
}
void CHoNI::normalizeHistogram(float *dst, int d, int n) const {
float nrm1sqr = 0, nrm2sqr = 0, nrm3sqr = 0;
int len = d*d*n;
for (int k = 0; k < len; k++) {
nrm1sqr += dst[k] * dst[k];
nrm2sqr += dst[k + len] * dst[k + len];
nrm3sqr += dst[k + 2 * len] * dst[k + 2 * len];
}
float thr1 = std::sqrt(nrm1sqr)*SIFT_DESCR_MAG_THR;
float thr2 = std::sqrt(nrm2sqr)*SIFT_DESCR_MAG_THR;
float thr3 = std::sqrt(nrm3sqr)*SIFT_DESCR_MAG_THR;
nrm1sqr = nrm2sqr = nrm3sqr = 0;
for (int k = 0; k < len; k++)
{
float val = std::min(dst[k], thr1);
dst[k] = val;
nrm1sqr += val*val;
val = std::min(dst[k + len], thr2);
dst[k + len] = val;
nrm2sqr += val*val;
val = std::min(dst[k + 2 * len], thr3);
dst[k + 2 * len] = val;
nrm3sqr += val*val;
}
// Factor of three added below to make vector lengths comparable with SIFT
nrm1sqr = SIFT_INT_DESCR_FCTR / std::max(std::sqrt(3 * nrm1sqr), FLT_EPSILON);
nrm2sqr = SIFT_INT_DESCR_FCTR / std::max(std::sqrt(3 * nrm2sqr), FLT_EPSILON);
nrm3sqr = SIFT_INT_DESCR_FCTR / std::max(std::sqrt(3 * nrm3sqr), FLT_EPSILON);
for (int k = 0; k < len; k++)
{
dst[k] = (dst[k] * nrm1sqr);
dst[k + len] = (dst[k + len] * nrm2sqr);
dst[k + 2 * len] = (dst[k + 2 * len] * nrm3sqr);
}
}
//-------------------------------------------------------------------------------------
//img: color image
//ptf: keypoint
//ori: angle(degree) of the keypoint relative to the coordinates, clockwise
//scl: radius of meaningful neighborhood around the keypoint
//d: newsift descr_width, 4 in this case
//n: SIFT_descr_hist_bins, 8 in this case
//dst: descriptor array to pass in
//changes: 1. img now is a color image
void CHoNI::calcSIFTDescriptor(const Mat& img, Point2f ptf, float ori, float scl, int d, int n, float* dst) const {
Point pt(cvRound(ptf.x), cvRound(ptf.y));
float cos_t = cosf(ori*(float)(CV_PI / 180));
float sin_t = sinf(ori*(float)(CV_PI / 180));
float bins_per_intensity = n / 255.f;
float hist_width = VanillaSIFT::SIFT_DESCR_SCL_FCTR * scl;
int radius = cvRound(hist_width * 1.4142135623730951f * (d + 1) * 0.5f);
// Clip the radius to the diagonal of the image to avoid autobuffer too large exception
radius = std::min(radius, (int)sqrt((double)img.cols*img.cols + img.rows*img.rows));
cos_t /= hist_width;
sin_t /= hist_width;
int i;
int j;
int k;
int len = (radius * 2 + 1)*(radius * 2 + 1);
int histlen = (d + 2)*(d + 2)*(n + 2);
int rows = img.rows, cols = img.cols;
AutoBuffer<float> buf(len * 7 + 3 * histlen);
float *RBin = buf, *CBin = RBin + len, *hist1 = CBin + len, *hist2 = hist1 + histlen, *hist3 = hist2 + histlen, *red = hist3 + histlen, *green = red + len, *blue = green + len;
calculateIntensity(0, bins_per_intensity, d, n, hist1, radius, cos_t, sin_t, pt, rows, cols, CBin, RBin, img, histlen, blue);
calculateIntensity(1, bins_per_intensity, d, n, hist2, radius, cos_t, sin_t, pt, rows, cols, CBin, RBin, img, histlen, green);
calculateIntensity(2, bins_per_intensity, d, n, hist3, radius, cos_t, sin_t, pt, rows, cols, CBin, RBin, img, histlen, red);
// finalize histogram, since the orientation histograms are circular
for (i = 0; i < d; i++)
for (j = 0; j < d; j++)
{
int idx = ((i + 1)*(d + 2) + (j + 1))*(n + 2);
hist1[idx] += hist1[idx + n];
hist1[idx + 1] += hist1[idx + n + 1];
hist2[idx] += hist2[idx + n];
hist2[idx + 1] += hist2[idx + n + 1];
hist3[idx] += hist3[idx + n];
hist3[idx + 1] += hist3[idx + n + 1];
for (k = 0; k < n; k++) {
dst[(i*d + j)*n + k] = hist1[idx + k];
dst[(i*d + j)*n + k + d * d * n] = hist2[idx + k];
dst[(i*d + j)*n + k + d * d * n * 2] = hist3[idx + k];
}
}
normalizeHistogram(dst, d, n);
}
void CHoNI::calculateIntensity(int band, float bins_per_intensity, int d, int n, float *hist, int radius, float cos_t, float sin_t, Point pt, int rows, int cols, float *CBin, float *RBin, const Mat& img, int histlen, float *intensity) const
{
int i, j, k;
for (i = 0; i < histlen; i++)
{
hist[i] = 0;
}
float ibar = 0, ibar2 = 0;
for (i = -radius, k = 0; i <= radius; i++)
for (j = -radius; j <= radius; j++)
{
// Calculate sample's histogram array coords rotated relative to ori.
// Subtract 0.5 so samples that fall e.g. in the center of row 1 (i.e.
// r_rot = 1.5) have full weight placed in row 1 after interpolation.
float c_rot = j * cos_t - i * sin_t;
float r_rot = j * sin_t + i * cos_t;
float rbin = r_rot + d / 2 - 0.5f;
float cbin = c_rot + d / 2 - 0.5f;
int r = pt.y + i, c = pt.x + j;
if (rbin > -1 && rbin < d && cbin > -1 && cbin < d &&
r > 0 && r < rows - 1 && c > 0 && c < cols - 1)
{
RBin[k] = rbin; CBin[k] = cbin;
// setting the intensity value of each pixel
intensity[k] = img.at<Vec3f>(r, c)[band];
ibar += intensity[k];
ibar2 += intensity[k] * intensity[k];
k++;
}
}
int len = k;
ibar = ibar / (float)len;
ibar2 = ibar2 / (float)len;
float isig = sqrt(ibar2 - ibar*ibar);
float bias = 127.5f - ibar;
float gain = 64.f / isig;
for (k = 0; k < len; k++)
{
intensity[k] = (intensity[k] - ibar)*gain + ibar + bias;
float rbin = RBin[k], cbin = CBin[k];
float ibin = (intensity[k]) * bins_per_intensity;
int r0 = cvFloor(rbin);
int c0 = cvFloor(cbin);
int i0 = cvFloor(ibin);
rbin -= r0;
cbin -= c0;
ibin -= i0;
// histogram update using tri-linear interpolation
float v_r1 = rbin, v_r0 = 1 - v_r1;
float v_rc11 = v_r1*cbin, v_rc10 = v_r1 - v_rc11;
float v_rc01 = v_r0*cbin, v_rc00 = v_r0 - v_rc01;
float v_rco111 = v_rc11*ibin, v_rco110 = v_rc11 - v_rco111;
float v_rco101 = v_rc10*ibin, v_rco100 = v_rc10 - v_rco101;
float v_rco011 = v_rc01*ibin, v_rco010 = v_rc01 - v_rco011;
float v_rco001 = v_rc00*ibin, v_rco000 = v_rc00 - v_rco001;
int idx = ((r0 + 1)*(d + 2) + c0 + 1)*(n + 2) + i0;
hist[idx] += v_rco000;
hist[idx + 1] += v_rco001;
hist[idx + (n + 2)] += v_rco010;
hist[idx + (n + 3)] += v_rco011;
hist[idx + (d + 2)*(n + 2)] += v_rco100;
hist[idx + (d + 2)*(n + 2) + 1] += v_rco101;
hist[idx + (d + 3)*(n + 2)] += v_rco110;
hist[idx + (d + 3)*(n + 2) + 1] += v_rco111;
}
}
//////////////////////////////////////////////////////////////////////////////////////////
CHoNI::CHoNI()
{
}
}
| true |
6df0214da35971c62a60f5b3858fb9ce478338c4 | C++ | Winnerhust/DesignPattern | /master/flyweight/flyweight.cpp | UTF-8 | 668 | 2.734375 | 3 | [] | no_license | #ifndef __FLYWEIGHT_FLYWEIGHT_CPP__
#define __FLYWEIGHT_FLYWEIGHT_CPP__
#include "flyweight.h"
#include <iostream>
using namespace std;
Flyweight::Flyweight(const string &s)
:m_state(s)
{
}
Flyweight::~Flyweight()
{
cout<<"Flyweight["<<getstate()<<"]"<<" is deleted"<<endl;
}
string Flyweight::getstate()
{
return m_state;
}
void Flyweight::option(const string &s)
{
}
ConFlyweight::ConFlyweight(const string &s)
:Flyweight(s)
{
}
ConFlyweight::~ConFlyweight()
{
cout<<"ConFlyweight["<<getstate()<<"]"<<" is deleted"<<endl;
}
void ConFlyweight::option(const string &s)
{
cout<<"ConFlyweight::"<<getstate()<<" ["<<s<<"]"<<endl;
}
#endif
| true |
ee8287cd70abd38aa009841bda69ad01af818b88 | C++ | jysso3070/CordingTest_Practice | /c++/data_struct/data_struct/stack(C style).cpp | UTF-8 | 835 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
constexpr int maxStackSize = 100;
int myStack[maxStackSize];
int stackTop = -1;
bool stackFull() {
if (stackTop >= maxStackSize - 1) {
return true;
}
else {
return false;
}
}
bool stackEmpty() {
if (stackTop < 0) {
return true;
}
else {
return false;
}
}
void pushStack(int val) {
if (stackFull() == true) {
printf("myStack is full");
}
else {
myStack[++stackTop] = val;
}
}
int popStack() {
if (stackEmpty() == true) {
printf("myStack is empty");
}
else {
return myStack[stackTop--];
}
}
int main() {
pushStack(10);
pushStack(9);
pushStack(5);
pushStack(1);
pushStack(11);
printf("%d \n", popStack());
printf("%d \n", popStack());
printf("%d \n", popStack());
printf("%d \n", popStack());
printf("%d \n", popStack());
} | true |
d5aca93d82c6e344028247a151e87f0de9daf44f | C++ | indro8307/hackerrank | /C++/attributeParser.cpp | UTF-8 | 5,225 | 3.078125 | 3 | [] | no_license | /*
https://www.hackerrank.com/challenges/attribute-parser/problem
*/
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <sstream>
#include <map>
#include <stack>
using namespace std;
class node
{
public:
string name;
//map<string,node> child;
node *child[100];
int index;
};
//map<string,node*> level1;
vector<node*> level1;
bool checkHierarchy(char* tag, node **tmp)
{
bool ret = false;
vector<node*>::iterator it;
if(*tmp==NULL){
for(it = level1.begin();it != level1.end();it++)
{
string s(tag);
node *a = *it;
if(a->name == s){
ret = true;
*tmp = a;
break;
}
}
}
else{
for(int i=0;i<(*tmp)->index;i++){
string s(tag);
if(s == (*tmp)->child[i]->name){
*tmp = (*tmp)->child[i];
ret = true;
break;
}
}
}
return ret;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N,Q;
string in_str;
std::getline(std::cin, in_str);
std::istringstream sin(in_str);
sin>>N>>Q;
// Readng the HRML file
int i=0;
vector<string> hrml_code(N);
while(i<N)
{
std::getline(std::cin, hrml_code[i]);
i++;
}
// Reading the queries
i = 0;
vector<string> queries(Q);
while(i<Q)
{
std::getline(std::cin, queries[i]);
i++;
}
//create a hierarchy of nodes
i=0;
stack<node*> exp;
while(i<N)
{
std::istringstream z(hrml_code[i].c_str());
string tag;
z>>tag;
/* strip '<', '>' and '/' characters*/
tag.erase(std::remove(tag.begin(),tag.end(),'<'),tag.end());
tag.erase(std::remove(tag.begin(),tag.end(),'>'),tag.end());
if(strstr(tag.c_str(),"/")){
// this is a closing tag
tag.erase(std::remove(tag.begin(),tag.end(),'/'),tag.end());
if(tag == exp.top()->name){
node *tmp = exp.top();
exp.pop();
if(exp.empty()){
level1.push_back(tmp);
}
}
else{
cout<<"ERROR: should not have reached here"<<endl;
}
}
else{
//node a;
// if exp is empty, then tag is level1 element
if(!exp.empty()){
node *tmp = exp.top();
node *child1 = new node();
child1->name = tag;
child1->index = 0;
tmp->child[tmp->index] = child1;
tmp->index++;
exp.push(child1);
}
else{
node *a = new node();
a->name = tag;
a->index = 0;
exp.push(a);
}
}
i++;
}
vector<node*>::iterator it;
// Parse each query
i = 0;
int j = 0;
char temp[200] = {0};
while(i<Q)
{
strcpy(temp,queries[i].c_str());
char *tok = strtok(temp,".");
j = 0;
node *tmp1 = NULL;
// the query is in the form of tag1.tag2. ...
// Have to parse the query here
while(tok != NULL){
if(strstr(tok,"~")){
char *tok_val = strtok(tok,"~");
if(!checkHierarchy(tok_val,&tmp1)){
cout<<"Not Found!"<<endl;
break;
}
std::ostringstream sout;
sout<<"<"<<tok_val<<" ";
j=0;
while(j<N){
char *a = strstr((char*)hrml_code[j].c_str(), sout.str().c_str());
if(a != NULL){
break;
}
j++;
}
if(j==N){
cout<<"Not Found!"<<endl;
break;
}
tok_val = strtok(NULL,"~");
std::ostringstream sout1;
sout1<<" "<<tok_val<<" ";
char *b = strstr((char*)hrml_code[j].c_str(), sout1.str().c_str());
if(b == NULL){
cout<<"Not Found!"<<endl;
break;
}
else{
std::istringstream str2(b);
string a,b,c;
str2>>a>>b>>c;
char *d = strtok((char*)c.c_str(),"\"");
cout<<d<<endl;
break;
}
}
else{
if(!checkHierarchy(tok,&tmp1)){
cout<<"Not Found!"<<endl;
break;
}
tok = strtok(NULL,".");
}
}
i++;
}
return 0;
}
| true |
91c19d07da09de32f7bf088fb28999ef612cc457 | C++ | rjsu26/Project_Euler | /PE_31.cpp | UTF-8 | 755 | 3 | 3 | [] | no_license | /* * @Title: Project Euler #31: Coin sums * @Author: raj sahu * @Date: 2020-08-08 23:42:31 * @Last Modified time: 2020-08-08 23:42:31 */
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int arr[8] = {1,2,5,10,20,50,100,200};
vector<int> ans;
void find(int N){
ans.resize(N+1, 0);
ans[0]=1;
for(int i=0;i<=7;i++){
for(int j=arr[i];j<=N;j++){
ans[j] = (ans[j]+ans[j-arr[i]])%1000000007;
}
}
}
int main() {
int t,n,mx=1; cin>>t;
vector<int> inp;
while(t--){
cin>>n;
mx = max(mx, n);
inp.push_back(n);
}
find(mx);
for(int t=0;t<inp.size();t++)
cout<<ans[inp[t]]<<endl;
return 0;
}
| true |
69f1f004877e3a7f62797aefe096771769b13823 | C++ | jamesjallorina/cpp_exercises | /class_basics_exercises/exercise1/exercise1.cpp | UTF-8 | 416 | 3.453125 | 3 | [
"MIT"
] | permissive | #include <iostream>
class functional
{
private:
void private_function() { std::cout << "private function \n"; }
protected:
void protected_function() { std::cout << "protected function \n"; }
public:
void public_function() { std::cout << "public function \n"; }
};
int main( int argc , char ** argv)
{
functional p;
p.public_function();
p.private_function();
p.protected_function();
return 0;
}
| true |
35825157388fca996e5b2c43ef4e1bb1e7339e18 | C++ | LanghaoZ/rubber-duck | /src/http/session/session.cc | UTF-8 | 5,022 | 2.53125 | 3 | [] | no_license | #include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <utility>
#include <vector>
#include <iostream>
#include <memory>
#include <cstdlib>
#include "http/session/session.h"
#include "http/request/request_parser.h"
#include "http/response.h"
#include "http/request_handler/request_handler.h"
#include "http/session/session_manager.h"
#include "logging/logging.h"
#include "http/request_handler/request_handler_factory.h"
#include "http/status_code.h"
#include "http/server/server.h"
using boost::asio::ip::tcp;
namespace http {
namespace session {
session::session(boost::asio::ip::tcp::socket socket,
session_manager& manager)
: socket_(std::move(socket)),
session_manager_(manager)
{
}
void session::start()
{
do_read();
}
void session::stop()
{
socket_.close();
}
void session::do_read()
{
auto self(shared_from_this());
// asynchronously read some data from socket and store it into buffer
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&session::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
int session::handle_read(const boost::system::error_code& ec,
std::size_t bytes_transferred)
{
auto self(shared_from_this());
if (!ec)
{
char* start = buffer_.data();
char* end = buffer_.data() + bytes_transferred;
request::request_parser::result_type result;
std::tie(result, start) = request_parser_.parse(
request_, start, end);
if (result == request::request_parser::good)
{
// buffer may contain more data beyond end of request header
// read more data from socket if necessary
read_leftover(std::string(start, end - start));
logging::logging::log_info(request_to_digest(request_) + " FROM " + find_client_address() + "\n");
logging::logging::log_trace(request_to_string(request_));
std::shared_ptr<request_handler::request_handler> request_handler
= request_handler::request_handler_factory::get_instance().dispatch(request_.uri);
res_ = request_handler.get()->handle_request(request_);
server::server::update_request_history(request_.uri, res_.code);
do_write();
return 0;
}
else if (result == request::request_parser::bad)
{
logging::logging::log_info(request_to_digest(request_) + " FROM " + find_client_address() + "\n");
logging::logging::log_trace(request_to_string(request_));
// respond with 400 status
res_ = status_code_to_stock_response(status_code::bad_request);
do_write();
return 1;
}
else
{
logging::logging::log_debug("Continue reading in HTTP request");
do_read();
return 0;
}
}
else if (ec != boost::asio::error::operation_aborted)
{
logging::logging::log_warning("Closing session with " + find_client_address() + "\n");
session_manager_.stop(shared_from_this());
}
return 1;
}
void session::do_write()
{
auto self(shared_from_this());
boost::asio::async_write(socket_, response_to_buffers(res_),
[this, self](boost::system::error_code ec, std::size_t)
{
if (!ec)
{
// Initiate graceful connection closure.
boost::system::error_code ignored_ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
ignored_ec);
}
if (ec != boost::asio::error::operation_aborted)
{
session_manager_.stop(shared_from_this());
}
});
}
void session::read_leftover(const std::string& extra_data_read)
{
auto self(shared_from_this());
read_request_body(extra_data_read,
[this, self](size_t content_length_left)
{
char* data = new char[content_length_left];
size_t length = socket_.read_some(boost::asio::buffer(data, content_length_left));
std::string addtional_data = std::string(data, data + length);
delete data;
return addtional_data;
});
}
void session::read_request_body(const std::string& extra_data_read,
std::function<std::string (size_t length)> reader)
{
size_t content_length_left = get_request_content_length(request_) - extra_data_read.size();
std::string addtional_data = "";
// read rest of the request body
if (content_length_left > 0)
{
logging::logging::log_debug("Reading in additional data");
addtional_data += reader(content_length_left);
}
request_.body = extra_data_read + addtional_data;
}
std::string session::find_client_address()
{
std::string client_address;
boost::system::error_code ec;
boost::asio::ip::tcp::endpoint endpoint = socket_.remote_endpoint(ec);
if (ec)
{
logging::logging::log_error("Failed to find the client address\n");
}
else
{
client_address = endpoint.address().to_string();
}
return client_address;
}
void session::set_buffer(boost::array<char, 8192>& buffer)
{
logging::logging::log_debug("Session read buffer has been initiated");
buffer_ = buffer;
}
} // namespace session
} // namespace http | true |
ac0373391d4d1826ff8948c7cc9d0723709de44e | C++ | jiemojiemo/DesignPatterns | /Composite/Leaf.h | UTF-8 | 503 | 3.171875 | 3 | [] | no_license | #pragma once
#include "Component.h"
#include <iostream>
using namespace std;
class Leaf : public Component
{
public:
Leaf(string name) :Component(name) {}
virtual void Add(Component* com)
{
cout << "Leaf cannot add" << endl;
}
virtual void Remove(Component* com)
{
cout << "Leaf cannot remove" << endl;
}
virtual Component* GetChild(int index)
{
cout << "Leaf cannot get child" << endl;
return nullptr;
}
virtual void Display()
{
cout << '-';
cout << this->m_name << endl;
}
}; | true |
73666cd0de4af75b2d8852e16827200faa1a7427 | C++ | BCLab-UNM/CPFA-ROS | /src/rqt_rover_gui/src/MapData.cpp | UTF-8 | 11,296 | 2.75 | 3 | [
"MIT"
] | permissive | #include "MapData.h"
using namespace std;
MapData::MapData()
{
display_global_offset = false;
}
void MapData::AddToGPSRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_gps_seen_x[rover]) max_gps_seen_x[rover] = x;
if (y > max_gps_seen_y[rover]) max_gps_seen_y[rover] = y;
if (x < min_gps_seen_x[rover]) min_gps_seen_x[rover] = x;
if (y < min_gps_seen_y[rover]) min_gps_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_gps_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
gps_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::AddToEncoderRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_encoder_seen_x[rover]) max_encoder_seen_x[rover] = x;
if (y > max_encoder_seen_y[rover]) max_encoder_seen_y[rover] = y;
if (x < min_encoder_seen_x[rover]) min_encoder_seen_x[rover] = x;
if (y < min_encoder_seen_y[rover]) min_encoder_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_encoder_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
encoder_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be flipped with respect to y the map coordinate system
void MapData::AddToEKFRoverPath(string rover, float x, float y)
{
// Negate the y direction to orient the map so up is north.
y = -y;
if (x > max_ekf_seen_x[rover]) max_ekf_seen_x[rover] = x;
if (y > max_ekf_seen_y[rover]) max_ekf_seen_y[rover] = y;
if (x < min_ekf_seen_x[rover]) min_ekf_seen_x[rover] = x;
if (y < min_ekf_seen_y[rover]) min_ekf_seen_y[rover] = y;
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
global_offset_ekf_rover_path[rover].push_back(pair<float,float>(x+offset_x,y-offset_y));
ekf_rover_path[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
// Expects the input y to be consistent with the map coordinate system
int MapData::AddToWaypointPath(string rover, float x, float y)
{
update_mutex.lock();
float offset_x = rover_global_offsets[rover].first;
float offset_y = rover_global_offsets[rover].second;
int this_id = waypoint_id_counter++; // Get the next waypoint id.
global_offset_waypoint_path[rover][this_id]=make_tuple(x+offset_x,y-offset_y,false);
waypoint_path[rover][this_id]=make_tuple(x,y,false);
update_mutex.unlock();
return this_id;
}
void MapData::RemoveFromWaypointPath(std::string rover, int id)
{
update_mutex.lock();
global_offset_waypoint_path[rover].erase(id);
waypoint_path[rover].erase(id);
update_mutex.unlock();
}
void MapData::ReachedWaypoint(int waypoint_id)
{
update_mutex.lock();
// Update the reached waypoint in both the normal waypoint path AND the global
// waypoint path. We must update both to prevent incorrect color display for
// reached waypoints when switching back and forth between the global frame.
for (auto &rover : global_offset_waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
for (auto &rover : waypoint_path)
{
map<int, std::tuple<float,float,bool>>::iterator found;
if ((found = rover.second.find(waypoint_id)) != rover.second.end())
{
get<2>(found->second) = true;
}
}
update_mutex.unlock();
}
void MapData::AddTargetLocation(string rover, float x, float y)
{
//The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
target_locations[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::AddCollectionPoint(string rover, float x, float y)
{
// The QT drawing coordinate system is reversed from the robot coordinate system in the y direction
y = -y;
update_mutex.lock();
collection_points[rover].push_back(pair<float,float>(x,y));
update_mutex.unlock();
}
void MapData::SetGlobalOffset(bool display)
{
display_global_offset = display;
}
void MapData::SetGlobalOffsetForRover(string rover, float x, float y)
{
rover_global_offsets[rover] = pair<float,float>(x,y);
}
std::pair<float,float> MapData::GetGlobalOffsetForRover(string rover)
{
return rover_global_offsets[rover];
}
bool MapData::IsDisplayingGlobalOffset()
{
return display_global_offset;
}
void MapData::clear()
{
update_mutex.lock();
ekf_rover_path.clear();
encoder_rover_path.clear();
gps_rover_path.clear();
waypoint_path.clear();
global_offset_ekf_rover_path.clear();
global_offset_encoder_rover_path.clear();
global_offset_gps_rover_path.clear();
global_offset_waypoint_path.clear();
target_locations.clear();
collection_points.clear();
waypoint_path.clear();
rover_mode.clear();
update_mutex.unlock();
}
void MapData::clear(string rover)
{
update_mutex.lock();
ekf_rover_path[rover].clear();
global_offset_ekf_rover_path[rover].clear();
ekf_rover_path.erase(rover);
global_offset_ekf_rover_path.erase(rover);
encoder_rover_path[rover].clear();
global_offset_encoder_rover_path[rover].clear();
encoder_rover_path.erase(rover);
global_offset_encoder_rover_path.erase(rover);
gps_rover_path[rover].clear();
global_offset_ekf_rover_path[rover].clear();
global_offset_encoder_rover_path[rover].clear();
global_offset_gps_rover_path[rover].clear();
gps_rover_path.erase(rover);
global_offset_gps_rover_path.erase(rover);
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
waypoint_path.erase(rover);
global_offset_waypoint_path.erase(rover);
target_locations[rover].clear();
collection_points[rover].clear();
target_locations.erase(rover);
collection_points.erase(rover);
rover_mode.erase(rover);
update_mutex.unlock();
}
std::vector< std::pair<float,float> >* MapData::getEKFPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_ekf_rover_path[rover_name];
}
return &ekf_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getGPSPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_gps_rover_path[rover_name];
}
return &gps_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getEncoderPath(std::string rover_name)
{
if(display_global_offset)
{
return &global_offset_encoder_rover_path[rover_name];
}
return &encoder_rover_path[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getTargetLocations(std::string rover_name)
{
return &target_locations[rover_name];
}
std::vector< std::pair<float,float> >* MapData::getCollectionPoints(std::string rover_name)
{
return &collection_points[rover_name];
}
std::map<int, std::tuple<float,float,bool> >* MapData::getWaypointPath(std::string rover_name) {
if(display_global_offset)
{
return &global_offset_waypoint_path[rover_name];
}
return &waypoint_path[rover_name];
}
void MapData::ResetAllWaypointPaths()
{
waypoint_path.clear();
global_offset_waypoint_path.clear();
waypoint_id_counter = 0;
}
void MapData::ResetWaypointPathForSelectedRover(std::string rover)
{
waypoint_path[rover].clear();
global_offset_waypoint_path[rover].clear();
}
// These functions report the maximum and minimum map values seen. This is useful for the GUI when it is calculating the map coordinate system.
float MapData::getMaxGPSX(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_gps_seen_x[rover_name];
}
float MapData::getMaxGPSY(string rover_name)
{
if(display_global_offset)
{
return max_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_gps_seen_y[rover_name];
}
float MapData::getMinGPSX(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_gps_seen_x[rover_name];
}
float MapData::getMinGPSY(string rover_name)
{
if(display_global_offset)
{
return min_gps_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_gps_seen_y[rover_name];
}
float MapData::getMaxEKFX(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_ekf_seen_x[rover_name];
}
float MapData::getMaxEKFY(string rover_name)
{
if(display_global_offset)
{
return max_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_ekf_seen_y[rover_name];
}
float MapData::getMinEKFX(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_ekf_seen_x[rover_name];
}
float MapData::getMinEKFY(string rover_name)
{
if(display_global_offset)
{
return min_ekf_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_ekf_seen_y[rover_name];
}
float MapData::getMaxEncoderX(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return max_encoder_seen_x[rover_name];
}
float MapData::getMaxEncoderY(string rover_name)
{
if(display_global_offset)
{
return max_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return max_encoder_seen_y[rover_name];
}
float MapData::getMinEncoderX(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_x[rover_name] + rover_global_offsets[rover_name].first;
}
return min_encoder_seen_x[rover_name];
}
float MapData::getMinEncoderY(string rover_name)
{
if(display_global_offset)
{
return min_encoder_seen_y[rover_name] - rover_global_offsets[rover_name].second;
}
return min_encoder_seen_y[rover_name];
}
bool MapData::InManualMode(string rover_name)
{
return rover_mode[rover_name] == 0;
}
void MapData::SetAutonomousMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 1;
ResetWaypointPathForSelectedRover(rover_name);
update_mutex.unlock();
}
void MapData::SetManualMode(string rover_name)
{
update_mutex.lock();
rover_mode[rover_name] = 0;
update_mutex.unlock();
}
void MapData::lock()
{
update_mutex.lock();
}
void MapData::unlock()
{
update_mutex.unlock();
}
MapData::~MapData()
{
clear();
}
| true |
882d2f195457fd8729a0b34d1cd1848810dbc816 | C++ | cde8eae8/list3 | /Huffman/bitwriter.h | UTF-8 | 4,342 | 3.140625 | 3 | [] | no_license | //
// Created by nikita on 12.06.19.
//
#ifndef HUFFMAN_BITWRITER_H
#define HUFFMAN_BITWRITER_H
#include <vector>
#include <algorithm>
#include <assert.h>
#include "bit_operations.h"
struct bitarray {
bitarray() : data_(nullptr) {}
template <typename InputIterator>
bitarray(InputIterator data, size_t bit_length) : bitarray(data, bit_length / 8, bit_length % 8){}
template <typename InputIterator>
bitarray(InputIterator data, size_t length, size_t tail) {
size_t s = length + (tail != 0);
// std::cout << "s = " << s << std::endl;
// data_ = static_cast<Data*>(operator new(sizeof(Data) + s * sizeof(unsigned char)));
data_ = static_cast<Data*>(operator new(sizeof(Data)));
data_->data_ = static_cast<char*>(operator new(s * sizeof(unsigned char)));
data_->bit_size = length * 8 + tail;
std::copy_n(data, s, data_->data_);
// skip last char of input
++data;
data_->nRefs = 1;
}
bitarray(bitarray const& rhs) {
data_ = rhs.data_;
addLink();
}
bitarray& operator=(bitarray const& rhs) {
if (data_ == rhs.data_) return *this;
deleteLink();
data_ = rhs.data_;
addLink();
return *this;
}
~bitarray() {
deleteLink();
}
friend std::ostream& operator<<(std::ostream& out, bitarray const& a) {
out << "[" << a.bit_length() << "]" << bits::bits_to_string(a.data(), a.bit_length());
return out;
}
char* data() const {
if (!data_) return nullptr;
return data_->data_;
}
size_t bit_length() const {
if (!data_) return 0;
return data_->bit_size;
}
size_t length() const {
if (!data_) return 0;
return data_->bit_size / 8;
}
size_t tail() const {
if (!data_) return 0;
return data_->bit_size % 8;
}
size_t byte_length() const {
if (!data_) return 0;
return bits::byte_to_length(length(), tail());
}
private:
struct Data {
size_t bit_size;
size_t nRefs;
char* data_;
};
void addLink() {
if (!data_) return;
++data_->nRefs;
}
void deleteLink() {
if (!data_) return;
--data_->nRefs;
if(data_->nRefs == 0) {
operator delete(data_);
}
}
Data *data_;
};
struct bytearray : private bitarray {
bytearray() : bitarray() {}
template <typename T>
bytearray(T* data, size_t size) : bitarray(data, size * 8) {}
char const *array() const {
return data();
}
auto &operator[](size_t pos) {
return data()[pos];
}
auto const &operator[](size_t pos) const {
return data()[pos];
}
size_t length() const {
return byte_length();
}
};
struct bitreader {
explicit bitreader(bitarray const& bits) : data_(bits), pos_(0), tail_pos_(0) {}
unsigned char get() {
unsigned char tmp = bits::get_bit(data_.data()[pos_], 7 - tail_pos_);
bits::next_bit(pos_, tail_pos_);
return tmp;
}
bool eob() {
return pos_ > data_.length() || (pos_ == data_.length() && tail_pos_ >= data_.tail());
}
private:
bitarray const& data_;
size_t pos_;
size_t tail_pos_;
};
struct bitwriter {
bitwriter() : pos_(0), tail_pos_(0), buffer_(1) {}
/**
* write length*8 + tail bytes to internal buffer
* @param bytes bitlen(bytes) // 8
* @param length bitlen(bytes) % 8
*/
void write(unsigned char const *bytes, size_t length);
/**
* write one bit to internal buffer
* @param bit should be 1 or 0, else result is undefined
*/
void push_back(unsigned char bit);
/**
* reset state to initial, return current state
* @return internal state for all writes since previous reset or construction of the object
*/
bitarray reset();
bitarray get();
private:
/**
* get change of the length dependent on tail size
*/
size_t tailShift(size_t tail) {
return tail != 0;
}
void clear_end() {
bits::clear_low_bits(buffer_[pos_ - 1 + tailShift(tail_pos_)], tail_pos_);
}
size_t pos_;
size_t tail_pos_;
std::vector<unsigned char> buffer_;
};
#endif //HUFFMAN_BITWRITER_H
| true |
bc8f4e6ccf87b458c08709db77cac7a320f634e0 | C++ | TheGreenBox/helium | /modules/heliumScreenObjects/include/heliumScreenConsole.h | UTF-8 | 1,870 | 2.671875 | 3 | [] | no_license | /* ========================================================
* Organization: The Green Box
*
* Project name: Helium
* File name: heliumScreenConsole.h
* Description: ScreenConsole Class
* Author: AKindyakov
* ========================================================
*/
#ifndef HELIUM_SCREEN_CONSOLE_INCLUDED
#define HELIUM_SCREEN_CONSOLE_INCLUDED
#include <list>
#include <Polycode.h>
#include "heliumScreenObjects.h"
class ScreenConsole {
public:
/**
* Create ScreenConsole
* @param _textSize
* @param _maxVisibleLines
* @param _stackSize
* @param _lineSpacing
* @param _defaultColor
*/
ScreenConsole( int _textSize,
int _maxVisibleLines,
int _stackSize,
double _lineSpacing = 0.0,
Polycode::Vector3 _defaultColor = Polycode::Vector3(0,0,0) );
virtual ~ScreenConsole();
/**
*
*/
void setPosition( Polycode::Vector3 _defaultColor = Polycode::Vector3(0,0,0) ){};
/**
*
*/
void add(const char*);
void add(const Polycode::String&);
/**
* Remove elements from the top
* @param numToRemove number of removed elements,
* if numToRemove > 0 - remove from the top of history
* if numToRemove < 0 - remove from the bottom of history
* if numToRemove = 0 - remove all history
*/
void clean(int numToRemove=0);
/**
* Add new line to the ScreenConsole
*/
void newLine();
/**
*
*/
void scroll(int);
private:
std::list< Polycode::ScreenLabel* > lines;
Polycode::Screen* screen;
double lineSpacing;
int textSize;
int maxVisibleLines;
int maxLines;
Polycode::Vector3 defaultColor;
int lines_count;
int visible_lines;
};
#endif // HELIUM_SCREEN_CONSOLE_INCLUDED
| true |
f34ef9970d54139a676bc0c0d90a0ae937d6d2a1 | C++ | nhrnjic6/heatingController | /src/Rule.h | UTF-8 | 459 | 2.515625 | 3 | [] | no_license | #include <NTPClient.h>
class Rule {
private:
int m_id;
int m_day;
int m_startHour;
int m_startMinute;
double m_maxTemperature;
public:
Rule();
Rule(int id ,int day, int startHour, int startMinute, double maxTemp);
int getId();
int getDay();
int getStartHour();
int getStartMinute();
double getMaxTemperature();
bool isBefore(NTPClient ntpClient);
bool isDirect();
void printInfoToSerial();
};
| true |
c09bd171b87f0ba514a00531e74e5812bc29a5b0 | C++ | smhemel/Algorithm | /Prime Generate/Prime Generate/main.cpp | UTF-8 | 1,425 | 2.609375 | 3 | [] | no_license | //
// main.cpp
// Prime Generate
//
// Created by S M HEMEL on 28/1/18.
// Copyright © 2018 Eastern University. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <algorithm>
#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032
using namespace std;
unsigned base[MAX/64], segment[RNG/64], primes[LEN];
#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
void sieve()
{
unsigned i, j, k;
for(i=3; i<LMT; i+=2)
if(!chkC(base, i))
for(j=i*i, k=i<<1; j<MAX; j+=k)
setC(base, j);
for(i=3, j=0; i<MAX; i+=2)
if(!chkC(base, i))
primes[j++] = i;
}
int segmented_sieve(int a, int b)
{
unsigned i, j, k, cnt = (a<=2 && 2<=b)? 1 : 0;
if(b<2) return 0;
if(a<3) a = 3;
if(a%2==0) a++;
mset(segment,0);
for(i=0; sq(primes[i])<=b; i++)
{
j = primes[i] * ( (a+primes[i]-1) / primes[i] );
if(j%2==0) j += primes[i];
for(k=primes[i]<<1; j<=b; j+=k)
if(j!=primes[i])
setC(segment, (j-a));
}
for(i=0; i<=b-a; i+=2)
if(!chkC(segment, i))
cnt++;
return cnt;
}
int main(){
int n,a,b;
cin >> n;
sieve();
while (n--) {
cin >> a >> b;
cout << segmented_sieve(a,b) << endl;
}
return 0;
}
| true |
2cfe09605ef903a52808907cc2eb8f9c437bbcd1 | C++ | humenghan314/TowerDefence | /enemy.h | UTF-8 | 884 | 2.578125 | 3 | [] | no_license | #ifndef ENEMY_H
#define ENEMY_H
#include "tfobj.h"
#include <string>
#include <QPoint>
class Enemy:public TFObj{
public:
Enemy(string type);
void show(QPainter *painter);
void move(QPoint A,QPoint B);
virtual void underAttack(int x, int y,int r,int damageValue);//传入炮台的攻击范围(炮台坐标和攻击半径)、攻击强度
void getDebuff(int x,int y,int r,int percent);
void setLayer(int x){this->layer=x;}
int getLayer(){return layer;}
void ManageEnemyMove();
int getDamageValue(){return damage;}
virtual string enemyType(){return "enemy";}
private:
int damage;//敌人一次伤害的数值
int steps;//每次移动的距离
int layer;//获得debuff的层数(防止debuff叠加或者导致step数据变为负数)
vector<QPoint>path;
};
bool betweenPoints(QPoint A,QPoint B,QPoint C);
#endif // ENEMY_H
| true |
43a9417292dc1be0918ad628bbb037895493c1c2 | C++ | ihewro/leetcode | /Utils/UF.hpp | UTF-8 | 1,853 | 3.15625 | 3 | [] | no_license | #pragma once
/**
* Copyright (c) 2020, SeekLoud Team.
* Date: 2021/1/11
* Main Developer: hewro
* Developer:
* Description:
* Refer:
*/
#include "Util.hpp"
#define SIZE 20
class UF {
public:
// 记录树的数目
int count;
// 节点 x 的节点是 parent[x],存储森林的数据结构
std::vector<int> parent;
//存储每棵数目的节点数目,优化1,减少连接时候的树的高度
vector<int> size;
public:
explicit UF(int n) {
this->count = n;
size.resize(n);
parent.resize(n);
for (int i = 0; i < n; i++) {//初始化,每个节点都是一颗树,自然每棵树的大小就是1
parent[i] = i;
size[i] = 1;
}
}
/* 将 p 和 q 连接 */
virtual void union_node(int p,int q){
std::cout << "union_node " << "p:" << p << " q:" << q <<std::endl;
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ)
return;
//连接两棵树
if (size[rootQ] < size[rootP]){
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}else{
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
//树的数目减少1
count--;
}
/* 判断 p 和 q 是否连通 */
virtual bool connected(int p, int q){
int p_parent = find(p);
int q_parent = find(q);
std::cout << "p:" << p << " q:"<< q << " p_parent:" << p_parent << " q_parent:" << q_parent << std::endl;
return p_parent == q_parent;
}
//找到 x 所在树的根节点
virtual int find(int x) {
if(parents[x] != x){ //x 的父亲节点不是根节点,则递归把 x放到树的根节点上
parents[x] = find(parents[x]);
}
return parents[x];
}
}; | true |
84f3bfbca753effc2457d3c2f7624a53e58cb121 | C++ | alexjhoff/C | /Compilers/phase2/parser.cpp | UTF-8 | 6,852 | 2.921875 | 3 | [] | no_license | # include <cstdio>
# include <cctype>
# include <string>
# include <iostream>
# include "lexer.h"
# include "lexer.cpp"
using namespace std;
int _token;
int lookahead;
static string lexbuf;
bool peekFlag = false;
/*
office hours:
W 12:00-1:00
Th 12:00-1:00
*/
void match(int t)
{
if(peekFlag == true){
_token = lookahead;
peekFlag = false;
}
else{
if (_token == t)
_token = lexan(lexbuf);
else
cout << "error on token:" << _token << "try to match " << t << endl;
}
}
int peek()
{
lookahead = lexan(lexbuf);
peekFlag = true;
return lookahead;
}
void matchEXPRLIST()
{
matchEXPR();
if(_token == COMMA){
match(COMMA);
matchEXPRLIST();
}
}
void matchID()
{
if(_token == ID){
match(ID);
if(_token == LPAREN){
match(LPAREN);
if(_token != RPAREN)
matchEXPRLIST();
match(RPAREN);
}
}
else if(_token == NUMBER)
match(NUMBER);
else if(_token == STRING)
match(STRING);
else if(_token == CHARACTER)
match(CHARACTER);
else{
match(LPAREN);
matchEXPR();
match(RPAREN);
}
}
void matchINDEX()
{
matchID();
while(_token == LBRACK || _token == DOT || _token == ARROW){
if(_token == LBRACK){
match(LBRACK);
matchEXPR();
match(RBRACK);
cout << "index" << endl;
}
else if(_token == DOT){
match(DOT);
matchID();
cout << "dot" << endl;
}
else{
match(ARROW);
matchID();
cout << "arrow" << endl;
}
}
}
void matchUNARY()
{
if(_token == ADDR){
match(ADDR);
matchUNARY();
cout << "addr" << endl;
}
else if(_token == STAR){
match(STAR);
matchUNARY();
cout << "deref" << endl;
}
else if(_token == NOT){
match(NOT);
matchUNARY();
cout << "not" << endl;
}
else if(_token == SUB){
match(SUB);
matchUNARY();
cout << "neg" << endl;
}
else if(_token == SIZEOF){
match(SIZEOF);
if(_token == LPAREN){
match(LPAREN);
matchSPECIFIER();
matchPOINTERS();
match(RPAREN);
}
else
matchUNARY();
cout << "sizeof" << endl;
}
else
matchINDEX();
}
void matchCAST()
{
int temp = peek();
if(_token == LPAREN && (temp == INT || temp == CHAR || temp == STRUCT)){
match(LPAREN);
matchSPECIFIER();
matchPOINTERS();
match(RPAREN);
matchCAST();
cout << "cast" << endl;
}
else
matchUNARY();
}
void matchMUL()
{
matchCAST();
while(_token == STAR || _token == DIV || _token == REM){
if(_token == STAR){
match(STAR);
matchCAST();
cout << "mul" << endl;
}
else if(_token == DIV){
match(DIV);
matchCAST();
cout << "div" << endl;
}
else{
match(REM);
matchCAST();
cout << "rem" << endl;
}
}
}
void matchADD()
{
matchMUL();
while(1){
if (_token == ADD){
match(ADD);
matchMUL();
cout << "add" << endl;
}
else if (_token == SUB){
match(SUB);
matchMUL();
cout << "sub" << endl;
}
else
break;
}
}
void matchLTN()
{
matchADD();
while(_token == LTN || _token == GTN || _token == LEQ || _token == GEQ){
if(_token == LTN){
match(LTN);
matchADD();
cout << "ltn" << endl;
}
else if(_token == GTN){
match(GTN);
matchADD();
cout << "gtn" << endl;
}
else if(_token == LEQ){
match(LEQ);
matchADD();
cout << "leq" << endl;
}
else{
match(GEQ);
matchADD();
cout << "geq" << endl;
}
}
}
void matchEQL()
{
matchLTN();
while(_token == EQLEQL || _token == NOTEQL){
if(_token == EQLEQL){
match(EQLEQL);
matchLTN();
cout << "eql" << endl;
}
else{
match(NOTEQL);
matchLTN();
cout << "neq" << endl;
}
}
}
void matchAND()
{
matchEQL();
while(_token == AND){
match(AND);
matchEQL();
cout << "and" << endl;
}
}
void matchEXPR()
{
matchAND();
while(_token == OR){
match(OR);
matchAND();
cout << "or" << endl;
}
}
void matchSTATEMENT()
{
if(_token == LBRACE){
match(LBRACE);
matchDECLARATIONS();
while(_token != RBRACE)
matchSTATEMENTS();
match(RBRACE);
}
else if(_token == RETURN){
match(RETURN);
matchEXPR();
match(SCOLON);
}
else if(_token == WHILE){
match(WHILE);
match(LPAREN);
matchEXPR();
match(RPAREN);
matchSTATEMENT();
}
else if(_token == IF){
match(IF);
match(LPAREN);
matchEXPR();
match(RPAREN);
matchSTATEMENT();
if(_token == ELSE){
match(ELSE);
matchSTATEMENT();
}
}
else{
matchEXPR();
if(_token == EQL){
match(EQL);
matchEXPR();
}
match(SCOLON);
}
}
void matchSTATEMENTS()
{
while(_token != RBRACE){
matchSTATEMENT();
}
}
void matchDECLARATOR()
{
matchPOINTERS();
match(ID);
if(_token == LBRACK){
match(LBRACK);
match(NUMBER);
match(RBRACK);
}
}
void matchDEC()
{
matchSPECIFIER();
matchDECLARATOR();
while(_token == COMMA){
match(COMMA);
matchDECLARATOR();
}
match(SCOLON);
}
void matchDECLARATIONS()
{
while(_token == INT || _token == CHAR || _token == STRUCT)
matchDEC();
}
void matchPARAM()
{
matchSPECIFIER();
matchPOINTERS();
match(ID);
}
void matchPARAMLIST()
{
matchPARAM();
if(_token == COMMA){
match(COMMA);
matchPARAMLIST();
}
}
void matchPARAMS()
{
if(_token == VOID)
match(VOID);
else
matchPARAMLIST();
}
void matchSPECIFIER()
{
if(_token == INT)
match(INT);
else if(_token == CHAR)
match(CHAR);
else{
match(STRUCT);
match(ID);
}
}
void matchPOINTERS()
{
while(_token == STAR){
match(STAR);
}
}
void matchGDEC()
{
matchPOINTERS();
match(ID);
if(_token == LBRACE){
match(LBRACE);
match(NUMBER);
match(RBRACE);
}
else if(_token == LPAREN){
match(LPAREN);
match(RPAREN);
}
}
void matchGDECLIST()
{
while(_token == COMMA){
match(COMMA);
matchGDEC();
}
match(SCOLON);
}
void matchTranslation()
{
matchSPECIFIER();
if(_token == LBRACE){ //type-def case
match(LBRACE);
matchDECLARATIONS();
match(RBRACE);
match(SCOLON);
}
else{
matchPOINTERS();
match(ID);
if(_token == LPAREN){ //pointers id() || funct-def case
match(LPAREN);
if(_token == RPAREN){ //pointers id()
match(RPAREN);
}
else{ //funct-def case
matchPARAMS();
match(RPAREN);
match(LBRACE);
matchDECLARATIONS();
matchSTATEMENTS();
match(RBRACE);
}
}
else if(_token == LBRACK){ //pointers id [num]
match(LBRACK);
match(NUMBER);
match(RBRACK);
}
if(_token == COMMA || _token == SCOLON){
matchGDECLIST();
}
}
}
int main()
{
_token = lexan(lexbuf);
while(_token != DONE){
matchTranslation();
}
return 1;
};
/*
EXAMPLE PARSER MODIFICATIONS
int matchPOINTERS()
{
int count = 0;
while(_token == STAR){
count++;
match(STAR);
}
return count;
}
string matchSPECIFIER()
{
if(_token == CHAR){
match(CHAR);
return "char";
}
if(_token == INT){
match(INT);
return "int";
}
match(STRUCT);
string s = lexbuf;
match(ID);
return s;
}
void matchDEC()
{
string s = matchSPECIFIER();
matchDECLARATOR(s);
while(_token == COMMA){
match(COMMA);
matchDECLARATOR(s);
}
match(SCOLON);
}
*/
| true |
ceb2ec39df52d854b8318076656e04a4d808e9b6 | C++ | YuilTripathee/CPP_programming | /Extra practise resources/Chapter 2 - Basics/2) pyramid.cpp | UTF-8 | 240 | 2.78125 | 3 | [
"MIT"
] | permissive | //program no 2
#include<iostream>
#include<iomanip>
using namespace std;
main()
{
cout << setw(4) << "*" << endl;
cout << setw(5) << "***" << endl;
cout << setw(6) << "*****" << endl;
cout << "*******" << endl;
}
| true |
e8c46d1de29f35981a7079f4f6b6400b6c11f136 | C++ | aberry5621/Lab-Exercises-20160914 | /for_loop.cpp | UTF-8 | 290 | 3.171875 | 3 | [] | no_license | //
// for_loop.cpp
// Lab Exercise 3 20160914
// Copyright © 2016 COMP130. All rights reserved.
//
#include <iostream>
using namespace std;
int main() {
cout << "For Loop \n";
// I // P // O
for (int i = 10; i < 100; i = i+20) {
cout << i << endl;
}
// 0
return 0;
}
| true |
110d0c0068a6dff98f830cb5c4ed843985c05156 | C++ | cjhgo/learn_and_use | /cpp/c++primer/sharedptr-race-cond.cpp | UTF-8 | 741 | 3.171875 | 3 | [] | no_license | #include <memory>
#include <mutex>
#include <thread>
#include <iostream>
#define CNT 1000
std::shared_ptr<int> g,g2;
std::mutex mut;
void readg()
{
std::shared_ptr<int> temp;
int sum=0;
for(int i = 0; i < CNT; i++)
{
temp.reset();
{
// std::lock_guard<std::mutex> lock(mut);
temp=g;
}
sum += *temp;
}
std::cout<<sum<<std::endl;
}
wrtieg2()
{
}
void writeg()
{
for(int i = 0; i < CNT;i++)
{
std::shared_ptr<int> temp(new int(3));
{
// std::lock_guard<std::mutex> lock(mut);
g=temp;
}
}
}
int main(int argc, char const *argv[])
{
g.reset(new int(3));
std::thread t1(readg),t2(writeg);
t1.join();
t2.join();
return 0;
}
| true |
dea7455342dd3ade25304f3dee4c0046adf172f0 | C++ | SidneyTTW/PCHMS-Remake | /src/linechart.h | UTF-8 | 1,224 | 3.03125 | 3 | [] | no_license | #ifndef LINECHART_H
#define LINECHART_H
#include <qwt_plot_curve.h>
#include <QVector>
/**
* @brief A class of a line chart.
*/
class LineChart : public QwtPlotCurve
{
public:
static const int RttiLineChart = 1001;
/**
* @brief Constructor.
*/
LineChart(const QString &, const QColor &);
/**
* @brief Set the color.
*/
void setColor(const QColor &);
/**
* @brief Set the values.
*
* @param v The values.
* @param t The tooptips.
*/
void setValues(const QVector<QPointF>& v, const QVector<QString>& t);
/**
* @brief Set the tooltip of the whole chart.
* @param tooltip The tooptip.
*/
void setTooltip(QString tooltip);
/**
* @return Tooltip of the whole chart.
*/
inline QString getTooltip() const
{return tooltip;}
/**
* @brief Get the tooltip at given index.
*
* @param index The given index;
*/
inline QString getTooptipAt(int index) const
{
if (index >= 0 && index < tooltips.size())
return tooltips.at(index);
return "";
}
/**
* @brief The rtti to figure out which kind of chart it is.
*/
virtual int rtti() const;
private:
QVector<QString> tooltips;
QString tooltip;
};
#endif // LINECHART_H
| true |
a3e209b6e2adf5ef814ceecbe3db00c293121cf0 | C++ | nissafors/pelletmeter | /test/distance/stub.cpp | UTF-8 | 1,035 | 2.625 | 3 | [
"MIT"
] | permissive | /* Copyright (C) 2021 Andreas Andersson */
#include "stub.h"
#include <cassert>
#include "Arduino.h"
const uint8_t N_PINS = 13;
bool init = false;
uint8_t stubPinMode[N_PINS];
unsigned long stubPulseIn;
void stubInit()
{
init = true;
for (uint8_t i = 0; i < N_PINS; i++)
{
stubPinMode[i] = PINMODE_NOT_SET;
}
stubPulseIn = 0;
}
void stubDeinit()
{
init = false;
}
// Spies
uint8_t stubGetPinMode(uint8_t pin)
{
assert(init);
return stubPinMode[pin];
}
void stubSetPulseIn(unsigned long pulse)
{
assert(init);
stubPulseIn = pulse;
}
// Stubs
void pinMode(uint8_t pin, uint8_t mode)
{
assert(init);
stubPinMode[pin] = mode;
}
void digitalWrite(uint8_t pin, uint8_t val)
{
UNUSED(pin);
UNUSED(val);
assert(init);
}
void delayMicroseconds(unsigned int us)
{
UNUSED(us);
assert(init);
}
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
assert(init);
UNUSED(pin);
UNUSED(state);
UNUSED(timeout);
return stubPulseIn;
}
| true |
762d6db30ad762c084e4c0a5668342a6851961e7 | C++ | sooglejay/geeksforgeeks | /basic/atio implement.cpp | UTF-8 | 1,294 | 3.34375 | 3 | [] | no_license | //
// Created by sooglejay on 16/12/18.
//
//
//Your task is to implement the function atoi. The function takes a string(str) as argument and converts it to an integer and returns it.
//
//Input:
// The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains a string str .
//
//Output:
// For each test case in a new line output will be an integer denoting the converted integer, if the input string is not a numerical string then output will be -1.
//
//Constraints:
//1<=T<=100
//1<=length of (s,x)<=10
//
//Example(To be used only for expected output) :
//Input:
//2
//123
//21a
//
//Output:
//123
//-1
/*You are required to complete this method */
int atoi(string str)
{
int len = str.size();
int minus='-';//48-57
int sum = 0 ;
int count = 0;
for (int i = len-1; i>=1; --i) {
int num = str[i]-'0';
if(num<=9&&num>=0){
sum += num*(int)pow(10,count);
}else{
return -1;
}
count++;
}
if(str[0]=='-'){
return sum*-1;
}else {
int num = str[0]-'0';
if(num<=9&&num>=0){
sum += num*(int)pow(10,count);
}else{
return -1;
}
}
return sum;
}
| true |
bb79f622ce32a55beef750dfb65ca4ae5b463794 | C++ | Zoxc/scaled | /river/color.hpp | UTF-8 | 486 | 2.921875 | 3 | [] | no_license | #pragma once
#include <stdint.h>
namespace River
{
typedef uint32_t color_t;
uint8_t color_red_component(color_t color);
uint8_t color_green_component(color_t color);
uint8_t color_blue_component(color_t color);
uint8_t color_alpha_component(color_t color);
const color_t color_black = 0x000000FF;
const color_t color_white = 0xFFFFFFFF;
color_t mix_color(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha);
color_t mix_color_alpha(color_t input, uint8_t alpha);
};
| true |
6b5d6d5830ffcbecb79f1ac5308ddb7842b25f64 | C++ | choyj0920/SBS_academy_unreal_engine | /learnAPI/LearnAPI/CPP_과제등등/CPP_7조_teamPJ_2_Tetris/CPP_teamPJ_2_Tetris/GameManager.cpp | UHC | 10,347 | 2.828125 | 3 | [] | no_license | #include "mainheader.h"
GameManager::GameManager()
{
initData();
}
GameManager::~GameManager()
{
}
// ʱȭ Լ
void GameManager::initData()
{
// Ż ʱȭԼ
Block::init_total();
// , μ, ʱȭ
stagelevel = 0;
clearline = 0;
score = 0;
}
void GameManager::show_gamestat()
{
//ó ѹ ѵ ھ ۾ ٽ Ϸ κΰ
//printed_text 0 ƴ ϴ κ ǹ̰ µ? -ϴ ׳
static int printed_text = 0; // ؿִ ǹ ǿ ǹ
SetColor(GRAY);
if (printed_text == 0)
{ //
gotoxy(35, 7);
printf("STAGE");
gotoxy(35, 9);
printf("SCORE");
gotoxy(35, 12);
printf("LINES");
}
gotoxy(41, 7);
printf("%d", stagelevel + 1);
gotoxy(35, 10);
printf("%10d", score);
gotoxy(35, 13);
printf("%10d", STAGE::stage[stagelevel].getclear_line() - clearline);
}
void GameManager::GameRun()
{
//
SetCursorvisible(false); //۽ Ŀ
int is_gameover = 0;
initData(); //ʱȭ Լ
Logo(); //ΰ
while (true) //
{
SetCursorvisible(true);// ý Ŀ
input_data(); // Լ
SetCursorvisible(false); // Ŀ
Block::show_total_block(stagelevel); //Ż - ó
//
MoveBlock = Block::make_new_block(STAGE::stage[stagelevel].getStick_rate()); //
MoveBlock.block_start(); // ʱȭ
NextBlock = Block::make_new_block(STAGE::stage[stagelevel].getStick_rate()); //
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
MoveBlock.show_cur_block(); // ̵ - ϸ
NextBlock.show_next_block(stagelevel); // ĭ ǥ
show_gamestat();
for (int i = 0; true; i++) { //
if (_kbhit()) { //ŰԷ
char keytemp = _getch();
if (keytemp == KEY_ESC) { //escԷ -
initData(); // ʱȭ
system("cls"); //ü ʱȭ
MoveBlock.block_start(); //
break;
}
if (keytemp == EXT_KEY) {//ȮŰ- ŰԷ½
keytemp = _getch();//ȮŰ
switch (keytemp)
{
case KEY_UP: { //Ű- ȸ Ű
MoveBlock.erase_cur_block(); //̵ ϴ
MoveBlock.rotate_Right(); //ȸ ų ȸִ Լ
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
MoveBlock.show_cur_block(); // ̵
break;
}
case KEY_LEFT: {//Ű -̵Ű
if (MoveBlock.getPos().x > LEFTSIDE) { //̵
MoveBlock.erase_cur_block(); //̵ ϴ
MoveBlock.moveX(-1); //ĭ ̵
if (MoveBlock.strike_check()) { //浹ϸ
MoveBlock.moveX(1); //ٽ ġ
}
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
MoveBlock.show_cur_block(); // ̵
}
break;
}
case KEY_RIGHT: {//Ű ̵Ű
if (MoveBlock.getPos().x < RIGHTSIDE) {//̵ -̰Ŵ ǹ̰ µ
MoveBlock.erase_cur_block(); //̵ ϴ
MoveBlock.moveX(1); // ĭ ̵
if (MoveBlock.strike_check()) {//浹ϸ
MoveBlock.moveX(-1); //ٽ ġ
}
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
MoveBlock.show_cur_block(); // ̵
}
break;
}
case KEY_DOWN: { //ƷŰ - ϴ Ű
is_gameover = move_block(); // ĭ Ʒ ̵Լ
if(is_gameover==0) //0 Ǿ
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
//is_gameover ==2 Ʒ ¼ ġ x
MoveBlock.show_cur_block(); // ̵
break;
}
default:
break;
}
continue;
}
if (keytemp == SPACEBAR) { //̽ٸ
while (is_gameover == 0) {
is_gameover = move_block();// Ʒ
}//̵ ̺κп ϰ ġ ϱ..
MoveBlock.show_cur_block();
}
}
if (is_gameover == 1) { // Ǹ
showGameover(); //ӿ
SetColor(GRAY); //
initData(); // ʱȭ
MoveBlock.block_start();
is_gameover = 0;
break;
}
if (STAGE::stage[stagelevel].getclear_line() <=clearline) // μ Ŭ
{
clearline -= STAGE::stage[stagelevel].getclear_line(); //μ ʱȭ
Block::show_total_block(++stagelevel); // ʱȭ -
show_gamestat();
}
if ((i % STAGE::stage[stagelevel].getSpeed()) == 0) {
if (is_gameover != 1) {
is_gameover = move_block();
naviBlock.show_naviblock(MoveBlock); // Ϻ̱
MoveBlock.show_cur_block(); // ̵
}
}
//º ʱȭ
gotoxy(77, 23);
Sleep(15);
gotoxy(77, 23);
}
//Լ ʱȭ
initData();
}
}
void GameManager::fullLine()
{
clearline += 1; // Ŭ Ǹ +1
score += 100 + (stagelevel * 10) + (rand() % 10); //
show_gamestat(); //
}
int GameManager::getStagelevel() const
{
return stagelevel;
}
//Ͽ ִ Լ
int GameManager::move_block()
{
MoveBlock.erase_cur_block(); // ġ
MoveBlock.moveY(1); //Ʒ ĭ ̵
if (MoveBlock.strike_check()) {// ̺ Ż ϰ 浹
MoveBlock.moveY(-1);
if (MoveBlock.check_in_Total()) {//
MoveBlock.merge_block();
Block::check_full_line(*this);
Block::show_total_block(stagelevel);
show_gamestat(); //
MoveBlock = NextBlock; // Ӱ ٲٱ
MoveBlock.block_start(); //
NextBlock = Block::make_new_block(STAGE::stage[stagelevel].getStick_rate());
NextBlock.show_next_block(stagelevel);
return 2;
}
else {
return 1;
}
}
return 0;
}
//ΰ Լ
void GameManager::Logo()
{
int i, j;// ݺ Ǵ
// ºε
gotoxy(13, 3);
printf(""); //
Sleep(100);
gotoxy(13, 4);
printf("ߡߡ ߡߡ ߡߡ ߡ ");
Sleep(100);
gotoxy(13, 5);
printf(" ߡ ");
Sleep(100);
gotoxy(13, 6);
printf(" ߡߡ ߡ ");
Sleep(100);
gotoxy(13, 7);
printf(" ߡ ");
Sleep(100);
gotoxy(13, 8);
printf(" ߡߡ ");
Sleep(100);
gotoxy(13, 9);
printf(""); //
gotoxy(28, 20);
printf("Please Press Any Key~!");
// Ű Է ݺؼ ϵ
for (i = 0; i >= 0; i++)
{
if (i % 40 == 0)
{
for (int i = 14; i < 19; i++) {
gotoxy(6, i); printf("%95s", ""); //-ܻ
}
Block(rand() % 7, rand() % 4, {6,14}).show_cur_block();
Block(rand() % 7, rand() % 4, { 12,14 }).show_cur_block();
Block(rand() % 7, rand() % 4, { 19,14 }).show_cur_block();
Block(rand() % 7, rand() % 4, { 24,14 }).show_cur_block();
}
if (kbhit())
break;
Sleep(30);
}
getche();
system("cls");
return;
}
// Լ
void GameManager::input_data()
{
int i = 0; // Է¹
SetColor(GRAY);
gotoxy(10, 7);
printf(" < GAME KEY > "); //
Sleep(10);
gotoxy(10, 8);
printf(" UP : Rotate Block ");
Sleep(10);
gotoxy(10, 9);
printf(" DOWN : Move One-Step Down ");
Sleep(10);
gotoxy(10, 10);
printf(" SPACE: Move Bottom Down ");
Sleep(10);
gotoxy(10, 11);
printf(" LEFT : Move Left ");
Sleep(10);
gotoxy(10, 12);
printf(" RIGHT: Move Right ");
Sleep(10);
gotoxy(10, 13);
printf(""); //
while (i < 1 || i>8)// 1̸ 8ʰμ϶ ٽ Է¹
{
gotoxy(10, 3);
printf("Select Start level[1-8]: \b\b\b\b\b\b\b\b\b\b\b\b\b\b");
scanf("%d", &i);
while (getchar() != '\n'); //۸ :scanf Ͱ ۿ ִٰ νĵǾ ѹݺǹǷ
/*
if (scanf("%d", &i) == 0) { κ ̷ ٲ㵵
rewind(stdin);
}
*/
}
stagelevel = i - 1;
system("cls");
return;
}
//ӿ
void GameManager::showGameover()
{
//
SetColor(RED);
gotoxy(15, 8);
printf("");
gotoxy(15, 9);
printf("**************************");
gotoxy(15, 10);
printf("* GAME OVER *");
gotoxy(15, 11);
printf("**************************");
gotoxy(15, 12);
printf("");
fflush(stdin); //ݱ ִ Է ۸
Sleep(1000); //1
getche();
system("cls");
return;
}
| true |
911c01d9845bb0d7408fbd3b3795ff3b5aac88f7 | C++ | bonly/exercise | /2010/201007/20100716_menu.cpp | UTF-8 | 2,589 | 2.671875 | 3 | [] | no_license | /**
* @file 20100716_menu.cpp
* @brief
* @author bonly
* @date 2012-11-6 bonly Created
*/
#include <boost/python.hpp>
#include <boost/thread.hpp>
#include <iostream>
using namespace boost::python;
class PyInf
{
public:
PyInf()
{
Py_Initialize();
//PyEval_InitThreads(); ///多线程支持
main_mod = import("__main__"); ///如果在python语句中使用了变量,就须要指定场景参数,则导入这个
main_spa = main_mod.attr("__dict__");
}
void init()
{
//PyEval_AcquireLock();
//Py_BEGIN_ALLOW_THREADS;
exec_file ("20100715_menu.py",main_spa);
exec("app = wx.PySimpleApp()\n"
"frame = ToolbarFrame(parent=None, id=-1)\n"
"frame.Show()\n", main_spa);
//PyEval_ReleaseLock();
//Py_END_ALLOW_THREADS;
}
void ClickButton()
{
//PyEval_AcquireLock();
//Py_BEGIN_ALLOW_THREADS;
std::clog << "u click the button\n";
exec("import wx", main_spa);
//exec("print 10", main_spa);
/*
exec("dlg=wx.MessageDialog(None, 'c直接建对话框','MessageDialog', wx.YES_NO|wx.ICON_QUESTION);\n"
"result=dlg.ShowModal();\n"
"dlg.Destroy();"
,main_spa);
//*/
//Py_END_ALLOW_THREADS;
//PyEval_AcquireLock();
}
void run()
{
//PyEval_AcquireLock();
//Py_BEGIN_ALLOW_THREADS;
exec("app.MainLoop()\n", main_spa);
//PyEval_ReleaseLock();
//Py_END_ALLOW_THREADS;
}
~PyInf()
{
//PyEval_ReleaseLock(); ///多线程释放
//Py_END_ALLOW_THREADS;
Py_Finalize();
}
private:
object main_mod;
object main_spa;
};
BOOST_PYTHON_MODULE(inf)
{
class_<PyInf>("PyInf").def("ClickButton", &PyInf::ClickButton);
}
void other_call(PyInf &py)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(5000));
py.ClickButton();
}
int main(int argc, char *argv[])
{
try
{
PyInf myc;
myc.init();
boost::thread thr(&PyInf::run, myc);
/*
PyInf otc;
otc.init();
boost::thread cl(&other_call, otc);
*/
//boost::thread cl(&other_call, myc);
thr.join();
//cl.join();
}
catch (...)
{
PyErr_Print();
}
return 0;
}
| true |
3e1f4a4ae5074ae303245f1751f23454f9b268b5 | C++ | zy0016/MyExam | /exam/exam/exam/linkstructor.h | UTF-8 | 1,814 | 2.5625 | 3 | [] | no_license | #ifndef _LINK_STRUCTOR_
#define _LINK_STRUCTOR_
#include <fstream>
#include <string>
#include "stdlib.h"
#include <time.h>
#include <iostream>
#include <list>
#include <vector>
#include <iostream>
#include <algorithm>
struct node_
{
int val ;
struct node_ *next;
};
typedef struct node_ node;
struct charnode_
{
char val ;
struct charnode_ *next;
};
typedef struct charnode_ charnode;
struct pnode_
{
int* val ;
struct pnode_ *next;
};
typedef struct pnode_ pnode;
struct cnode_
{
char* val;
struct cnode_ *next;
};
typedef struct cnode_ cnode;
struct nodem_
{
cnode *pcnode;
char* str_sorted;
struct nodem_ *next;
};
typedef struct nodem_ nodem;
pnode * AddNode(int* value ,int len, pnode *a);
cnode * AddNode(const char* value, cnode *a);
nodem * AddNode(const char* str_ori, const char* str_sorted, nodem *a);
bool FindNode(cnode *s, const char *str);
void DeleteAllNodes(cnode *s);
int getAmountLink(node *p);
charnode * pushNode(char value , charnode *a);
charnode * popupNode(charnode *a,char *c);
int getTopNode(charnode *a,char *c);
void releaseNode(charnode *a);
int getNodeCount(charnode *s);
int getNodeCharAll(charnode *s,char *buf,unsigned int buflen);
node **findNode(node *root, int key);
bool remove_if(node **head, int key);
node * AddNode(int value , node *a);
void AddNode(int value, node **a);
void DeleteAllNodes(node *s);
node* DeleteNodeByValue(node *head, int value);
node* DeleteNodeById(node *head, unsigned int id);
void ShowNode(node *s);
node * reverse( node *n);
node * reverse( node *n,int k);
node *merge_1(node *a,node *b);
node *merge_2(node *a,node *b);
node *merge_3(node *a,node *b);
int GetLinkLength(node *s);
void LinkAction();
#endif /*_LINK_STRUCTOR_*/ | true |
044b29a22613ef29a84e603864a81d43419aa987 | C++ | ZhongpuXia/utils | /interpolation/src/unittest/polynomial_test.cpp | UTF-8 | 2,901 | 3.0625 | 3 | [] | no_license | #include "polynomial.h"
#include "gtest/gtest.h"
namespace planning {
TEST(PolynomialTest, evaluate) {
Polynomial func; //f(x)
EXPECT_EQ(func(0.0), 0.0);
EXPECT_EQ(func(1.0), 0.0);
EXPECT_EQ(func.order(), 0);
Polynomial func0({2.0}); //f(x) = 2.0
EXPECT_EQ(func0(0.0), 2.0);
EXPECT_EQ(func0(1.0), 2.0);
EXPECT_EQ(func0.order(), 0);
Polynomial func1({1.0, 2.0}); //f(x) = x + 2
EXPECT_EQ(func1(0.0), 2.0);
EXPECT_EQ(func1(1.0), 3.0);
EXPECT_EQ(func1.order(), 1);
Polynomial func2({3.0, 1.0, 2.0}); //f(x) = 3x^2 + x + 2
EXPECT_EQ(func2(0.0), 2.0);
EXPECT_EQ(func2(1.0), 6.0);
EXPECT_EQ(func2(10.0), 312.0);
EXPECT_EQ(func2.order(), 2);
Polynomial func3({-3.0, 1.0, 2.0}); //f(x) = -3x^2 + x + 2
EXPECT_EQ(func3(0.0), 2.0);
EXPECT_EQ(func3(1.0), 0.0);
EXPECT_EQ(func3(10.0), -288.0);
EXPECT_EQ(func3.order(), 2);
Polynomial func_0({0.0, 0.0, 0.0, 0.0}); // f(x) = 0.0
EXPECT_EQ(func_0(0.0), 0.0);
EXPECT_EQ(func_0.order(), 0);
Polynomial func_1({0.0, 0.0, 0.0, 1.0}); // f(x) = 1.0
EXPECT_EQ(func_1(0.0), 1.0);
EXPECT_EQ(func_1.order(), 0);
}
TEST(PolynomialTest, derive) {
Polynomial func; //f(x)
EXPECT_EQ(func.derive()(0.0), 0.0);
EXPECT_EQ(func.derive()(1.0), 0.0);
Polynomial func0({2.0}); //f(x) = 2.0
EXPECT_EQ(func0.derive()(0.0), 0.0);
EXPECT_EQ(func0.derive()(1.0), 0.0);
Polynomial func1({1.0, 2.0}); //f(x) = x + 2
EXPECT_EQ(func1.derive()(0.0), 1.0);
EXPECT_EQ(func1.derive()(1.0), 1.0);
Polynomial func2({3.0, 1.0, 2.0}); //f(x) = 3x^2 + x + 2
EXPECT_EQ(func2.derive()(0.0), 1.0);
EXPECT_EQ(func2.derive()(1.0), 7.0);
EXPECT_EQ(func2.derive()(10.0), 61.0);
Polynomial func3({-3.0, 1.0, 2.0}); //f(x) = -3x^2 + x + 2
EXPECT_EQ(func3.derive()(0.0), 1.0);
EXPECT_EQ(func3.derive()(1.0), -5.0);
EXPECT_EQ(func3.derive()(10.0), -59.0);
}
TEST(PolynomialTest, integrate) {
Polynomial func; //f(x)
EXPECT_EQ(func.integrate()(0.0), 0.0);
EXPECT_EQ(func.integrate()(1.0), 0.0);
Polynomial func0({2.0}); //f(x) = 2.0
EXPECT_EQ(func0.integrate()(0.0), 0.0);
EXPECT_EQ(func0.integrate()(1.0), 2.0);
Polynomial func1({1.0, 2.0}); //f(x) = x + 2
EXPECT_EQ(func1.integrate()(0.0), 0.0);
EXPECT_EQ(func1.integrate()(1.0), 2.5);
Polynomial func2({3.0, 1.0, 2.0}); //f(x) = 3x^2 + x + 2
EXPECT_EQ(func2.integrate()(0.0), 0.0);
EXPECT_EQ(func2.integrate()(1.0), 3.5);
EXPECT_EQ(func2.integrate()(10.0), 1070);
Polynomial func3({-3.0, 1.0, 2.0}); //f(x) = -3x^2 + x + 2
EXPECT_EQ(func3.integrate()(0.0), 0.0);
EXPECT_EQ(func3.integrate()(1.0), 1.5);
EXPECT_EQ(func3.integrate()(10.0), -930.0);
}
} // end of planning
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
a1df08afa1f13edb097d14c96b5d70a12ad0f790 | C++ | dexter1691/Algorithms | /UVA/UVA10911.cpp | WINDOWS-1252 | 1,085 | 2.515625 | 3 | [] | no_license | /**
UVA 10911 Forming Quiz Teams
Tags: DP
*/
#include <stdio.h>
#include <math.h>
#define min(a,b) (a<b)?a:b
int max;
int n;
int x[20];
int y[20];
double dist[20][20],dp[1<<16];
char name[20];
double minD(int state)
{
if(state==max)
return 0;
else if(dp[state]!=-1)
return dp[state];
else
{
int i,j;
double m=1<<30;
for(i = 0;i<2*n;i++)
if(!(state&(1<<i)))
for(j=i+1;j<2*n;j++)
if(!(state&(1<<j)))
m = min(m,dist[i][j]+minD(state|(1<<i)|(1<<j)));
return dp[state]=m;
}
}
int main()
{
int i,j,cc=1;
scanf("%d",&n);
while(n)
{
max = (1<<(2*n))-1;
for(i=0;i<2*n;i++)
scanf("%s %d %d",name,x+i,y+i);
for(i=0;i<2*n;i++)
for(j=i+1;j<2*n;j++)
dist[i][j]=dist[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
for(i=0;i<=max;i++)
dp[i]=-1;
printf("Case %d: %.2lf\n",cc++,minD(0));
scanf("%d",&n);
}
return 0;
} | true |
fde07a2ebdae0499b8a88c1de9112b6287e3007e | C++ | github188/demodemo | /other_projects/base_station_monitor/GokuClient/src/client_demo.cpp | UTF-8 | 1,454 | 2.734375 | 3 | [] | no_license |
#include <iostream>
#include "GokuClient.cpp"
using namespace std;
void output(wstring &src){
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
int writeLen = wcstombs(buffer, src.c_str(), src.length());
cout << buffer;
}
int call_back(int sessionId, char *pBuffer, int len){
cout << "call_back session " << sessionId << " size:" << len << "\n";
sleep(3);
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
GokuClient *client; //("127.0.0.1");
wstring host(L"127.0.0.1:8000");
client = new GokuClient(host, host);
write_log("start client...");
//string user = ""
int code = client->login(L"test1", L"pass");
//write_log("login status:")
cout << "login status:" << code << "\n";
int count = client->list_basestation();
cout << "list station:" << count << "\n";
if(count > 0){
for (int i = 0; i < count; i++){
cout << "uuid:";
output(client->station_list[i]->uuid);
cout << "\n" << endl;
cout << "route:";
output(client->station_list[i]->route);
cout << "\n" << endl;
}
}
host = L"10020002";
client->replay(host, &call_back, 1);
cout << "waiting replay video....";
sleep(10);
delete client;
/*
BaseStation bs(*new string("123$1$2"));
cout << "uuid:" << bs.uuid << "\n";
cout << "devType:" << bs.devType << "\n";
cout << "devType2:" << bs.idevType << "\n";
cout << "route:" << bs.route << "\n";
cout << "status:" << bs.status << "\n";
*/
return 0;
}
| true |
59b0750086e9606885cd0b1a4d12ee2cbe9fd0a9 | C++ | adfa0117/UniversityProject | /programming/1-1/객체지향프로그래밍/review3/OfficeItem.cpp | UTF-8 | 718 | 3.015625 | 3 | [] | no_license | #include "OfficeItem.h"
#include <iostream>
void OfficeItem::displayItem() const {
cout << code << "\t" << name << "\t" << price << "\t" << company << endl;
}
int OfficeItem::readItemFromFile(ifstream& fin) {
string _code;
string _name;
int _price;
string _company;
bool isAble = true;
fin >> _code;
if (!fin) isAble = false;
fin >> _name;
if (!fin) isAble = false;
fin >> _price;
if (!fin) isAble = false;
fin >> _company;
if (!fin) isAble = false;
if (isAble) {
code = _code;
name = _name;
price = _price;
company = _company;
return 1;
}
else return 0;
}
void OfficeItem::writeItemToFile(ofstream& fout) {
fout << code << "\t" << name << "\t" << price << "\t"<< company <<endl;
} | true |
e4a5bf0021352e9dd5c2533f5b570697dad12633 | C++ | nguyen-hoang-viet/arduino | /quacau.ino | UTF-8 | 1,263 | 2.890625 | 3 | [] | no_license | #define buttonA 13
#define buttonB 1
#define greenA 6
#define greenB 5
#define yellowA 7
#define yellowB 4
#define redA 8
#define redB 3
bool kt=1;
void setup() {
// put your setup code here, to run once:
for (int i = 3; i <= 8; i++)
pinMode (i, OUTPUT);
Serial.begin(9600);
pinMode (buttonA, INPUT); //thiet lap buttonA o che do input
pinMode (buttonB, INPUT); //thiet lap buttonB o che do input
digitalWrite(greenA,HIGH);
digitalWrite(redB,HIGH);
kt=false;
}
void nhay(int n, int a) {
//hàm nháy n lần đèn a
for (int i = 1; i <= n; i++) {
digitalWrite(a, HIGH);
delay(50);
digitalWrite(a, LOW);
delay(50);
}
}
void loop() {
// put your main code here, to run repeatedly:
if (digitalRead(buttonB)==0&&kt==false){
digitalWrite(greenA,LOW);
nhay(3,yellowA);
digitalWrite(redA,HIGH);
delay(6000);
digitalWrite(redB,LOW);
nhay(3,yellowB);
digitalWrite(greenB,HIGH);
kt=true;
}
if (digitalRead(buttonA)==0&&kt==true){
digitalWrite(greenB,LOW);
nhay(3,yellowB);
digitalWrite(redB,HIGH);
delay(6000);
digitalWrite(redA,LOW);
nhay(3,yellowA);
digitalWrite(greenA,HIGH);
kt=false;
}
}
| true |
2baa0731d6d49a6271cc3d7b128885f5e3a376ab | C++ | siradam7th/CyanOS | /kernel/Filesystem/Mountpoint.h | UTF-8 | 398 | 2.515625 | 3 | [] | no_license | #pragma once
#include "FSNode.h"
#include "utils/List.h"
#include "utils/types.h"
class Mountpoint
{
private:
struct MountpointMapping {
FSNode* old_node;
FSNode* new_node;
};
static List<MountpointMapping>* m_mountpoints;
public:
static void setup();
static void register_mountpoint(FSNode& old_fs_node, FSNode& new_fs_node);
static FSNode& translate_mountpoint(FSNode& node);
};
| true |
66446377d082bab3c26a3ca4f8d56ed99be999b9 | C++ | Eva7em/Semester-1 | /WS1213/Grundlagen_der_Informatik_-_Juettner/Uebungen_und_Aufgaben/Print32Bitline_Gleitkomma.cpp | UTF-8 | 284 | 2.921875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
void Print32BitLine(unsigned long* ui)
{ int i;
for(i=0; i<32; i++)
{ if(*ui & (0x80000000>>i))
printf("1");
else
printf("0");
}
printf("\n");
}
int main()
{
float f = 1.0;
Print32BitLine((unsigned long*) &f);
system("PAUSE");
};
| true |
4961be78918c6df664e1310ae1576e229cc3941b | C++ | ccl1616/programming-10802 | /mid03/mid3_pra/social_distance/social_v2.cpp | UTF-8 | 2,510 | 3.25 | 3 | [] | no_license | // social distance
#include <iostream>
#include <set>
#include <vector>
#include <string>
using namespace std;
struct Seg{
int left,right;
Seg(int l, int r):left(l),right(r){}
};
struct mycomp{
bool operator() (const Seg& lhs, const Seg& rhs) const
{
int ll = (lhs.right-lhs.left)/2;
int rl = (rhs.right-rhs.left)/2;
if(ll != rl)
return ll > rl; // bigger length is better
else return lhs.left < rhs.left; // smaller seat number is better
}
};
int main()
{
// set to store seg
// array to store student pos
// set to store now occupied seats
// need to redefine compare function of set
set<Seg,mycomp> ss;
vector<int> student;
set<int> seat;
// n seats, m students, 2m op
// s for strict min distance
// dis for distance
int n, m, s, dis;
cin >> n >> m >> s;
// initialize
student.resize(m+1,-1);
dis = n+1;
ss.insert( Seg(0,n+1) ); //!!
seat.insert(0);
seat.insert(n+1);
for(int i = 1; i <= 2*m; i ++){
string temp;
int id;
cin >> temp >> id;
if( temp == "i"){
// find best seg, which is in the begin of set
// find best pos within given seg
auto cur = ss.begin();
int left = cur->left;
int right = cur->right;
int pos = (left+right)/2;
//update dis !!
if(left != 0)
dis = min(pos-left,dis);
if(right != n+1)
dis = min(right-pos,dis);
// spilt seg
ss.insert(Seg(left,pos));
ss.insert(Seg(pos,right));
ss.erase(cur);
// put student into that pos
student[id] = pos;
seat.insert(pos);
}
else {
// find his seat
// merge seat
int pos = student[id];
auto cur = seat.find(pos);
auto l = cur;
auto k = cur;
int left_seat = *(--l);
int right_seat = *(++k);
ss.erase( Seg(left_seat,pos));
ss.erase( Seg(pos,right_seat));
ss.insert( Seg(left_seat,right_seat));
// record student&seat
student[id] = -1;
seat.erase(pos);
}
}
if(dis >= s) cout << "YES\n";
else cout << "NO\n";
if(dis == n+1) cout << "INF\n";
else cout << dis << endl;
return 0;
} | true |
000efd937eeb40b3c7f89646008cdaf72992f1c2 | C++ | mjww3/codeforces | /equivalentstrings.cpp | UTF-8 | 703 | 2.640625 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <math.h>
#include <list>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s1;
string s2;
cin>>s1;
cin>>s2;
string a1,a2,b1,b2;
for(int i=0;i<s1.length()/2;i++)
{
a1 = a1+s1[i];
}
for(int i=0;i<s1.length()/2;i++)
{
b1 = b1+s2[i];
}
for(int i=s1.length()/2;i<s1.length();i++)
{
a2 = a2+s1[i];
}
for(int i=s1.length()/2;i<s1.length();i++)
{
b2 = b2+s2[i];
}
sort(a1.begin(),a1.end());
sort(a2.begin(),a2.end());
sort(b1.begin(),b1.end());
sort(b2.begin(),b2.end());
if((a1==b1 && a2==b2)||(a1==b2 && a2==b1))
{
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
} | true |
25bfd4cfa19b5f95e45946bc5939959c0ef1f51c | C++ | zinsmatt/Programming | /LeetCode/medium/Find_All_Anagrams_in_a_String_II.cxx | UTF-8 | 738 | 2.796875 | 3 | [] | no_license | class Solution {
void print(vector<int>& v)
{
for (auto x : v)
cout << x << " ";
cout << "\n";
}
public:
vector<int> findAnagrams(string s, string p) {
vector<int> ref(26, 0);
for (auto c : p)
++ref[c-'a'];
vector<int> res;
vector<int> cur(26, 0);
for (int i = 0; i < p.size() && i < s.size(); ++i) {
++cur[s[i]-'a'];
}
if (cur == ref)
res.push_back(0);
int i = 0;
while (i + p.size() < s.size()) {
--cur[s[i] - 'a'];
++cur[s[i+p.size()] - 'a'];
++i;
if (cur == ref)
res.push_back(i);
}
return res;
}
};
| true |
2648e37e1edb36a74500f53819a2fdf6169da8bc | C++ | SolarAA-11/practice | /src/leetcode/leetcode-0044/0044-210420.cpp | UTF-8 | 1,171 | 2.8125 | 3 | [] | no_license |
#include "common.h"
class Solution {
private:
string s, p;
vector<vector<int>> m;
bool dfs(int l1, int l2) {
if (m[l1][l2] != -1) return m[l1][l2];
int& mc = m[l1][l2];
if (l1 == 0 && l2 == 0) return mc = 1;
else if (l1 == 0) return mc = p[l2 - 1] == '*' ? dfs(l1, l2 - 1) : 0;
else if (l2 == 0) return mc = 0;
else {
if (p[l2 - 1] == '?') return mc = dfs(l1 - 1, l2 - 1);
else if (p[l2 - 1] == '*') {
for (int i = l1; i >= 0; --i)
if (dfs(i, l2 - 1)) return mc = 1;
return mc = 0;
} else return mc = s[l1 - 1] == p[l2 - 1] && dfs(l1 - 1, l2 - 1);
}
}
public:
bool isMatch(string ss, string pp) {
s = move(ss), p = move(pp);
m.assign(s.size() + 1, vector<int>(p.size() + 1, -1));
return dfs(s.size(), p.size());
}
};
int main() {
Solution s;
cout << s.isMatch("bbbababbabbbbabbbbaabaaabbbbabbbababbbbababaabbbab",
"a******b*");
vector<vector<int>> vvi(10, vector<int>(10, 10));
int& p = vvi[5][5];
p = 10000;
cout << vvi[5][5] << endl;
}
| true |
cea5c0cb50ff9b7ae3dbbc002f3d53c7948b85eb | C++ | DoroGi/exercises | /cracking_the_coding_interview/4-Trees_and_Graphs/4.1-RouteBetweenNodes/routeBetweenNodes.cpp | UTF-8 | 1,589 | 3.5625 | 4 | [] | no_license | #include <vector>
#include <queue>
#include <iostream>
#include "../../data_structures/2-Trees_Tries_Graphs/Graph/Graph.hpp"
bool routeBetweenNodes(node<char>* start, node<char>* target)
{
std::queue<node<char>*> q;
start->marked = true;
q.push(start);
while (!q.empty())
{
node<char>* current = q.front();
q.pop();
current->marked = true;
for (node<char>* adjacent : current->children)
{
if (adjacent == target) return true;
if (!adjacent->marked)
{
adjacent->marked = true;
q.push(adjacent);
}
}
}
return false;
}
int main ()
{
node<char> node1 = node<char>('a');
node<char> node2 = node<char>('b');
node<char> node3 = node<char>('c');
node<char> node4 = node<char>('d');
node<char> node5 = node<char>('e');
node<char> node6 = node<char>('f');
node1.children.push_back(&node2);
node1.children.push_back(&node3);
node1.children.push_back(&node4);
node2.children.push_back(&node1);
node2.children.push_back(&node3);
node2.children.push_back(&node4);
node4.children.push_back(&node5);
node5.children.push_back(&node4);
bool firstAndFifthAreConnected = routeBetweenNodes(&node1, &node5);
bool firstAndSixthAreConnected = routeBetweenNodes(&node1, &node6);
std::cout << (firstAndFifthAreConnected ? "yes" : "no") << std::endl;
std::cout << (firstAndSixthAreConnected ? "yes" : "no") << std::endl;
return 0;
} | true |
bf6cb080e0b29af3f1063909a9e29cdd275a6c41 | C++ | damorim/model-checking-tutorial | /jbmc/ipasir/sat/sat4j235/ipasirsat4jglue.cpp | UTF-8 | 4,747 | 2.84375 | 3 | [
"MIT"
] | permissive | /** @author Tomas Balyo, KIT, Karlsruhe */
#include <jni.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
extern "C" {
#include "ipasir.h"
}
struct SolverData {
int id;
void* callbackState;
int(*callbackFunction)(void*);
pthread_t thread;
};
JavaVM *vm = NULL;
jclass clazz;
jmethodID init;
jmethodID reset;
jmethodID add;
jmethodID assume;
jmethodID solve;
jmethodID val;
jmethodID failed;
jmethodID interrupt;
JNIEnv* initializeJavaConnection() {
JNIEnv *env;
JavaVMOption options[1];
char classpath[] = "-Djava.class.path=org.sat4j.core.jar:.";
options[0].optionString = classpath;
JavaVMInitArgs vm_args;
vm_args.version = JNI_VERSION_1_2;
vm_args.ignoreUnrecognized = 1;
vm_args.nOptions = 1;
vm_args.options = options;
// Construct a VM
JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
// Get the class that contains the methods
clazz = env->FindClass("Sat4jIpasir");
if (clazz == NULL) {
printf("ERROR: jni initialization failed, class 'Sat4jIpasir' not found.\n");
return NULL;
}
// Get the method IDs
init = env->GetStaticMethodID(clazz, "initSolver", "()I");
reset = env->GetStaticMethodID(clazz, "reset", "(I)V");
add = env->GetStaticMethodID(clazz, "add", "(II)V");
assume = env->GetStaticMethodID(clazz, "assume", "(II)V");
solve = env->GetStaticMethodID(clazz, "solve", "(I)I");
val = env->GetStaticMethodID(clazz, "val", "(II)I");
failed = env->GetStaticMethodID(clazz, "failed", "(II)I");
interrupt = env->GetStaticMethodID(clazz, "terminate", "(I)V");
if (init == NULL || reset == NULL || add == NULL || assume == NULL
|| solve == NULL || val == NULL || failed == NULL || interrupt == NULL) {
printf("ERROR: jni initialization failed, method not found.\n");
}
return env;
//vm->DestroyJavaVM();
}
JNIEnv* getEnv() {
JNIEnv *env = NULL;
if (vm == NULL) {
env = initializeJavaConnection();
} else {
jint res = vm->GetEnv((void**)&env, JNI_VERSION_1_2);
if (res == JNI_EDETACHED) {
vm->AttachCurrentThread((void**)&env, NULL);
}
}
return env;
}
/**
* Return the name and the version of the solver
*/
const char * ipasir_signature () {
return "Sat4j-2.3.5.";
}
/**
* Construct a new solver and return a pointer to it
*/
void * ipasir_init () {
JNIEnv *env = getEnv();
jint result = env->CallStaticIntMethod(clazz, init);
SolverData* sd = (SolverData*)malloc(sizeof(SolverData));
sd->id = (int)result;
sd->callbackFunction = NULL;
sd->callbackState = NULL;
return sd;
}
/**
* Release all the allocated memory (destructor)
*/
void ipasir_release (void * solver) {
SolverData* sd = (SolverData*)solver;
jint id = sd->id;
getEnv()->CallStaticVoidMethod(clazz, reset, id);
free(sd);
}
/**
* Add literal into the currently added clause or finalize the clause with 0
*/
void ipasir_add (void * solver, int lit) {
SolverData* sd = (SolverData*)solver;
getEnv()->CallStaticVoidMethod(clazz, add, sd->id, lit);
}
/**
* Add an assumption for solving
*/
void ipasir_assume (void * solver, int lit) {
SolverData* sd = (SolverData*)solver;
getEnv()->CallStaticVoidMethod(clazz, assume, sd->id, lit);
}
/**
* Get the truth value of the given literal.
* Return 'lit' if True, '-lit' if False, and 0 if not important
*/
int ipasir_val (void * solver, int lit) {
SolverData* sd = (SolverData*)solver;
jint result = getEnv()->CallStaticIntMethod(clazz, val, sd->id, lit);
return result;
}
/**
* Check if the given assumption literal has failed.
* Return 1 if failed, 0 otherwise.
*/
int ipasir_failed (void * solver, int lit) {
SolverData* sd = (SolverData*)solver;
jint result = getEnv()->CallStaticIntMethod(clazz, failed, sd->id, lit);
return result;
}
void * terminateCheckThread(void * solver) {
SolverData* sd = (SolverData*)solver;
while (true) {
usleep(100*1000); //100 miliseconds
if (sd->callbackFunction(sd->callbackState)) {
getEnv()->CallStaticVoidMethod(clazz, interrupt, sd->id);
}
}
return NULL;
}
/**
* Solve the formula with specified clauses under the specified assumptions.
* Returns 10 for SAT, 20 for UNSAT, and 0 for INDETERMINATE
*/
int ipasir_solve (void * solver) {
SolverData* sd = (SolverData*)solver;
if (sd->callbackFunction != NULL) {
pthread_create(&(sd->thread), NULL, terminateCheckThread, sd);
}
jint result = getEnv()->CallStaticIntMethod(clazz, solve, sd->id);
if (sd->callbackFunction != NULL) {
pthread_cancel(sd->thread);
}
return result;
}
void ipasir_set_terminate (void * solver, void * state, int (*terminate)(void * state)) {
SolverData* sd = (SolverData*)solver;
sd->callbackFunction = terminate;
sd->callbackState = state;
}
| true |
0b2ed6c7c7c0950d932fe204257164b2a13abece | C++ | xiaohuanlin/Algorithms | /Leetcode/954. Array of Doubled Pairs.cpp | UTF-8 | 1,745 | 3.59375 | 4 | [] | no_license | #include <vector>
#include <unordered_map>
#include <set>
#include <algorithm>
#include <iostream>
#include <tuple>
#include <assert.h>
using namespace std;
// Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise.
// Example 1:
// Input: arr = [3,1,3,6]
// Output: false
// Example 2:
// Input: arr = [2,1,2,6]
// Output: false
// Example 3:
// Input: arr = [4,-2,2,-4]
// Output: true
// Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4].
// Example 4:
// Input: arr = [1,2,4,16,8,4]
// Output: false
// Constraints:
// 2 <= arr.length <= 3 * 10^4
// arr.length is even.
// -105 <= arr[i] <= 10^5
class Solution {
public:
bool canReorderDoubled(vector<int>& arr) {
sort(arr.begin(), arr.end(), [] (int a, int b) {
return abs(a) < abs(b);
});
unordered_map<int, int> counts;
for (auto& num: arr) {
counts[num]++;
}
for (auto& num: arr) {
if (counts[num] == 0) {
continue;
}
counts[num]--;
counts[2 * num]--;
if (counts[2 * num] < 0) {
return false;
}
}
return true;
}
};
int main() {
Solution s;
vector<tuple<vector<int>, bool>> test_cases {
{{3,1,3,6}, false},
{{0,1,3,0}, false},
{{0,1,2,0}, true},
{{2,1,2,6}, false},
{{4,-2,2,-4}, true},
{{1,2,4,16,8,4}, false},
};
for (auto& test_case: test_cases) {
assert(s.canReorderDoubled(get<0>(test_case)) == get<1>(test_case));
}
} | true |
dde284d24c347524f7e2da2f3010bfebd49e553f | C++ | kexincoding/leetcode | /E556 Next Greater Element III.cpp | UTF-8 | 953 | 2.9375 | 3 | [] | no_license | class Solution
{
public:
int nextGreaterElement(int n)
{
string num=to_string(n);
int len=num.size(),m=100,p,t,flag=0,i,j;
if(len==0||len==1)
return -1;
for(i=len-2; i>=0; i--)
{
for( j=i+1; j<len; j++)
{
if(num[i]<num[j])
{
t=num[j]-num[i];
if(t<m)
{
m=t;
p=j;
flag=1;
}
}
}
if(flag==1)
break;
}
if(flag==0)
return -1;
swap(num[i],num[p]);
sort(num.begin()+(i+1),num.end());
if(len>9&&num[0]>2)
return -1;
int ans=0;
for(i=0; i<len; i++)
ans=ans*10+(num[i]-'0');
return ans;
}
};
| true |
6d89f44b2985bde2abe38160db8d054f0913e2a6 | C++ | markus2121212/Hospital | /Doctor.cpp | UTF-8 | 707 | 3.265625 | 3 | [] | no_license | #include "Doctor.h"
#include <iostream>
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS
Doctor::Doctor(string _name, string _surname, int _age, char _sex)
: Worker(_name, _surname, _age, _sex)
{
}
void Doctor::set_salary()
{
cout << "\nLosuje pensje" << endl;
int _salary = (rand() % 20);
cout << "Wylosowana pensja: " << _salary << endl;
salary = _salary;
}
void Doctor::display()
{
cout << endl;
cout << "Imie: " << name << " Nazwisko: " << surname << " Wiek: " << age << " Plec: " << sex << " Wylosowana pensja: " << salary << endl;
cout << endl;
}
| true |
57be390c88616b92d38065e850169183be53c0f1 | C++ | jasoncustodio/Coursework | /Coursework/C++/Data Structures/HW5/table.h | UTF-8 | 2,289 | 3.59375 | 4 | [] | no_license | /*
Program: Graph
Author: Jason Custodio
Class: CS163
Date: 03/20/2014
Description: This program will simulates a quiz for computers
A list of vertices are used with edges that connect to adjacent vertices
The vertices and edges are loaded from an external file
Each node node holds an answer, a pointer to the next node, and index
The vertices hold a question, a visit flag, and a head pointer to a LLL
*/
#include <iostream>
#include <cstring>
#include <cctype>
#include <fstream>
const int SIZE = 100; //Used to create arrays in main function
const int MAX = 5;
using namespace std;
//Used to hold index/answers for vertex
struct node
{
char * answer; //Answer to question
int index; //Index of adjacent vertex
node * next; //Pointer to next adjacent vertex
};
//Holds questions and edge list
struct vertex
{
char * question; //Quiz question
int visit; //Visit flag, 0=false, 1=true
node * head; //Edge list
};
//Graph of quiz questions
class table
{
public:
table(); //Constructor sets root to NULL
~table(); //Calls destructor
int displayEdge(int);
int takeQuiz(int);
int displayVertex(int); //Wrapper function for displayVertex
int displayQuiz(); //Wrapper function for in depth
int insertVertex(char[]); //Wrapper function for insert
int insertEdge(char[], int, int); //Wrapper function for insert
int traverse(int);
void reset();
void load(char[], char[]); //Load courses from external file
private:
vertex * list; //Vertex pointer to adjacency list
int num; //Number of vertices
int displayVertex(node*&); //Displays vertex
// int displayQuiz(node*&); //Displays using in depth traversal
int insertVertex(char*, char[]); //Inserts Vertex
int insertEdge(node*&, char[], int); //Inserts edge
};
| true |
1cebeafa6f539582164085069c2c54cf73bcd144 | C++ | katzeforest/Computer-Animation | /Curve Editor Framework/CurveEditor/svzalgebra.cpp | UTF-8 | 45,349 | 2.8125 | 3 | [] | no_license | /* -------------------------------------------------------------------------
* SvzAlgebra.h -- Basic algebra source file
* --------------------------------------------------------------------------
* Copyright (c) 1995 - 2011 Sovoz Inc. All Rights Reserved
* --------------------------------------------------------------------------
* Liming Zhao, Stephen Lane
*/
#include <SvzAlgebra.h>
//
// Implementation
//
/****************************************************************
* *
* vec2 Member functions *
* *
****************************************************************/
// CONSTRUCTORS
vec2::vec2()
{
}
vec2::vec2(const Real x, const Real y)
{
n[vx] = x; n[vy] = y;
}
vec2::vec2(const Real d)
{
n[vx] = n[vy] = d;
}
vec2::vec2(const vec2& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy];
}
vec2::vec2(const vec3& v) // it is up to caller to avoid divide-by-zero
{
n[vx] = v.n[vx]/v.n[vz]; n[vy] = v.n[vy]/v.n[vz];
};
vec2::vec2(const vec3& v, int dropAxis) {
switch (dropAxis) {
case vx: n[vx] = v.n[vy]; n[vy] = v.n[vz]; break;
case vy: n[vx] = v.n[vx]; n[vy] = v.n[vz]; break;
default: n[vx] = v.n[vx]; n[vy] = v.n[vy]; break;
}
}
// ASSIGNMENT OPERATORS
vec2& vec2::operator = (const vec2& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; return *this;
}
vec2& vec2::operator += ( const vec2& v )
{
n[vx] += v.n[vx]; n[vy] += v.n[vy]; return *this;
}
vec2& vec2::operator -= ( const vec2& v )
{
n[vx] -= v.n[vx]; n[vy] -= v.n[vy]; return *this;
}
vec2& vec2::operator *= ( const Real d )
{
n[vx] *= d; n[vy] *= d; return *this;
}
vec2& vec2::operator /= ( const Real d )
{
Real d_inv = 1./d; n[vx] *= d_inv; n[vy] *= d_inv; return *this;
}
Real& vec2::operator [] ( int i)
{
assert(!(i < vx || i > vy)); // subscript check
return n[i];
}
Real vec2::operator [] ( int i) const
{
assert(!(i < vx || i > vy));
return n[i];
}
// SPECIAL FUNCTIONS
Real vec2::Length() const
{
return sqrt(Length2());
}
Real vec2::Length2() const
{
return n[vx]*n[vx] + n[vy]*n[vy];
}
vec2& vec2::Normalize() // it is up to caller to avoid divide-by-zero
{
//*this /= Length(); return *this;
Real norm = Length();
if (norm < EPSILON)
return *this = vec2(1.0f, 0.0f);
else return *this /= norm;
}
vec2& vec2::apply(Svz_V_FCT_PTR fct)
{
n[vx] = (*fct)(n[vx]); n[vy] = (*fct)(n[vy]); return *this;
}
int vec2::dim() const // SHL added - returns dimension of vector
{
return (sizeof(n)/sizeof(Real));
}
// FRIENDS
vec2 operator - (const vec2& a)
{
return vec2(-a.n[vx],-a.n[vy]);
}
vec2 operator + (const vec2& a, const vec2& b)
{
return vec2(a.n[vx]+ b.n[vx], a.n[vy] + b.n[vy]);
}
vec2 operator - (const vec2& a, const vec2& b)
{
return vec2(a.n[vx]-b.n[vx], a.n[vy]-b.n[vy]);
}
vec2 operator * (const vec2& a, const Real d)
{
return vec2(d*a.n[vx], d*a.n[vy]);
}
vec2 operator * (const Real d, const vec2& a)
{
return a*d;
}
vec2 operator * (const mat3& a, const vec2& v)
{
vec3 av;
av.n[vx] = a.v[0].n[vx]*v.n[vx] + a.v[0].n[vy]*v.n[vy] + a.v[0].n[vz];
av.n[vy] = a.v[1].n[vx]*v.n[vx] + a.v[1].n[vy]*v.n[vy] + a.v[1].n[vz];
av.n[vz] = a.v[2].n[vx]*v.n[vx] + a.v[2].n[vy]*v.n[vy] + a.v[2].n[vz];
return av;
}
vec2 operator * (const vec2& v, const mat3& a)
{
return a.transpose() * v;
}
Real operator * (const vec2& a, const vec2& b)
{
return (a.n[vx]*b.n[vx] + a.n[vy]*b.n[vy]);
}
vec2 operator / (const vec2& a, const Real d)
{
Real d_inv = 1./d; return vec2(a.n[vx]*d_inv, a.n[vy]*d_inv);
}
vec3 operator ^ (const vec2& a, const vec2& b)
{
return vec3(0.0, 0.0, a.n[vx] * b.n[vy] - b.n[vx] * a.n[vy]);
}
int operator == (const vec2& a, const vec2& b)
{
return (a.n[vx] == b.n[vx]) && (a.n[vy] == b.n[vy]);
}
int operator != (const vec2& a, const vec2& b)
{
return !(a == b);
}
#ifdef ALGEBRAIOSTREAMS
ostream& operator << (ostream& s, const vec2& v)
{
return s << "[ " << v.n[vx] << ' ' << v.n[vy] << " ]";
}
// istream& operator >> (istream& s, vec2& v)
//{
// vec2 v_tmp;
// char c = ' ';
//
// while (isspace(c))
// s >> c;
// // The vectors can be formatted either as x y or | x y |
// if (c == '[') {
// s >> v_tmp[vx] >> v_tmp[vy];
// while (s >> c && isspace(c)) ;
// if (c != ']')
// s.set(_bad);
// }
// else {
// s.putback(c);
// s >> v_tmp[vx] >> v_tmp[vy];
// }
// if (s)
// v = v_tmp;
// return s;
//}
#endif // ALGEBRAIOSTREAMS
void swap(vec2& a, vec2& b)
{
vec2 tmp(a); a = b; b = tmp;
}
vec2 min(const vec2& a, const vec2& b)
{
return vec2(MIN(a.n[vx], b.n[vx]), MIN(a.n[vy], b.n[vy]));
}
vec2 max(const vec2& a, const vec2& b)
{
return vec2(MAX(a.n[vx], b.n[vx]), MAX(a.n[vy], b.n[vy]));
}
vec2 prod(const vec2& a, const vec2& b)
{
return vec2(a.n[vx] * b.n[vx], a.n[vy] * b.n[vy]);
}
/****************************************************************
* *
* vec3 Member functions *
* *
****************************************************************/
// CONSTRUCTORS
vec3::vec3()
{
}
vec3::vec3(const Real x, const Real y, const Real z)
{
n[vx] = x; n[vy] = y; n[vz] = z;
}
vec3::vec3(const Real d)
{
n[vx] = n[vy] = n[vz] = d;
}
vec3::vec3(const vec3& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz];
}
vec3::vec3(const vec2& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = 1.0;
}
vec3::vec3(const vec2& v, Real d)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = d;
}
vec3::vec3(const vec4& v) // it is up to caller to avoid divide-by-zero
{
n[vx] = v.n[vx] / v.n[vw];
n[vy] = v.n[vy] / v.n[vw];
n[vz] = v.n[vz] / v.n[vw];
}
vec3::vec3(const quat& q) // cast quat to v3 //*** SHL added 11/25/10
{
}
vec3::vec3(const vec4& v, int dropAxis)
{
switch (dropAxis) {
case vx: n[vx] = v.n[vy]; n[vy] = v.n[vz]; n[vz] = v.n[vw]; break;
case vy: n[vx] = v.n[vx]; n[vy] = v.n[vz]; n[vz] = v.n[vw]; break;
case vz: n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vw]; break;
default: n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; break;
}
}
// ASSIGNMENT OPERATORS
vec3& vec3::operator = (const vec3& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; return *this;
}
vec3& vec3::operator += ( const vec3& v )
{
n[vx] += v.n[vx]; n[vy] += v.n[vy]; n[vz] += v.n[vz]; return *this;
}
vec3& vec3::operator -= ( const vec3& v )
{
n[vx] -= v.n[vx]; n[vy] -= v.n[vy]; n[vz] -= v.n[vz]; return *this;
}
vec3& vec3::operator *= ( const Real d )
{
n[vx] *= d; n[vy] *= d; n[vz] *= d; return *this;
}
vec3& vec3::operator /= ( const Real d )
{
Real d_inv = 1./d; n[vx] *= d_inv; n[vy] *= d_inv; n[vz] *= d_inv;
return *this;
}
Real& vec3::operator [] ( int i) {
assert(! (i < vx || i > vz));
return n[i];
}
Real vec3::operator [] ( int i) const {
assert(! (i < vx || i > vz));
return n[i];
}
// SPECIAL FUNCTIONS
Real vec3::Length() const
{
return sqrt(Length2());
}
Real vec3::Length2() const
{
return n[vx]*n[vx] + n[vy]*n[vy] + n[vz]*n[vz];
}
vec3& vec3::Normalize() // it is up to caller to avoid divide-by-zero
{
Real norm = Length();
if (norm == 0.0)
return *this = vec3(1.0f, 0.0f, 0.0f);
else return *this /= (double) norm;
}
vec3& vec3::apply(Svz_V_FCT_PTR fct)
{
n[vx] = (*fct)(n[vx]); n[vy] = (*fct)(n[vy]); n[vz] = (*fct)(n[vz]);
return *this;
}
vec3 vec3::Cross(vec3 &v) const
{
vec3 tmp;
tmp[0] = n[1] * v.n[2] - n[2] * v.n[1];
tmp[1] = n[2] * v.n[0] - n[0] * v.n[2];
tmp[2] = n[0] * v.n[1] - n[1] * v.n[0];
return tmp;
}
int vec3::dim() const // SHL added - returns dimension of vector
{
return (sizeof(n)/sizeof(Real));
}
Real* vec3::getn()
{
return n;
}
// FRIENDS
vec3 operator - (const vec3& a)
{
return vec3(-a.n[vx],-a.n[vy],-a.n[vz]);
}
vec3 operator + (const vec3& a, const vec3& b)
{
return vec3(a.n[vx]+ b.n[vx], a.n[vy] + b.n[vy], a.n[vz] + b.n[vz]);
}
vec3 operator - (const vec3& a, const vec3& b)
{
return vec3(a.n[vx]-b.n[vx], a.n[vy]-b.n[vy], a.n[vz]-b.n[vz]);
}
vec3 operator * (const vec3& a, const Real d)
{
return vec3(d*a.n[vx], d*a.n[vy], d*a.n[vz]);
}
vec3 operator * (const Real d, const vec3& a)
{
return a*d;
}
vec3 operator * (const mat3& a, const vec3& v)
{
#define ROWCOL(i) a.v[i].n[0]*v.n[vx] + a.v[i].n[1]*v.n[vy] \
+ a.v[i].n[2]*v.n[vz]
return vec3(ROWCOL(0), ROWCOL(1), ROWCOL(2));
#undef ROWCOL // (i)
}
vec3 operator * (const mat4& a, const vec3& v)
{
return a * vec4(v);
}
vec3 operator * (const vec3& v, const mat4& a)
{
return a.transpose() * v;
}
Real operator * (const vec3& a, const vec3& b)
{
return (a.n[vx]*b.n[vx] + a.n[vy]*b.n[vy] + a.n[vz]*b.n[vz]);
}
vec3 operator / (const vec3& a, const Real d)
{
Real d_inv = 1./d;
return vec3(a.n[vx]*d_inv, a.n[vy]*d_inv, a.n[vz]*d_inv);
}
vec3 operator ^ (const vec3& a, const vec3& b)
{
return vec3(a.n[vy]*b.n[vz] - a.n[vz]*b.n[vy],
a.n[vz]*b.n[vx] - a.n[vx]*b.n[vz],
a.n[vx]*b.n[vy] - a.n[vy]*b.n[vx]);
}
int operator == (const vec3& a, const vec3& b)
{
return (a.n[vx] == b.n[vx]) && (a.n[vy] == b.n[vy]) && (a.n[vz] == b.n[vz]);
}
int operator != (const vec3& a, const vec3& b)
{
return !(a == b); }
#ifdef ALGEBRAIOSTREAMS
//ostream& operator << (ostream& s, const vec3& v)
//{
// return s << "[ " << v.n[vx] << ' ' << v.n[vy] << ' ' << v.n[vz] << " ]";
//}
ostream& operator << (ostream& s, const vec3& v)
{
return s << v[0] << "\t" << v[1] << "\t" << v[2];
}
istream& operator >> (istream& s, vec3& v)
{
vec3 v_tmp;
s >> v_tmp[0] >> v_tmp[1] >> v_tmp[2];
if (s)
v = v_tmp;
return s;
}
// istream& operator >> (istream& s, vec3& v)
//{
// vec3 v_tmp;
// char c = ' ';
//
// while (isspace(c))
// s >> c;
// // The vectors can be formatted either as x y z or | x y z |
// if (c == '[') {
// s >> v_tmp[vx] >> v_tmp[vy] >> v_tmp[vz];
// while (s >> c && isspace(c)) ;
// if (c != ']')
// s.set(_bad);
// }
// else {
// s.putback(c);
// s >> v_tmp[vx] >> v_tmp[vy] >> v_tmp[vz];
// }
// if (s)
// v = v_tmp;
// return s;
//}
#endif // ALGEBRAIOSTREAMS
void swap(vec3& a, vec3& b)
{
vec3 tmp(a); a = b; b = tmp;
}
vec3 min(const vec3& a, const vec3& b)
{
return vec3(MIN(a.n[vx], b.n[vx]), MIN(a.n[vy], b.n[vy]), MIN(a.n[vz], b.n[vz]));
}
vec3 max(const vec3& a, const vec3& b)
{
return vec3(MAX(a.n[vx], b.n[vx]), MAX(a.n[vy], b.n[vy]), MAX(a.n[vz], b.n[vz]));
}
vec3 prod(const vec3& a, const vec3& b)
{
return vec3(a.n[vx] * b.n[vx], a.n[vy] * b.n[vy], a.n[vz] * b.n[vz]);
}
/****************************************************************
* *
* vec4 Member functions *
* *
****************************************************************/
// CONSTRUCTORS
vec4::vec4()
{
}
vec4::vec4(const Real x, const Real y, const Real z, const Real w)
{
n[vx] = x; n[vy] = y; n[vz] = z; n[vw] = w;
}
vec4::vec4(const Real d)
{
n[vx] = n[vy] = n[vz] = n[vw] = d;
}
vec4::vec4(const vec4& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; n[vw] = v.n[vw];
}
vec4::vec4(const vec3& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; n[vw] = 1.0;
}
vec4::vec4(const vec3& v, const Real d)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; n[vw] = d;
}
// ASSIGNMENT OPERATORS
vec4& vec4::operator = (const vec4& v)
{
n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz]; n[vw] = v.n[vw];
return *this;
}
vec4& vec4::operator += ( const vec4& v )
{
n[vx] += v.n[vx]; n[vy] += v.n[vy]; n[vz] += v.n[vz]; n[vw] += v.n[vw];
return *this;
}
vec4& vec4::operator -= ( const vec4& v )
{
n[vx] -= v.n[vx]; n[vy] -= v.n[vy]; n[vz] -= v.n[vz]; n[vw] -= v.n[vw];
return *this;
}
vec4& vec4::operator *= ( const Real d )
{
n[vx] *= d; n[vy] *= d; n[vz] *= d; n[vw] *= d;
return *this;
}
vec4& vec4::operator /= ( const Real d )
{
Real d_inv = 1./d;
n[vx] *= d_inv; n[vy] *= d_inv; n[vz] *= d_inv; n[vw] *= d_inv;
return *this;
}
Real& vec4::operator [] ( int i)
{
assert(! (i < vx || i > vw));
return n[i];
}
Real vec4::operator [] ( int i) const
{
assert(! (i < vx || i > vw));
return n[i];
}
// SPECIAL FUNCTIONS
Real vec4::Length() const
{
return sqrt(Length2());
}
Real vec4::Length2() const
{
return n[vx]*n[vx] + n[vy]*n[vy] + n[vz]*n[vz] + n[vw]*n[vw];
}
vec4& vec4::Normalize() // it is up to caller to avoid divide-by-zero
{
*this /= Length(); return *this;
}
vec4& vec4::apply(Svz_V_FCT_PTR fct)
{
n[vx] = (*fct)(n[vx]);
n[vy] = (*fct)(n[vy]);
n[vz] = (*fct)(n[vz]);
n[vw] = (*fct)(n[vw]);
return *this;
}
int vec4::dim() const // SHL added - returns dimension of vector
{
return (sizeof(n)/sizeof(Real));
}
// FRIENDS
vec4 operator - (const vec4& a)
{
return vec4(-a.n[vx],-a.n[vy],-a.n[vz],-a.n[vw]);
}
vec4 operator + (const vec4& a, const vec4& b)
{
return vec4(a.n[vx] + b.n[vx], a.n[vy] + b.n[vy], a.n[vz] + b.n[vz], a.n[vw] + b.n[vw]);
}
vec4 operator - (const vec4& a, const vec4& b)
{
return vec4(a.n[vx] - b.n[vx], a.n[vy] - b.n[vy], a.n[vz] - b.n[vz], a.n[vw] - b.n[vw]);
}
vec4 operator * (const vec4& a, const Real d)
{
return vec4(d*a.n[vx], d*a.n[vy], d*a.n[vz], d*a.n[vw] );
}
vec4 operator * (const Real d, const vec4& a)
{
return a*d;
}
vec4 operator * (const mat4& a, const vec4& v)
{
#define ROWCOL(i) a.v[i].n[0]*v.n[vx] + a.v[i].n[1]*v.n[vy] \
+ a.v[i].n[2]*v.n[vz] + a.v[i].n[3]*v.n[vw]
return vec4(ROWCOL(0), ROWCOL(1), ROWCOL(2), ROWCOL(3));
#undef ROWCOL // (i)
}
vec4 operator * (const vec4& v, const mat4& a)
{
return a.transpose() * v;
}
Real operator * (const vec4& a, const vec4& b)
{
return (a.n[vx]*b.n[vx] + a.n[vy]*b.n[vy] + a.n[vz]*b.n[vz] + a.n[vw]*b.n[vw]);
}
vec4 operator / (const vec4& a, const Real d)
{
Real d_inv = 1./d;
return vec4(a.n[vx]*d_inv, a.n[vy]*d_inv, a.n[vz]*d_inv, a.n[vw]*d_inv);
}
int operator == (const vec4& a, const vec4& b)
{
return (a.n[vx] == b.n[vx]) && (a.n[vy] == b.n[vy]) && (a.n[vz] == b.n[vz]) && (a.n[vw] == b.n[vw]);
}
int operator != (const vec4& a, const vec4& b)
{
return !(a == b);
}
#ifdef ALGEBRAIOSTREAMS
ostream& operator << (ostream& s, const vec4& v)
{
return s << "[ " << v.n[vx] << ' ' << v.n[vy] << ' ' << v.n[vz] << ' ' << v.n[vw] << " ]";
}
// stream& operator >> (istream& s, vec4& v)
//{
// vec4 v_tmp;
// char c = ' ';
//
// while (isspace(c))
// s >> c;
// // The vectors can be formatted either as x y z w or | x y z w |
// if (c == '[') {
// s >> v_tmp[vx] >> v_tmp[vy] >> v_tmp[vz] >> v_tmp[vw];
// while (s >> c && isspace(c)) ;
// if (c != ']')
// s.set(_bad);
// }
// else {
// s.putback(c);
// s >> v_tmp[vx] >> v_tmp[vy] >> v_tmp[vz] >> v_tmp[vw];
// }
// if (s)
// v = v_tmp;
// return s;
//}
#endif // ALGEBRAIOSTREAMS
void swap(vec4& a, vec4& b)
{
vec4 tmp(a); a = b; b = tmp;
}
vec4 min(const vec4& a, const vec4& b)
{
return vec4(MIN(a.n[vx], b.n[vx]), MIN(a.n[vy], b.n[vy]), MIN(a.n[vz], b.n[vz]), MIN(a.n[vw], b.n[vw]));
}
vec4 max(const vec4& a, const vec4& b)
{
return vec4(MAX(a.n[vx], b.n[vx]), MAX(a.n[vy], b.n[vy]), MAX(a.n[vz], b.n[vz]), MAX(a.n[vw], b.n[vw]));
}
vec4 prod(const vec4& a, const vec4& b)
{
return vec4(a.n[vx] * b.n[vx], a.n[vy] * b.n[vy], a.n[vz] * b.n[vz], a.n[vw] * b.n[vw]);
}
/****************************************************************
* *
* mat3 member functions *
* *
****************************************************************/
// CONSTRUCTORS
mat3::mat3()
{
v[0] = vec3(0.0,0.0,0.0);
v[1] = v[2] = v[0];
}
mat3::mat3(const vec3& v0, const vec3& v1, const vec3& v2)
{
v[0] = v0; v[1] = v1; v[2] = v2;
}
mat3::mat3(const Real d)
{
v[0] = v[1] = v[2] = vec3(d);
}
mat3::mat3(const mat3& m)
{
v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2];
}
mat3::mat3(const mat4& m){
v[0] = vec3(m[0][0], m[0][1], m[0][2]);
v[1] = vec3(m[1][0], m[1][1], m[1][2]);
v[2] = vec3(m[2][0], m[2][1], m[2][2]);
}
// Static functions
mat3 mat3::Identity()
{
return mat3(vec3(1.0, 0.0, 0.0),
vec3(0.0, 1.0, 0.0),
vec3(0.0, 0.0, 1.0));
}
mat3 mat3::Translation2D(const vec2& v)
{
return mat3(vec3(1.0, 0.0, v[vx]),
vec3(0.0, 1.0, v[vy]),
vec3(0.0, 0.0, 1.0));
}
mat3 mat3::Rotation2DDeg(const vec2& center, const Real angleDeg)
{
Real angleRad = angleDeg * Deg2Rad;
return Rotation2DRad(center, angleRad);
}
mat3 mat3::Rotation2DRad(const vec2& center, const Real angleRad)
{
Real c = cos(angleRad), s = sin(angleRad);
return mat3(vec3(c, -s, center[vx] * (1.0-c) + center[vy] * s),
vec3(s, c, center[vy] * (1.0-c) - center[vx] * s),
vec3(0.0, 0.0, 1.0));
}
mat3 mat3::Scaling2D(const vec2& scaleVector)
{
return mat3(vec3(scaleVector[vx], 0.0, 0.0),
vec3(0.0, scaleVector[vy], 0.0),
vec3(0.0, 0.0, 1.0));
}
mat3 mat3::Rotation3DDeg(const vec3& axis, const Real angleDeg)
{
Real angleRad = angleDeg * Deg2Rad;
return Rotation3DRad(axis, angleRad);
}
mat3 mat3::Rotation3DRad(const vec3& axis, const Real angleRad)
{
Real c = cos(angleRad), s = sin(angleRad), t = 1.0 - c;
vec3 Axis = axis;
Axis.Normalize();
return mat3(vec3(t * Axis[vx] * Axis[vx] + c,
t * Axis[vx] * Axis[vy] - s * Axis[vz],
t * Axis[vx] * Axis[vz] + s * Axis[vy]),
vec3(t * Axis[vx] * Axis[vy] + s * Axis[vz],
t * Axis[vy] * Axis[vy] + c,
t * Axis[vy] * Axis[vz] - s * Axis[vx]),
vec3(t * Axis[vx] * Axis[vz] - s * Axis[vy],
t * Axis[vy] * Axis[vz] + s * Axis[vx],
t * Axis[vz] * Axis[vz] + c)
);
}
mat3 mat3::Rotation3DDeg(const int Axis, const Real angleDeg)
{
Real angleRad = angleDeg * Deg2Rad;
return Rotation3DRad(Axis, angleRad);
}
mat3 mat3::Rotation3DRad(const int Axis, const Real angleRad)
{
vec3 axis;
switch(Axis)
{
case vx: axis = vec3(1.0, 0.0, 0.0);
break;
case vy: axis = vec3(0.0, 1.0, 0.0);
break;
case vz: axis = vec3(0.0, 0.0, 1.0);
break;
}
return Rotation3DRad(axis, angleRad);
}
mat3 mat3::Slerp(const mat3& rot0, const mat3& rot1, const Real& fPerc)
{
return mat3(0.0f);
}
mat3 mat3::Lerp(const mat3& rot0, const mat3& rot1, const Real& fPerc)
{
return mat3(0.0f);
}
// Rotation operations, matrix must be orthonomal
bool mat3::ToEulerAnglesXYZ(vec3& angleRad) const
{
return true;
}
bool mat3::ToEulerAnglesXZY(vec3& angleRad) const
{
return true;
}
bool mat3::ToEulerAnglesYXZ(vec3& angleRad) const
{
return true;
}
bool mat3::ToEulerAnglesYZX(vec3& angleRad) const
{
return true;
}
bool mat3::ToEulerAnglesZXY(vec3& angleRad) const
{
return true;
}
bool mat3::ToEulerAnglesZYX(vec3& angleRad) const
{
return true;
}
mat3 mat3::FromEulerAnglesXYZ(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
mat3 mat3::FromEulerAnglesXZY(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
mat3 mat3::FromEulerAnglesYXZ(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
mat3 mat3::FromEulerAnglesYZX(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
mat3 mat3::FromEulerAnglesZXY(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
mat3 mat3::FromEulerAnglesZYX(const vec3& angleRad)
{
*this = mat3(0.0f);
return *this;
}
bool mat3::reorthogonalize()
{
// Factor M = QR where Q is orthogonal and R is upper triangular.
// Algorithm uses Gram-Schmidt orthogonalization (the QR algorithm).
//
// If M = [ m0 | m1 | m2 ] and Q = [ q0 | q1 | q2 ], then
//
// q0 = m0/|m0|
// q1 = (m1-(q0*m1)q0)/|m1-(q0*m1)q0|
// q2 = (m2-(q0*m2)q0-(q1*m2)q1)/|m2-(q0*m2)q0-(q1*m2)q1|
//
// where |V| indicates length of vector V and A*B indicates dot
// product of vectors A and B. The matrix R has entries
//
// r00 = q0*m0 r01 = q0*m1 r02 = q0*m2
// r10 = 0 r11 = q1*m1 r12 = q1*m2
// r20 = 0 r21 = 0 r22 = q2*m2
//
// The reorthogonalization replaces current matrix by computed Q.
const Real fEpsilon = 1e-05f;
// unitize column 0
Real fLength = sqrt(v[0][0] * v[0][0] + v[1][0] * v[1][0] + v[2][0] * v[2][0]);
if ( fLength < fEpsilon )
return false;
Real fInvLength = 1.0f / fLength;
v[0][0] *= fInvLength;
v[1][0] *= fInvLength;
v[2][0] *= fInvLength;
// project out column 0 from column 1
Real fDot = v[0][0] * v[0][1] + v[1][0] * v[1][1] + v[2][0] * v[2][1];
v[0][1] -= fDot * v[0][0];
v[1][1] -= fDot * v[1][0];
v[2][1] -= fDot * v[2][0];
// unitize column 1
fLength = sqrt(v[0][1] * v[0][1] + v[1][1] * v[1][1] + v[2][1] * v[2][1]);
if ( fLength < fEpsilon )
return false;
fInvLength = 1.0f/fLength;
v[0][1] *= fInvLength;
v[1][1] *= fInvLength;
v[2][1] *= fInvLength;
// project out column 0 from column 2
fDot = v[0][0] * v[0][2] + v[1][0] * v[1][2] + v[2][0] * v[2][2];
v[0][2] -= fDot * v[0][0];
v[1][2] -= fDot * v[1][0];
v[2][2] -= fDot * v[2][0];
// project out column 1 from column 2
fDot = v[0][1] * v[0][2] + v[1][1] * v[1][2] + v[2][1] * v[2][2];
v[0][2] -= fDot * v[0][1];
v[1][2] -= fDot * v[1][1];
v[2][2] -= fDot * v[2][1];
// unitize column 2
fLength = sqrt(v[0][2] * v[0][2] + v[1][2] * v[1][2] + v[2][2] * v[2][2]);
if ( fLength < fEpsilon )
return false;
fInvLength = 1.0f / fLength;
v[0][2] *= fInvLength;
v[1][2] *= fInvLength;
v[2][2] *= fInvLength;
return true;
}
// Conversion with quat
quat mat3::ToQuaternion() const
{
return quat(0.0f);
}
void mat3::FromQuaternion(const quat& q)
{
}
void mat3::ToAxisAngle(vec3& axis, Real& angleRad) const
{
}
void mat3::ToAxisAngle2(vec3& axis, Real& angleRad) const
{
quat q = this->ToQuaternion();
//q.Normalize();
q.ToAxisAngle(axis, angleRad);
}
mat3 mat3::inverse() const // Gauss-Jordan elimination with partial pivoting
{
mat3 a(*this), // As a evolves from original mat into identity
b(mat3::Identity()); // b evolves from identity into inverse(a)
int i, j, i1;
// Loop over cols of a from left to right, eliminating above and below diag
for (j=0; j<3; j++) { // Find largest pivot in column j among rows j..2
i1 = j; // Row with largest pivot candidate
for (i=j+1; i<3; i++)
if (fabs(a.v[i].n[j]) > fabs(a.v[i1].n[j]))
i1 = i;
// Swap rows i1 and j in a and b to put pivot on diagonal
swap(a.v[i1], a.v[j]);
swap(b.v[i1], b.v[j]);
// Scale row j to have a unit diagonal
if (a.v[j].n[j]==0.)
ALGEBRA_ERROR("mat3::inverse: singular matrix; can't invert\n");
b.v[j] /= a.v[j].n[j];
a.v[j] /= a.v[j].n[j];
// Eliminate off-diagonal elems in col j of a, doing identical ops to b
for (i=0; i<3; i++)
if (i!=j)
{
b.v[i] -= a.v[i].n[j]*b.v[j];
a.v[i] -= a.v[i].n[j]*a.v[j];
}
}
return b;
}
void mat3::FromAxisAngle(const vec3& axis, const Real& angleRad)
{
*this = Rotation3DRad(axis, angleRad);
}
// ASSIGNMENT OPERATORS
mat3& mat3::operator = ( const mat3& m )
{
v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2];
return *this;
}
mat3& mat3::operator += ( const mat3& m )
{
v[0] += m.v[0]; v[1] += m.v[1]; v[2] += m.v[2];
return *this;
}
mat3& mat3::operator -= ( const mat3& m )
{
v[0] -= m.v[0]; v[1] -= m.v[1]; v[2] -= m.v[2];
return *this;
}
mat3& mat3::operator *= ( const Real d )
{
v[0] *= d; v[1] *= d; v[2] *= d;
return *this;
}
mat3& mat3::operator /= ( const Real d )
{
v[0] /= d; v[1] /= d; v[2] /= d;
return *this;
}
vec3& mat3::operator [] ( int i)
{
assert(! (i < vx || i > vz));
return v[i];
}
const vec3& mat3::operator [] ( int i) const
{
assert(!(i < vx || i > vz));
return v[i];
}
// SPECIAL FUNCTIONS
mat3 mat3::transpose() const
{
return mat3(vec3(v[0][0], v[1][0], v[2][0]),
vec3(v[0][1], v[1][1], v[2][1]),
vec3(v[0][2], v[1][2], v[2][2]));
}
mat3& mat3::apply(Svz_V_FCT_PTR fct)
{
v[vx].apply(fct);
v[vy].apply(fct);
v[vz].apply(fct);
return *this;
}
void mat3::getData(Real* d)
{
d[0] = v[0][0]; d[4] = v[0][1]; d[8] = v[0][2]; d[12] = 0;
d[1] = v[1][0]; d[5] = v[1][1]; d[9] = v[1][2]; d[13] = 0;
d[2] = v[2][0]; d[6] = v[2][1]; d[10] = v[2][2]; d[14] = 0;
d[3] = 0; d[7] = 0; d[11] = 0; d[15] = 1;
}
vec3 mat3::getRow(unsigned int axis) const
{
vec3 rowVec = v[axis];
return rowVec;
}
vec3 mat3::getCol(unsigned int axis) const
{
vec3 colVec;
colVec[0] = v[0][axis]; colVec[1] = v[1][axis]; colVec[2] = v[2][axis];
return colVec;
}
void mat3::setRow(unsigned int axis, const vec3& rowVec)
{
v[axis] = rowVec;
}
void mat3::setCol(unsigned int axis, const vec3& colVec)
{
v[0][axis] = colVec[0]; v[1][axis] = colVec[1]; v[2][axis] = colVec[2];
}
mat3 mat3::Normalize(int axis)
{
vec3 v0 = vec3(v[0][0],v[1][0],v[2][0]).Normalize();
vec3 v1 = vec3(v[0][1],v[1][1],v[2][1]).Normalize();
vec3 v2 = vec3(v[0][2],v[1][2],v[2][2]).Normalize();
if (axis == 0)
v0 = v1.Cross(v2);
else if (axis == 1)
v1 = v2.Cross(v0);
else if (axis == 2)
v2 = v0.Cross(v1);
else
assert(3==4);
return mat3(v0,v1,v2).transpose();
}
vec3 mat3::GetYawPitchRoll(unsigned int leftAxis, unsigned int upAxis, unsigned int frontAxis) const
{
// Assume world coordinates: Y up, X left, Z front.
vec3 leftVect, upVect, frontVect, dVect, angles, frontVect2, leftVect2;
Real t, value, x, y;
leftVect = getCol(leftAxis);
upVect = getCol(upAxis);
frontVect = getCol(frontAxis);
// Compute yaw angle
if (frontVect[vy] >= 0.0f && upVect[vy] >= 0.0f)
{
frontVect2 = frontVect;
dVect = -upVect - frontVect2;
}else if (frontVect[vy] < 0.0f && upVect[vy] < 0.0f)
{
frontVect2 = -frontVect;
dVect = upVect - frontVect2;
}else if (frontVect[vy] >= 0.0f && upVect[vy] < 0.0f)
{
frontVect2 = -frontVect;
dVect = -upVect - frontVect2;
}else if (frontVect[vy] < 0.0f && upVect[vy] >= 0.0f)
{
frontVect2 = frontVect;
dVect = upVect - frontVect2;
}
t = -frontVect2[vy] / dVect[vy];
x = frontVect2[vz] + t * dVect[vz];
y = frontVect2[vx] + t * dVect[vx];
angles[0] = atan2(y, x);
frontVect2 = vec3(y, 0.0f, x);
frontVect2.Normalize();
leftVect2 = vec3(0.0f, 1.0f, 0.0f);
leftVect2 = leftVect2.Cross(frontVect2);
// Compute pitch angle
Real dotProd = frontVect * frontVect2;
if(fabs(dotProd) > 1.0)
dotProd = (dotProd>0)?1.0:-1.0;
Real v = acos(dotProd);
if (frontVect[vy] >= 0.0f)
{
value = -v;
}else
{
value = v;
}
angles[1] = value;
// Compute roll angle
dotProd = leftVect * leftVect2;
if(fabs(dotProd) > 1.0)
dotProd = (dotProd>0)?1.0:-1.0;
v = acos(dotProd);
if (leftVect[vy] >= 0.0f)
{
value = -v;
}else
{
value = v;
}
angles[2] = value;
return angles;
}
//OpenGL Functions
void mat3::ToGLMatrix( Real* pData )
{
pData[0] = v[0][0]; pData[4] = v[0][1]; pData[8] = v[0][2]; pData[12] = 0.0f;
pData[1] = v[1][0]; pData[5] = v[1][1]; pData[9] = v[1][2]; pData[13] = 0.0f;
pData[2] = v[2][0]; pData[6] = v[2][1]; pData[10] = v[2][2]; pData[14] = 0.0f;
pData[3] = 0.0f; pData[7] = 0.0f; pData[11] = 0.0f; pData[15] = 1.0f;
}
void mat3::WriteToGLMatrix(Real* m)
{
m[0] = v[0][0]; m[4] = v[0][1]; m[8] = v[0][2]; m[12] = 0.0f;
m[1] = v[1][0]; m[5] = v[1][1]; m[9] = v[1][2]; m[13] = 0.0f;
m[2] = v[2][0]; m[6] = v[2][1]; m[10] = v[2][2]; m[14] = 0.0f;
m[3] = 0.0f; m[7] = 0.0f; m[11] = 0.0f; m[15] = 1.0f;
}
void mat3::ReadFromGLMatrix(Real* m)
{
v[0][0] = m[0]; v[0][1] = m[4]; v[0][2] = m[8];
v[1][0] = m[1]; v[1][1] = m[5]; v[1][2] = m[9];
v[2][0] = m[2]; v[2][1] = m[6]; v[2][2] = m[10];
}
// FRIENDS
mat3 operator - (const mat3& a)
{
return mat3(-a.v[0], -a.v[1], -a.v[2]);
}
mat3 operator + (const mat3& a, const mat3& b)
{
return mat3(a.v[0] + b.v[0], a.v[1] + b.v[1], a.v[2] + b.v[2]);
}
mat3 operator - (const mat3& a, const mat3& b)
{
return mat3(a.v[0] - b.v[0], a.v[1] - b.v[1], a.v[2] - b.v[2]);
}
mat3 operator * (const mat3& a, const mat3& b)
{
#define ROWCOL(i, j) \
a.v[i].n[0]*b.v[0][j] + a.v[i].n[1]*b.v[1][j] + a.v[i].n[2]*b.v[2][j]
return mat3(vec3(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2)),
vec3(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2)),
vec3(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2)));
#undef ROWCOL // (i, j)
}
mat3 operator * (const mat3& a, const Real d)
{
return mat3(a.v[0] * d, a.v[1] * d, a.v[2] * d);
}
mat3 operator * (const Real d, const mat3& a)
{
return a*d;
}
mat3 operator / (const mat3& a, const Real d)
{
return mat3(a.v[0] / d, a.v[1] / d, a.v[2] / d);
}
int operator == (const mat3& a, const mat3& b)
{
return (a.v[0] == b.v[0]) && (a.v[1] == b.v[1]) && (a.v[2] == b.v[2]);
}
int operator != (const mat3& a, const mat3& b)
{
return !(a == b);
}
#ifdef ALGEBRAIOSTREAMS
ostream& operator << (ostream& s, const mat3& m)
{
//return s << m.v[vx] << '\t' << m.v[vy] << '\t' << m.v[vz];
return s << m[0][0] << "\t" << m[0][1] << "\t" << m[0][2] << "\t"
<< m[1][0] << "\t" << m[1][1] << "\t" << m[1][2] << "\t"
<< m[2][0] << "\t" << m[2][1] << "\t" << m[2][2];
}
// stream& operator >> (istream& s, mat3& m)
//{
// mat3 m_tmp;
// s >> m_tmp[vx] >> m_tmp[vy] >> m_tmp[vz];
// if (s)
// m = m_tmp;
// return s;
//}
istream& operator >> (istream& s, mat3& m)
{
mat3 m_tmp;
s >> m_tmp[0][0] >> m_tmp[0][1] >> m_tmp[0][2]
>> m_tmp[1][0] >> m_tmp[1][1] >> m_tmp[1][2]
>> m_tmp[2][0] >> m_tmp[2][1] >> m_tmp[2][2];
if (s)
m = m_tmp;
return s;
}
#endif // ALGEBRAIOSTREAMS
void swap(mat3& a, mat3& b)
{
mat3 tmp(a); a = b; b = tmp;
}
/****************************************************************
* *
* mat4 member functions *
* *
****************************************************************/
// CONSTRUCTORS
mat4::mat4()
{
}
mat4::mat4(const vec4& v0, const vec4& v1, const vec4& v2, const vec4& v3)
{
v[0] = v0; v[1] = v1; v[2] = v2; v[3] = v3;
}
mat4::mat4(const Real d)
{
v[0] = v[1] = v[2] = v[3] = vec4(d);
}
mat4::mat4(const mat4& m)
{
v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; v[3] = m.v[3];
}
mat4::mat4(const Real* d)
{
v[0] = vec4(d[0], d[4], d[8], d[12]);
v[1] = vec4(d[1], d[5], d[9], d[13]);
v[2] = vec4(d[2], d[6], d[10], d[14]);
v[3] = vec4(d[3], d[7], d[11], d[15]);
}
mat4::mat4(const mat3& m)
{
v[0] = vec4(m[0], 0);
v[1] = vec4(m[1], 0);
v[2] = vec4(m[2], 0);
v[3] = vec4(0, 0, 0, 1);
}
mat4::mat4(const mat3& m, const vec3& t)
{
v[0] = vec4(m[0], t[0]);
v[1] = vec4(m[1], t[1]);
v[2] = vec4(m[2], t[2]);
v[3] = vec4(0, 0, 0, 1);
}
// Static functions
mat4 mat4::identity()
{
return mat4(vec4(1.0, 0.0, 0.0, 0.0),
vec4(0.0, 1.0, 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 0.0, 1.0));
}
mat4 mat4::translation3D(const vec3& v)
{
return mat4(vec4(1.0, 0.0, 0.0, v[vx]),
vec4(0.0, 1.0, 0.0, v[vy]),
vec4(0.0, 0.0, 1.0, v[vz]),
vec4(0.0, 0.0, 0.0, 1.0));
}
mat4 mat4::rotation3DDeg(const vec3& axis, const Real angleDeg)
{
Real angleRad = angleDeg * Deg2Rad;
return rotation3DRad(axis, angleRad);
}
mat4 mat4::rotation3DRad(const vec3& axis, const Real angleRad)
{
Real c = cos(angleRad),
s = sin(angleRad),
t = 1.0 - c;
vec3 Axis = axis;
Axis.Normalize();
return mat4(vec4(t * Axis[vx] * Axis[vx] + c,
t * Axis[vx] * Axis[vy] - s * Axis[vz],
t * Axis[vx] * Axis[vz] + s * Axis[vy],
0.0),
vec4(t * Axis[vx] * Axis[vy] + s * Axis[vz],
t * Axis[vy] * Axis[vy] + c,
t * Axis[vy] * Axis[vz] - s * Axis[vx],
0.0),
vec4(t * Axis[vx] * Axis[vz] - s * Axis[vy],
t * Axis[vy] * Axis[vz] + s * Axis[vx],
t * Axis[vz] * Axis[vz] + c,
0.0),
vec4(0.0, 0.0, 0.0, 1.0));
}
mat4 mat4::scaling3D(const vec3& scaleVector)
{
return mat4(vec4(scaleVector[vx], 0.0, 0.0, 0.0),
vec4(0.0, scaleVector[vy], 0.0, 0.0),
vec4(0.0, 0.0, scaleVector[vz], 0.0),
vec4(0.0, 0.0, 0.0, 1.0));
}
mat4 mat4::perspective3D(const Real d)
{
return mat4(vec4(1.0, 0.0, 0.0, 0.0),
vec4(0.0, 1.0, 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 1.0/d, 0.0));
}
// ASSIGNMENT OPERATORS
mat4& mat4::operator = ( const mat4& m )
{
v[0] = m.v[0]; v[1] = m.v[1]; v[2] = m.v[2]; v[3] = m.v[3];
return *this;
}
mat4& mat4::operator += ( const mat4& m )
{
v[0] += m.v[0]; v[1] += m.v[1]; v[2] += m.v[2]; v[3] += m.v[3];
return *this;
}
mat4& mat4::operator -= ( const mat4& m )
{
v[0] -= m.v[0]; v[1] -= m.v[1]; v[2] -= m.v[2]; v[3] -= m.v[3];
return *this;
}
mat4& mat4::operator *= ( const Real d )
{
v[0] *= d; v[1] *= d; v[2] *= d; v[3] *= d;
return *this;
}
mat4& mat4::operator /= ( const Real d )
{
v[0] /= d; v[1] /= d; v[2] /= d; v[3] /= d;
return *this;
}
vec4& mat4::operator [] ( int i)
{
assert(! (i < vx || i > vw));
return v[i];
}
const vec4& mat4::operator [] ( int i) const
{
assert(! (i < vx || i > vw));
return v[i];
}
// SPECIAL FUNCTIONS;
mat4 mat4::transpose() const
{
return mat4(vec4(v[0][0], v[1][0], v[2][0], v[3][0]),
vec4(v[0][1], v[1][1], v[2][1], v[3][1]),
vec4(v[0][2], v[1][2], v[2][2], v[3][2]),
vec4(v[0][3], v[1][3], v[2][3], v[3][3]));
}
mat4& mat4::apply(Svz_V_FCT_PTR fct)
{
v[vx].apply(fct); v[vy].apply(fct); v[vz].apply(fct); v[vw].apply(fct);
return *this;
}
void mat4::getData(Real* d)
{
d[0] = v[0][0]; d[1] = v[1][0]; d[2] = v[2][0]; d[3] = v[3][0];
d[4] = v[0][1]; d[5] = v[1][1]; d[6] = v[2][1]; d[7] = v[3][1];
d[8] = v[0][2]; d[9] = v[1][2]; d[10] = v[2][2]; d[11] = v[3][2];
d[12] = v[0][3]; d[13] = v[1][3]; d[14] = v[2][3]; d[15] = v[3][3];
}
// FRIENDS
mat4 operator - (const mat4& a)
{
return mat4(-a.v[0], -a.v[1], -a.v[2], -a.v[3]);
}
mat4 operator + (const mat4& a, const mat4& b)
{
return mat4(a.v[0] + b.v[0], a.v[1] + b.v[1], a.v[2] + b.v[2], a.v[3] + b.v[3]);
}
mat4 operator - (const mat4& a, const mat4& b)
{
return mat4(a.v[0] - b.v[0], a.v[1] - b.v[1], a.v[2] - b.v[2], a.v[3] - b.v[3]);
}
mat4 operator * (const mat4& a, const mat4& b)
{
#define ROWCOL(i, j) a.v[i].n[0]*b.v[0][j] + a.v[i].n[1]*b.v[1][j] + \
a.v[i].n[2]*b.v[2][j] + a.v[i].n[3]*b.v[3][j]
return mat4(
vec4(ROWCOL(0,0), ROWCOL(0,1), ROWCOL(0,2), ROWCOL(0,3)),
vec4(ROWCOL(1,0), ROWCOL(1,1), ROWCOL(1,2), ROWCOL(1,3)),
vec4(ROWCOL(2,0), ROWCOL(2,1), ROWCOL(2,2), ROWCOL(2,3)),
vec4(ROWCOL(3,0), ROWCOL(3,1), ROWCOL(3,2), ROWCOL(3,3))
);
#undef ROWCOL
}
mat4 operator * (const mat4& a, const Real d)
{
return mat4(a.v[0] * d, a.v[1] * d, a.v[2] * d, a.v[3] * d);
}
mat4 operator * (const Real d, const mat4& a)
{
return a*d;
}
mat4 operator / (const mat4& a, const Real d)
{
return mat4(a.v[0] / d, a.v[1] / d, a.v[2] / d, a.v[3] / d);
}
int operator == (const mat4& a, const mat4& b)
{
return ((a.v[0] == b.v[0]) && (a.v[1] == b.v[1]) && (a.v[2] == b.v[2]) && (a.v[3] == b.v[3]));
}
int operator != (const mat4& a, const mat4& b)
{
return !(a == b);
}
#ifdef ALGEBRAIOSTREAMS
ostream& operator << (ostream& s, const mat4& m)
{
return s << m.v[vx] << '\n' << m.v[vy] << '\n' << m.v[vz] << '\n' << m.v[vw];
}
// istream& operator >> (istream& s, mat4& m)
//{
// mat4 m_tmp;
// s >> m_tmp[vx] >> m_tmp[vy] >> m_tmp[vz] >> m_tmp[vw];
// if (s)
// m = m_tmp;
// return s;
//}
#endif // ALGEBRAIOSTREAMS
void swap(mat4& a, mat4& b)
{
mat4 tmp(a); a = b; b = tmp;
}
mat4 mat4::inverse() const // Gauss-Jordan elimination with partial pivoting
{
mat4 a(*this), // As a evolves from original mat into identity
b(mat4::identity()); // b evolves from identity into inverse(a)
int i, j, i1;
// Loop over cols of a from left to right, eliminating above and below diag
for (j=0; j<4; j++) { // Find largest pivot in column j among rows j..3
i1 = j; // Row with largest pivot candidate
for (i=j+1; i<4; i++)
if (fabs(a.v[i].n[j]) > fabs(a.v[i1].n[j]))
i1 = i;
// Swap rows i1 and j in a and b to put pivot on diagonal
swap(a.v[i1], a.v[j]);
swap(b.v[i1], b.v[j]);
// Scale row j to have a unit diagonal
if (a.v[j].n[j]==0.)
ALGEBRA_ERROR("mat4::inverse: singular matrix; can't invert\n");
b.v[j] /= a.v[j].n[j];
a.v[j] /= a.v[j].n[j];
// Eliminate off-diagonal elems in col j of a, doing identical ops to b
for (i=0; i<4; i++)
if (i!=j) {
b.v[i] -= a.v[i].n[j]*b.v[j];
a.v[i] -= a.v[i].n[j]*a.v[j];
}
}
return b;
}
/****************************************************************
* *
* quat member functions *
* *
****************************************************************/
// CONSTRUCTORS
quat::quat()
{
}
quat::quat(const Real d) //*** SHL added 11/25/10
{
if (d==0.0) {
n[vw] = 1.0; n[vx] = n[vy] = n[vz] = 0.0;
}
else n[vw] = d;
}
quat::quat(Real q[4])
{
n[vw] = q[0]; n[vx] = q[1]; n[vy] = q[2]; n[vz] = q[3];
}
quat::quat(const Real w, const Real x, const Real y, const Real z)
{
n[vw] = w; n[vx] = x; n[vy] = y; n[vz] = z;
}
quat::quat(const quat& q)
{
n[vw] = q.n[vw]; n[vx] = q.n[vx]; n[vy] = q.n[vy]; n[vz] = q.n[vz];
}
quat::quat(const vec4& v)
{
n[vw] = v.n[vw]; n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz];
}
quat::quat(const vec3& v) //*** SHL added 11/25/10
{
n[vw] = 0.0; n[vx] = v.n[vx]; n[vy] = v.n[vy]; n[vz] = v.n[vz];
}
// Static functions
Real quat::Dot(const quat& q0, const quat& q1)
{
return q0.n[vw] * q1.n[vw] + q0.n[vx] * q1.n[vx] + q0.n[vy] * q1.n[vy] + q0.n[vz] * q1.n[vz];
}
quat quat::UnitInverse(const quat& q)
{
return quat(q.n[vw], -q.n[vx], -q.n[vy], -q.n[vz]);
}
Real quat::CounterWarp(Real t, Real fCos)
{
const Real ATTENUATION = 0.82279687f;
const Real WORST_CASE_SLOPE = 0.58549219f;
Real fFactor = 1.0 - ATTENUATION * fCos;
fFactor *= fFactor;
Real fK = WORST_CASE_SLOPE * fFactor;
return t * (fK * t * (2.0 * t - 3.0) + 1.0 + fK);
}
static const Real ISQRT_NEIGHBORHOOD = 0.959066f;
static const Real ISQRT_SCALE = 1.000311f;
static const Real ISQRT_ADDITIVE_CONSTANT = ISQRT_SCALE / (Real)sqrt(ISQRT_NEIGHBORHOOD);
static const Real ISQRT_FACTOR = ISQRT_SCALE * (-0.5f / (ISQRT_NEIGHBORHOOD * (Real)sqrt(ISQRT_NEIGHBORHOOD)));
Real quat::ISqrt_approx_in_neighborhood(Real s)
{
return ISQRT_ADDITIVE_CONSTANT + (s - ISQRT_NEIGHBORHOOD) * ISQRT_FACTOR;
}
// Assignment operators
quat& quat::operator = (const quat& q)
{
n[vw] = q.n[vw]; n[vx] = q.n[vx]; n[vy] = q.n[vy]; n[vz] = q.n[vz];
return *this;
}
quat& quat::operator += (const quat& q)
{
n[vw] += q.n[vw]; n[vx] += q.n[vx]; n[vy] += q.n[vy]; n[vz] += q.n[vz];
return *this;
}
quat& quat::operator -= (const quat& q)
{
n[vw] -= q.n[vw]; n[vx] -= q.n[vx]; n[vy] -= q.n[vy]; n[vz] -= q.n[vz];
return *this;
}
quat& quat::operator *= (const quat& q)
{
*this = quat(n[vw] * q.n[vw] - n[vx] * q.n[vx] - n[vy] * q.n[vy] - n[vz] * q.n[vz],
n[vw] * q.n[vx] + n[vx] * q.n[vw] + n[vy] * q.n[vz] - n[vz] * q.n[vy],
n[vw] * q.n[vy] + n[vy] * q.n[vw] + n[vz] * q.n[vx] - n[vx] * q.n[vz],
n[vw] * q.n[vz] + n[vz] * q.n[vw] + n[vx] * q.n[vy] - n[vy] * q.n[vx]);
return *this;
}
quat& quat::operator *= (const Real d)
{
n[vw] *= d; n[vx] *= d; n[vy] *= d; n[vz] *= d;
return *this;
}
quat& quat::operator /= (const Real d)
{
n[vw] /= d; n[vx] /= d; n[vy] /= d; n[vz] /= d;
return *this;
}
// Indexing
Real& quat::operator [](int i)
{
return n[i];
}
Real quat::operator [](int i) const
{
return n[i];
}
Real& quat::W()
{
return n[vw];
}
Real quat::W() const
{
return n[vw];
}
Real& quat::X()
{
return n[vx];
}
Real quat::X() const
{
return n[vx];
}
Real& quat::Y()
{
return n[vy];
}
Real quat::Y() const
{
return n[vy];
}
Real& quat::Z()
{
return n[vz];
}
Real quat::Z() const
{
return n[vz];
}
// Friends
quat operator - (const quat& q)
{
return quat(-q.n[vw], -q.n[vx], -q.n[vy], -q.n[vz]);
}
quat operator + (const quat& q0, const quat& q1)
{
return quat(q0.n[vw] + q1.n[vw], q0.n[vx] + q1.n[vx], q0.n[vy] + q1.n[vy], q0.n[vz] + q1.n[vz]);
}
quat operator - (const quat& q0, const quat& q1)
{
return quat(q0.n[vw] - q1.n[vw], q0.n[vx] - q1.n[vx], q0.n[vy] - q1.n[vy], q0.n[vz] - q1.n[vz]);
}
quat operator * (const quat& q, const Real d)
{
return quat(q.n[vw] * d, q.n[vx] * d, q.n[vy] * d, q.n[vz] * d);
}
quat operator * (const Real d, const quat& q)
{
return quat(q.n[vw] * d, q.n[vx] * d, q.n[vy] * d, q.n[vz] * d);
}
quat operator * (const quat& q0, const quat& q1)
{
// modified
return quat(0.0f);
}
quat operator / (const quat& q, const Real d)
{
return quat(q.n[vw] / d, q.n[vx] / d, q.n[vy] / d, q.n[vz] / d);
}
bool operator == (const quat& q0, const quat& q1)
{
return (q0.n[vw] == q1.n[vw]) && (q0.n[vx] == q1.n[vx]) && (q0.n[vy] == q1.n[vy]) && (q0.n[vz] == q1.n[vz]);
}
bool operator != (const quat& q0, const quat& q1)
{
return !(q0 == q1);
}
// special functions
Real quat::Length2() const
{
return n[vw] * n[vw] + n[vx] * n[vx] + n[vy] * n[vy] + n[vz] * n[vz];
}
Real quat::Length() const
{
return sqrt(Length2());
}
quat& quat::Normalize()
{
Real l = Length();
if (l < EPSILON || abs(l) > 1e6)
{
FromAxisAngle(vec3(0.0f, 1.0f, 0.0f), 0.0f);
}else
{
*this /= l;
}
return *this;
}
quat& quat::fastNormalize()
{
Real s = n[vw] * n[vw] + n[vx] * n[vx] + n[vy] * n[vy] + n[vz] * n[vz]; // length^2
Real k = ISqrt_approx_in_neighborhood(s);
if (s <= 0.91521198) {
k *= ISqrt_approx_in_neighborhood(k * k * s);
if (s <= 0.65211970) {
k *= ISqrt_approx_in_neighborhood(k * k * s);
}
}
n[vw] *= k;
n[vx] *= k;
n[vy] *= k;
n[vz] *= k;
return * this;
}
quat quat::inverse() const
{
return quat(n[vw], -n[vx], -n[vy], -n[vz]);
}
quat quat::Exp(const quat& q)
{
// q = A*(x*i+y*j+z*k) where (x,y,z) is unit length
// exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k)
Real angle = sqrt(q.n[vx] * q.n[vx] + q.n[vy] * q.n[vy] + q.n[vz] * q.n[vz]);
Real sn, cs;
sn = sin(angle);
cs = cos(angle);
// When A is near zero, sin(A)/A is approximately 1. Use
// exp(q) = cos(A)+A*(x*i+y*j+z*k)
Real coeff = ( abs(sn) < EPSILON ? 1.0 : sn/angle );
quat result(cs, coeff * q.n[vx], coeff * q.n[vy], coeff * q.n[vz]);
return result;
}
quat quat::Log(const quat& q)
{
// q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length
// log(q) = A*(x*i+y*j+z*k)
Real angle = acos(q.n[vw]);
Real sn = sin(angle);
// When A is near zero, A/sin(A) is approximately 1. Use
// log(q) = sin(A)*(x*i+y*j+z*k)
Real coeff = ( abs(sn) < EPSILON ? 1.0 : angle/sn );
return quat(0.0f, coeff * q.n[vx], coeff * q.n[vy], coeff * q.n[vz]);
}
void quat::Zero()
{
n[vw] = n[vx] = n[vy] = n[vz] = 0.0f;
}
int quat::dim() const // SHL added - returns dimension of vector
{
return (sizeof(n)/sizeof(Real));
}
quat quat::Slerp(Real t, const quat& q0, const quat& q1)
{
return quat(0.0f);
}
quat quat::Intermediate (const quat& q0, const quat& q1, const quat& q2)
{
return quat(0.0f);
}
quat quat::Squad(Real t, const quat& q0, const quat& a, const quat& b, const quat& q1)
{
return Slerp(2.0 * t * (1.0 - t), Slerp(t, q0, q1), Slerp(t, a, b));
}
quat quat::ProjectToAxis(const quat& q, vec3 axis)
{
axis.Normalize();
vec3 qv = vec3(q[vx], q[vy], q[vz]);
Real angle = acos(q.n[vw]);
Real sn = sin(angle);
vec3 qaxis = qv / sn;
qaxis.Normalize();
angle = qaxis * axis;
Real halfTheta;
if (angle < EPSILON)
{
halfTheta = 0.0f;
}else
{
Real s = axis * qv;
Real c = q[vw];
halfTheta = atan2(s, c);
}
Real cn = cos(halfTheta);
sn = sin(halfTheta);
return quat(cn, sn * axis[vx], sn * axis[vy], sn * axis[vz]);
}
quat quat::ProjectToAxis2(const quat& q, vec3 axis)
{
axis.Normalize();
vec3 qv = vec3(q[vx], q[vy], q[vz]);
Real angle = acos(q.n[vw]);
Real sn = sin(angle);
vec3 qaxis = qv / sn;
qaxis.Normalize();
angle = qaxis * axis;
Real halfTheta;
if (fabs(angle) < EPSILON)
{
halfTheta = 0.0f;
}else
{
sn = axis * qv;
//Real c = q[vw];
halfTheta = asin(sn);
}
Real cn = cos(halfTheta);
return quat(cn, sn * axis[vx], sn * axis[vy], sn * axis[vz]);
}
// Conversion functions
void quat::ToAxisAngle (vec3& axis, Real& angleRad) const
{
Real length2 = n[vx]*n[vx] + n[vy]*n[vy] + n[vz]*n[vz];
if (length2 < EPSILON) {
angleRad = 0.0;
axis[vx] = 0.0;
axis[vy] = 1.0;
axis[vz] = 0.0;
}
else {
Real length = sqrt(length2);
angleRad = 2.0 * acos(n[vw]);
axis[vx] = n[vx]/length;
axis[vy] = n[vy]/length;
axis[vz] = n[vz]/length;
if (angleRad > M_PI) { // always use the smaller angle
angleRad = M2_PI - angleRad;
axis *= -1.0;
}
}
}
void quat::FromAxisAngle (const vec3& axis, Real angleRad)
{
Real fHalfAngle = angleRad * 0.5;
Real sn = sin(fHalfAngle);
n[vw] = cos(fHalfAngle);
n[vx] = axis[vx] * sn;
n[vy] = axis[vy] * sn;
n[vz] = axis[vz] * sn;
}
void quat::FromAxisXAngle(Real angleRad)
{
Real fHalfAngle = angleRad * 0.5;
n[vw] = cos(fHalfAngle);
n[vx] = sin(fHalfAngle);
n[vy] = n[vz] = 0.0f;
}
void quat::FromAxisYAngle(Real angleRad)
{
Real fHalfAngle = angleRad * 0.5;
n[vw] = cos(fHalfAngle);
n[vy] = sin(fHalfAngle);
n[vx] = n[vz] = 0.0f;
}
void quat::FromAxisZAngle(Real angleRad)
{
Real fHalfAngle = angleRad * 0.5;
n[vw] = cos(fHalfAngle);
n[vz] = sin(fHalfAngle);
n[vx] = n[vy] = 0.0f;
}
mat3 quat::ToRotation () const
{
// operations (*,+,-) = 24
Real tx = 2.0 * n[vx];
Real ty = 2.0 * n[vy];
Real tz = 2.0 * n[vz];
Real twx = tx * n[vw];
Real twy = ty * n[vw];
Real twz = tz * n[vw];
Real txx = tx * n[vx];
Real txy = ty * n[vx];
Real txz = tz * n[vx];
Real tyy = ty * n[vy];
Real tyz = tz * n[vy];
Real tzz = tz * n[vz];
mat3 m;
m[0][0] = 1.0 - tyy - tzz;
m[0][1] = txy - twz;
m[0][2] = txz + twy;
m[1][0] = txy + twz;
m[1][1] = 1.0 - txx - tzz;
m[1][2] = tyz - twx;
m[2][0] = txz - twy;
m[2][1] = tyz + twx;
m[2][2] = 1.0 - txx - tyy;
return m;
}
void quat::FromRotation (const mat3& rot)
{
}
#ifdef ALGEBRAIOSTREAMS
ostream& operator << (ostream& s, const quat& q)
{
return s << "[ " << q.n[vw] << ' ' << q.n[vx] << ' ' << q.n[vy] << ' ' << q.n[vz] << " ]";
}
#endif // ALGEBRAIOSTREAMS
| true |
921763e26d6769855a8d161c56848663b311c111 | C++ | mfkiwl/SRC2-smach | /state_machine/utils/sm_utils.cpp | UTF-8 | 4,449 | 2.71875 | 3 | [
"BSD-3-Clause"
] | permissive | /**
@file sm_utils.cpp
Utility functions for
@author Jared Beard,
@version 1.0 8/25/2020
*/
#include <state_machine/sm_utils.h>
namespace sm_utils
{
std::vector<std::pair<double, double>> circlePacking(std::pair<double,double> origin, std::vector<double> P, int size_P, double radius)
{
//variables
std::vector<std::pair<double, double>> samples, transformed_samples;
Eigen::MatrixXd P_mat = Eigen::MatrixXd::Zero(size_P,size_P);
int count = 0;
Eigen::Vector2d origin_vec(origin.first,origin.second);
/**Get transform of P matrix Eigenvalues*/
// Convert to matrix
for (int i = 0; i < size_P; ++i)
{
for(int j = 0; j < size_P; ++j)
{
P_mat(i,j) = P[count];
++count;
}
}
// Evaluate eigenvectors/values
//ROS_INFO_STREAM(P_mat(0,0) << "," << P_mat(0,1));
//ROS_INFO_STREAM(P_mat(1,0) << "," << P_mat(1,1));
Eigen::EigenSolver<Eigen::MatrixXd> eigSolver(P_mat);
Eigen::VectorXd eigVector;
eigVector = eigSolver.eigenvectors().col(0).real();
/**for (int i = 0; i < 2; ++i)
{
//ROS_INFO_STREAM(eigSolver.eigenvectors().col(i).real());
}*/
Eigen::VectorXd eigValues;
eigValues = eigSolver.eigenvalues().real();
/**for (int i = 0; i < 2; ++i)
{
ROS_INFO_STREAM(eigValues[i]);
}*/
//Eigen::Vector2d eigValues(eigSolver.eigenvectors().cols(0));
ROS_INFO_STREAM("Tr: " << P_mat.trace() << " SUM: " << P_mat.sum() << " TF: " << (P_mat.trace() == P_mat.sum()));
std::vector<double> scaledEigenVector, sEV;
for (int i = 0; i < size_P; ++i)
{
sEV.push_back(eigVector(i)*eigValues(0));
if (P_mat.trace() != P_mat.sum()){
scaledEigenVector.push_back(eigVector(i)*eigValues(0));
} else
{
scaledEigenVector.push_back(P_mat(i,i));
}
ROS_INFO_STREAM(scaledEigenVector[i]);
}
ROS_INFO_STREAM("STEP");
//Pack in transformed space
double ellipseRadius = 0;
double x = 0.0, y = 0.0;
int n = 0, m = 0;
std::pair<double,double> temp_pair;
//aligned points
while (x <= fabs(scaledEigenVector[0]))
{
while (ellipseRadius <= 1.0)
{
temp_pair = {x,y};
transformed_samples.push_back(temp_pair);
if (x > 0)
{
temp_pair = {-x,y};
transformed_samples.push_back(temp_pair);
}
if (y > 0)
{
temp_pair = {x,-y};
transformed_samples.push_back(temp_pair);
if (x > 0)
{
temp_pair = {-x,-y};
transformed_samples.push_back(temp_pair);
}
}
++n;
y = n*sqrt(5)*radius;
ellipseRadius = (x*x)/pow(scaledEigenVector[0],2) + (y*y)/pow(scaledEigenVector[1],2);
ROS_INFO_STREAM("X: " << x << " Y: " << y << " R: " << ellipseRadius);
}
++m;
n = 0;
x = m*radius;
y = 0;
ellipseRadius = 0;
}
x = radius/2.0;
y = sqrt(5)/2.0*radius;
n = 0;
m = 0;
//offset points
//ROS_INFO("1");
while (ellipseRadius <= 1.0)
{
//ellipseRadius = 0;
while (ellipseRadius <= 1.0)
{
temp_pair = {x,y};
transformed_samples.push_back(temp_pair);
temp_pair = {x,-y};
transformed_samples.push_back(temp_pair);
temp_pair = {-x,y};
transformed_samples.push_back(temp_pair);
temp_pair = {-x,-y};
transformed_samples.push_back(temp_pair);
++n;
y = (2*n+1)*sqrt(5)/2.0*radius;
ellipseRadius = (x*x)/pow(scaledEigenVector[0],2) + (y*y)/pow(scaledEigenVector[1],2);
ROS_INFO_STREAM(ellipseRadius);
}
++m;
n = 0;
x = ( (2*m+1.0)/2.0 )*radius;
y = sqrt(5)/2.0*radius;
ellipseRadius = (x*x)/pow(scaledEigenVector[0],2) + (y*y)/pow(scaledEigenVector[1],2);
}
//transform to normal space
double theta = atan2(sEV[1],sEV[0]);
Eigen::Matrix2d R;
R << cos(theta), -sin(theta), sin(theta), cos(theta);
ROS_INFO_STREAM("THETA: " << theta);
ROS_INFO_STREAM(R);
for (int i = 0; i < transformed_samples.size();++i)
{
Eigen::Vector2d temp_vec;
temp_vec << transformed_samples[i].first, transformed_samples[i].second;
Eigen::Vector2d point = R.inverse()*temp_vec + origin_vec;
std::pair<double,double> temp_pair(point(0),point(1));
samples.push_back(temp_pair);
}
return samples;
}
}
| true |
c98755ea7e2551522b034d662b23b07ae56d3c2f | C++ | Sashank-B/Strings- | /removecharactersfrom1stringpresentin2string.cpp | UTF-8 | 654 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
#define NO_OF_CHAR 256
int* print2(string str2)
{
int* count=(int*)calloc(sizeof(int),NO_OF_CHAR);
for(int i=0;i<str2.size();i++){
count[str2[i]]++;
}
return count;
}
string remove(string str1, string str2)
{
int* count=print2(str2);
string res;
int index=0;
while(index<str1.size())
{
char temp=str1[index];
if(count[temp]==0)
{
res.push_back(temp);
}
index++;
}
return res;
}
int main()
{
string str1="sony";
string str2="somu";
cout<<remove(str1,str2);
}
| true |
71489ba4c69dc45720311a187bbc22b1bd4470ab | C++ | metanoia1989/cppStudy | /C++基础/constants/IMO/constants.h | UTF-8 | 294 | 2.8125 | 3 | [] | no_license | #pragma once
#include <iostream>
namespace constants
{
const int PICTURE_NUMS = 5;
class Number
{
public:
Number()
{
std::cout << "Number constructed" << std::endl;
}
};
const Number price;
} // namespace constants | true |
e3699179b7ae62932763d15a7e2fa7d577264036 | C++ | xiaomu00/Exercises | /二叉树/Tree/Tree/test_1.cpp | WINDOWS-1256 | 386 | 2.828125 | 3 | [] | no_license | #include"tree.h"
////
MyTree::MyTree(const int* s)
{
int i = 0;
root = MyTree_1(s,&i);
}
TreeNode* MyTree::MyTree_1(const int* s, int *p)
{
if (s[*p] == -1 || s[*p] == '\0')
return NULL;
else
{
TreeNode* t = new TreeNode(s[*p]);
(*p)++;
t->left = MyTree_1(s, p);
(*p)++;
t->right = MyTree_1(s, p);
return t;
}
}
| true |
9ac663277b12908bc7bbb72ac5844514eba50c14 | C++ | b-z-l/RandomSketches | /USB_Battery_sleep_fix/USB_Battery_sleep_fix.ino | UTF-8 | 933 | 2.578125 | 3 | [] | no_license | #include "LowPower.h"
#define sleep_period 200000
#define wake_period 20000
#define sleep_cycles sleep_period / 8000
// need to wake every 11 cycles (88 seconds) for 100ms
#define battery_keepalive 11
#define transistor_pin 2
int sleep_count = sleep_cycles;
long int lastSleepTime = millis();
void setup()
{
pinMode(transistor_pin, OUTPUT);
// start turned on
digitalWrite(transistor_pin, HIGH);
}
void loop()
{
// Wake cycle
// Sleep cycle
if (millis() - lastSleepTime > wake_period)
{
digitalWrite(transistor_pin, LOW);
for (int i = 0; i < sleep_cycles; i++)
{
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
// keepalive if 96 seconds have elapsed
if ((i % 12) == 0)
{
digitalWrite(transistor_pin, HIGH);
delay(20);
digitalWrite(transistor_pin, LOW);
}
}
digitalWrite(transistor_pin, HIGH);
lastSleepTime = millis();
}
}
| true |
911fb31ec817eb45063160d84806257e72fb7aa6 | C++ | indraShan/4.2_Project | /Statistics.cc | UTF-8 | 15,636 | 3.578125 | 4 | [] | no_license | #include "Statistics.h"
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
Relation::Relation() {
numTuples = 0;
joinedRelationCount = 1;
attributes = new unordered_map<string, int>();
}
//Custom output stream for Relations
std::ostream& operator<< (std::ostream& os, const Relation& relation)
{
os << relation.numTuples;
os << " ";
os << relation.joinedRelationCount;
os << " ";
os << relation.attributes->size();
os << "\n";
for (unordered_map<string, int>::iterator iit = relation.attributes->begin(); iit!=relation.attributes->end(); ++iit) {
os << iit->first << " " << iit->second << "\n";
}
return os;
}
Statistics::Statistics()
{
store = new unordered_map<string, Relation*>();
}
//Perform deep copy of the statistics objefct
Statistics::Statistics(Statistics ©Me)
{
this->store = new unordered_map<string, Relation*>();
unordered_map<string, Relation *>::iterator it;
for (it = copyMe.store->begin(); it != copyMe.store->end(); it++)
{
string relName = string(it->first);
Relation *relation = it->second;
char cRelName[relName.size() + 1];
strcpy(cRelName, relName.c_str());
AddRel(cRelName, relation->numTuples);
unordered_map<string, int>::iterator attIterator;
for (attIterator = relation->attributes->begin();
attIterator != relation->attributes->end(); attIterator++)
{
string attName = string(attIterator->first);
int numDistincts = attIterator->second;
char cAttName[attName.size() + 1];
strcpy(cAttName, attName.c_str());
AddAtt(cRelName, cAttName, numDistincts);
}
Relation *copied = this->store->find(relName)->second;
copied->joinedRelationCount = relation->joinedRelationCount;
}
}
Statistics::~Statistics()
{
if (store != NULL) {
delete store;
store = NULL;
}
}
//Add relations to the store map
void Statistics::AddRel(char *relName, int numTuples)
{
Relation *relation = NULL;
//if relation already exists, update the number of tuples, else create a new relation
if (this->store->find(relName) == store->end()) {
relation = new Relation();
this->store->insert(std::make_pair(relName, relation));
}
else {
relation = this->store->find(relName)->second;
}
relation->joinedRelationCount = 1;
relation->numTuples = numTuples;
}
//Add attributes to the relation
void Statistics::AddAtt(char *relName, char *attName, int numDistincts)
{
Relation *relation = NULL;
if (this->store->find(relName) == store->end()) {
relation = new Relation();
this->store->insert(std::make_pair(relName, relation));
}
else {
relation = this->store->find(relName)->second;
}
//If numDistincts is given as -1, use the number of tuples as number of distincts
if(numDistincts == -1){
relation->attributes->insert(std::make_pair(attName, relation->numTuples));
}
else{
relation->attributes->insert(std::make_pair(attName, numDistincts));
}
//Store all the attributes in a map for easy access
attribute_relations[attName] = relName;
//printStore();
}
void Relation::copyAttributes(Relation *rel){
//Copy attributes from the parameter to current relation
this->attributes->insert(rel->attributes->begin(),rel->attributes->end());
}
void Statistics::CopyRel(char *oldName, char *newName)
{
//If relation doesn't exist
if (this->store->find(oldName) == store->end()) {
return;
}
//Create a new relation object
Relation *relation = this->store->find(oldName)->second;
//Add the relation to the store map with new name
AddRel(newName, relation->numTuples);
unordered_map<string, int>::iterator attIterator;
for (attIterator = relation->attributes->begin();
attIterator != relation->attributes->end(); attIterator++)
{
//Add all the attributes to the new relation
string attName = string(newName) + "." + attIterator->first;
int numDistincts = attIterator->second;
char cAttName[attName.size() + 1];
strcpy(cAttName, attName.c_str());
AddAtt(newName, cAttName, numDistincts);
}
Relation *copied = this->store->find(newName)->second;
copied->joinedRelationCount = relation->joinedRelationCount;
}
//Read Statistics object from file
void Statistics::Read(char *fromWhere)
{
ifstream stats_file(fromWhere);
if (!stats_file.good()){
return;
}
//Get number of relations
int numRelations;
std::string line;
std::getline(stats_file, line);
std::istringstream iss0(line);
iss0 >> numRelations;
for(int i = 0; i < numRelations; i++){
//Get each relation name
std::string relNameLine;
Relation *relation = new Relation();
std::getline(stats_file, relNameLine);
std::istringstream iss(relNameLine);
string relName;
iss >> relName;
std::string relationLine;
std::getline(stats_file, relationLine);
std::istringstream iss2(relationLine);
int numTuples, joinedRelations, numAtts;
//Next line contains number of tuples, joinedRelationCount and number of attributes
iss2 >> numTuples >> joinedRelations >> numAtts;
relation->numTuples = numTuples;
relation->joinedRelationCount = joinedRelations;
for(int j = 0; j < numAtts; j++){
//Read all the attributes line by line and add to relation object
std::string attsLine;
std::getline(stats_file, attsLine);
string attr;
int distinct;
std::istringstream iss3(attsLine);
iss3 >> attr >> distinct;
relation->attributes->insert(std::make_pair(attr, distinct));
//add the attributes to the attribute-relations map
attribute_relations[attr] = relName;
}
//Insert the newly created relation into the map
this->store->insert(std::make_pair(relName, relation));
}
stats_file.close();
}
//Write statistics object to file in the following format -
//Number of relations
//{Relation 1 Name} {Relation 1 number of tuples} {Relation 1 joined relations count}
//number of Attributes
//attribute1 numDistincts
//attribute2 numDistincts
void Statistics::Write(char *fromWhere)
{
ofstream stats_file(fromWhere);
stats_file << store->size() << endl;
for (unordered_map<string, Relation*>::iterator iit = store->begin(); iit!=store->end(); ++iit){
stats_file << iit->first << endl;
stats_file << iit->second->numTuples;
stats_file << " ";
stats_file << iit->second->joinedRelationCount;
stats_file << " ";
stats_file << iit->second->attributes->size();
stats_file << "\n";
for (unordered_map<string, int>::iterator attIterator = iit->second->attributes->begin(); attIterator!=iit->second->attributes->end(); ++attIterator) {
stats_file << attIterator->first << " " << attIterator->second << "\n";
}
}
stats_file.close();
}
// Review and fix.
// Are we handling all cases?
// Error handling and print.
void Statistics::Apply(struct AndList *parseTree, char *relNames[], int numToJoin)
{
//Check if the given relations exist in the map
RelationsExist(relNames,numToJoin);
// Estimate the output
double estimate = 0.0l;
if (0 == parseTree and numToJoin <= 2){
double result = 1.0l;
for (unsigned i = 0; i < numToJoin; i++){
string relation(relNames[i]);
result *= store->find(relation)->second->numTuples;
}
estimate = result;
}
else{
estimate = EstimateResultFromParseTree(parseTree);
}
string newrelation;
bool joinExists = false;
AndList *aList = parseTree;
//Check if join exists in the given parse tree
while(aList){
OrList *p_or = aList->left;
while(p_or){
ComparisonOp * comp = p_or->left;
if(comp != NULL){
Operand *leftop = comp->left;
Operand *rightop = comp->right;
//If both operands are names and operator equals
if( (leftop != NULL && (leftop->code == NAME)) &&
(rightop != NULL && (rightop->code == NAME) ) && comp->code == EQUALS) {
joinExists = true;
}
}
p_or = p_or->rightOr;
}
aList = aList->rightAnd;
}
//if a join exists...
if (joinExists){
//Merge both the relations and update the store and merge_relations maps
for(int i=0;i<numToJoin;i++){
string rel(relNames[i]);
newrelation += rel;
}
Relation *joinRelInfo = new Relation();
joinRelInfo->numTuples=estimate;
for(int i=0;i<numToJoin;i++){
if(store->find(relNames[i]) != store->end()){
joinRelInfo->attributes->insert(store->find(relNames[i])->second->attributes->begin(),store->find(relNames[i])->second->attributes->end());
}
}
//joinRelInfo.print();
store->insert(std::make_pair(newrelation, joinRelInfo));
vector<string> attrs;
//Check the parse tree to get attributes in the CNF
while(parseTree){
OrList *p_or = parseTree->left;
while(p_or){
ComparisonOp *comp = p_or->left;
if(comp!=NULL){
Operand *leftop = comp->left;
if(leftop!=NULL && leftop->code == NAME){
string attribute(leftop->value);
if(attribute_relations.count(attribute)==0){
cout << "Attribute " << attribute << " not found in given relations." << endl;
exit(-1);
}
attrs.push_back(attribute);
}
Operand *rightop = comp->right;
if(rightop!=NULL && rightop->code == NAME){
string attribute(rightop->value);
if(attribute_relations.count(attribute)==0){
cout << "Attribute " << attribute << " not found in given relations." << endl;
exit(-1);
}
attrs.push_back(attribute);
}
}
p_or = p_or->rightOr;
}
parseTree = parseTree->rightAnd;
}
set<string> relationSet;
for(auto i:attrs){
relationSet.insert(attribute_relations[i]);
}
for(auto i:relationSet){
joinRelInfo->copyAttributes(store->find(i)->second);
store->erase(i);
}
for(int i=0;i<numToJoin;i++){
store->erase(relNames[i]);
merged_relations[relNames[i]]=newrelation;
}
for (unordered_map<string, int>::iterator i = joinRelInfo->attributes->begin(); i!=joinRelInfo->attributes->end(); ++i) {
attribute_relations[i->first]=newrelation;
}
}
}
//Estimate number of tuples output
double Statistics::Estimate(struct AndList *parseTree, char **relNames, int numToJoin)
{
//If the parse tree is empty with two relations, return cross product
if (0 == parseTree && numToJoin <= 2){
double result = 1.0l;
for (signed i = 0; i < numToJoin; i++){
string relation(relNames[i]);
result *= store->find(relNames[i])->second->numTuples;
}
return result;
}
//Check if relations exist
RelationsExist(relNames,numToJoin);
//Check the parsetree and estimate output
double result = EstimateResultFromParseTree(parseTree);
return result;
}
//Estimate result from parsetree
double Statistics::EstimateResultFromParseTree(struct AndList *parseTree){
double result = 1.0l;
bool joinExists = false;
double selectOnlySize = 0.0l;
while (parseTree){
OrList *p_or = parseTree->left;
bool independent = true;
bool single = false;
set <string> orset;
int count = 0;
// Checking for independent or dependent OR
while(p_or){
ComparisonOp * comp = p_or->left;
if(comp != NULL){
count++;
string attribute(comp->left->value);
orset.insert(attribute);
}
p_or = p_or->rightOr;
}
if(orset.size() != count){
independent = false;
}
if(count == 1){
independent = false;
single = true;
}
p_or = parseTree->left;
double ORresult = 0.0l;
if(independent){
ORresult = 1.0l;
}
// Estimate the output
while(p_or){
ComparisonOp * comp = p_or->left;
if(comp != NULL){
Operand *leftop = comp->left;
Operand *rightop = comp->right;
switch(comp->code){
//If the operator is Equals
case EQUALS:
if( (leftop != NULL && (leftop->code == NAME)) &&
(rightop != NULL && (rightop->code == NAME) )) {
joinExists = true;
string lattr(leftop->value);
string rattr(rightop->value);
string lrel = attribute_relations[lattr];
string rrel = attribute_relations[rattr];
int lRelSize = this->store->find(lrel)->second->numTuples;
int lDistinct = this->store->find(lrel)->second->attributes->find(lattr)->second;
int rRelSize = this->store->find(rrel)->second->numTuples;
int rDistinct = this->store->find(rrel)->second->attributes->find(rattr)->second;
double denominator = max(lDistinct,rDistinct);
ORresult += (min(lRelSize,rRelSize) * (max(rRelSize,lRelSize) / denominator));
}
else{
Operand *record = NULL;
Operand *literal = NULL;
if(leftop->code == NAME){
record = leftop;
literal = rightop;
}
else{
record = rightop;
literal = leftop;
}
string attribute(record->value);
if(attribute_relations.count(attribute) == 0) break;
string relation = attribute_relations[attribute];
int distinct = this->store->find(relation)->second->attributes->find(attribute)->second;
if(independent && !single){
double prob = 1.0l - (1.0l/distinct);
ORresult *= prob;
}
else{
double prob = (1.0l/distinct);
ORresult += prob;
}
}
break;
//If the operator is less than or greater than
case LESS_THAN : case GREATER_THAN:
Operand *record = NULL;
Operand *literal = NULL;
if(leftop->code == NAME){
record = leftop;
literal = rightop;
}
else{
record = rightop;
literal = leftop;
}
string attribute(record->value);
if(attribute_relations.count(attribute) == 0) break;
string relation = attribute_relations[attribute];
if(independent){
double prob = 1.0l - (1.0l/3.0l);
ORresult *= prob;
}
else{
double prob = 1.0l/3.0l;
ORresult += prob;
}
break;
}
if (!joinExists){
Operand *record = NULL;
if (leftop->code == NAME)
{record = leftop;}
else if (rightop->code == NAME)
{record = rightop;}
string attribute(record->value);
if(attribute_relations.count(attribute) == 0) break;
string relation = attribute_relations[attribute];
int relationSize = this->store->find(relation)->second->numTuples;
selectOnlySize = relationSize;
}
}
p_or = p_or->rightOr;
}
if(independent){
result *= (1 - ORresult);
}
else{
result *= ORresult;
}
parseTree = parseTree->rightAnd;
}
if (joinExists){ return result; }
return result * selectOnlySize;
}
void Statistics::RelationsExist(char *relNames[],int numToJoin){
for(int i=0;i<numToJoin;i++){
string rel(relNames[i]);
if(this->store->count(rel)==0 && merged_relations.count(rel)==0){
cout << "Relation not found" << rel << endl;
exit(-1);
}
}
}
int Statistics::validateParams(struct AndList *parseTree, char **relNames, int numToJoin) {
return 1;
}
void Statistics::printStore() {
for (unordered_map<string, Relation*>::iterator iit = store->begin(); iit!=store->end(); ++iit) {
std::cout << iit->first << " " << *iit->second << "\n";
}
}
| true |
6d72cfa513cbfde13c996ca3dfb0ac9c50488424 | C++ | toomeykevin/reversis.dotello | /Grille.cpp | ISO-8859-1 | 15,604 | 3.4375 | 3 | [] | no_license | #include "Grille.hpp"
#include <iostream>
using namespace std;
//Case Grille :: getG(){
// return G ;}
void Grille :: setCouleurjouee(Color c){
couleurjouee=c;
}
Color Grille :: getCouleurjouee(){
return couleurjouee;
}
int trouverLigne(int x){
for (int i=0;i<8;i++){
int a=i*(70+5);
if (x>a && x<a+75){
return i;
}
}
}
int trouverColonne(int y){
for (int j=0;j<8;j++){
int b=j*(70+5);
if (y>b && y<b+75){
return j;
}
}
}
void Grille :: effectuerTour(int i, int j){
int L[8]; //on cre une liste de taille 8 qui contient les infos sur les axes explorer
for (int k=0;k<8;k++){
L[k]=1;
} //on remplit cette liste de 1
// on va regarder les tats des cases qui entourent la case sur laquelle on a cliqu ; si la case est vide ou de la mme couleur que celle que l'on joue, cela ne sert rien d'explorer l'axe et on passe donc 0 l'emplacement de L correspondant
// L[0] correspond l'axe vertical montant, L[1] l'axe diagonal montant droit, etc. en faisant le tour dans le sens des aiguilles d'une montre
// pour chaque case, on commence par un if qui permet de vrifier si la case observe existe ou pas (ie si on sort de la grille ou pas)
if (j-1<0){L[0]=0;}
if (j+1>7){L[4]=0;}
if (i-1<0){L[6]=0;}
if (i+1>7){L[3]=0;}
if (G[i][j-1].getCouleur() == Color::Black || G[i][j-1].getCouleur() == couleurjouee){ //si la case est vide ou bien si elle est de la mme couleur que celle que l'on joue
L[0]=0; // alors on va pas explorer l'axe qui va par l
}
// on regarde la case en diagonale montante droite
if (G[i+1][j-1].getCouleur() == Color::Black || G[i+1][j-1].getCouleur() == couleurjouee){
L[1]=0;
}
// on regarde la case droite
if (G[i+1][j].getCouleur() == Color::Black || G[i+1][j].getCouleur() == couleurjouee){
L[2]=0;
}
// on regarde la case en diagonale descendante droite
if (G[i+1][j+1].getCouleur() == Color::Black || G[i+1][j+1].getCouleur() == couleurjouee){
L[3]=0;
}
// on regarde la case en dessous
if (G[i][j+1].getCouleur() == Color::Black || G[i][j+1].getCouleur() == couleurjouee){
L[4]=0;
}
// on regarde la case en diagonale descendante gauche
if (G[i-1][j+1].getCouleur() == Color::Black || G[i-1][j+1].getCouleur() == couleurjouee){
L[5]=0;
}
// on regarde la case gauche
if (G[i-1][j].getCouleur() == Color::Black || G[i-1][j].getCouleur() == couleurjouee){
L[6]=0;
}
// on regarde la case en diagonale montante gauche
if (G[i-1][j-1].getCouleur() == Color::Black || G[i-1][j-1].getCouleur() == couleurjouee){
L[7]=0;
}
/////////////////////////////////////////////////////////////////////////////////BLOC 2
int k=0;
while (k<8){ //on parcourt la liste L pour explorer successivement les axes
if (L[k]==0){ //si l'lment k de la liste L est nul
k=k+1; //alors on explore pas l'axe et on passe au suivant
}
else{ //sinon alors on doit explorer l'axe
if(k==0){ //si il s'agit du premier lment, on explore l'axe vertical montant
int jcourant = j-1; //initialisation de jcourant
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (jcourant<0 || G[i][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[i][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
jcourant = jcourant-1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i][j-m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==1){ //axe diagonal montant droit
int icourant = i+1; //initialisation de icourant
int jcourant = j-1;
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant>7 || jcourant<0 || G[icourant][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant+1;
jcourant = jcourant-1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i+m][j-m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==2){ //axe horizontal droit
int icourant = i+1; //initialisation de icourant
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant>7 || G[icourant][j].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][j].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant+1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i+m][j].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==3){ //axe diagonal descendant droit
int icourant = i+1; //initialisation de icourant
int jcourant = j+1;
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant>7 || jcourant>7 || G[icourant][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant+1;
jcourant = jcourant+1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i+m][j+m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==4){ //axe vertical descendant
int jcourant = j+1; //initialisation de jcourant
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (jcourant>7 || G[i][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[i][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
jcourant = jcourant+1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i][j+m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==5){ //axe diagonal descendant gauche
int icourant = i-1; //initialisation de icourant
int jcourant = j+1;
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant<0 || jcourant>7 || G[icourant][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant-1;
jcourant = jcourant+1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i-m][j+m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==6){ //axe horizontal gauche
int icourant = i-1; //initialisation de icourant
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant<0 || G[icourant][j].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][j].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant-1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i-m][j].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
else if(k==7){ //axe diagonal montant gauche
int icourant = i-1; //initialisation de icourant
int jcourant = j-1;
int n=0; //initialisation du compteur n
while (L[k]==1){ //tant qu'on considre que l'axe peut encore apporter retournement
if (icourant<0 || jcourant<0 || G[icourant][jcourant].getCouleur()==Color::Black){ //si on a atteint le bord de la grille sans avoir trouv de case vide ou de couleur oppose
L[k]=0;//alors on arrte d'observer cet axe et on sort de la boucle while
n=0;
cout<<"Impossible de jouer ici !"<<endl;
}
else if (G[icourant][jcourant].getCouleur()==couleurjouee){ //si la case compare est de la mme couleur ou vide
L[k]=0; //il devient inutile d'observer plus loin, donc on sort de la boucle while
}
else { //sinon si la case compare est de l'autre couleur
icourant = icourant-1;
jcourant = jcourant-1; //on continue explorer plus loin dans l'axe
n=n+1; //on rajoute une case retourner au compteur
}
}
for(int m=1;m<=n;m++){
G[i-m][j-m].setCouleur(couleurjouee);
G[i][j].setCouleur(couleurjouee);
}
k=k+1; //on passe l'axe suivant
}
}
}
if (couleurjouee==Color::Blue){
couleurjouee=Color::Magenta;
cout<<"on joue mntnt le magenta"<<endl;
}
else if (couleurjouee==Color::Magenta){
couleurjouee=Color::Blue;
cout<<"on joue mntnt le bleu"<<endl;
}
}
Grille::Grille(){
couleurjouee=Color::Magenta;
}
| true |
84185247b9b0558c961230471f300b12e3cf7842 | C++ | miyukiYAMAMOTO/aziantam | /YAMAMOTO_test/aziantam/item.cpp | SHIFT_JIS | 8,506 | 2.578125 | 3 | [] | no_license | //// ۯ߱т͓G|ꂽ炻̏ɏo
//// HPgēG|Ĉ莞ԓɎȂƏ悤ɂ
//// G̓蔻Ɂ@ςƉ̌DAꔽؖȂƕ̌DACV傾Ɛ̌D
//// ̌D͑S̓GMOBmŏo悤ɂ
//// G|ꂽ@HP炵Ă
#include <DxLib.h>
#include "main.h"
#include "stage.h"
#include "item.h"
//-----Oϐ錾
//ъ֘A
//D
CHARACTER itemF[ITEM_MAX]; // ۯ߱ѕϐi[p
CHARACTER itemFmaster[MAGIC_TYPE_MAX];
int itemFImage[MAGIC_TYPE_MAX]; // ۯ߱їp摜iFFD̓
int itemFIImage[MAGIC_TYPE_MAX]; // ؗp摜iFFD̓CIF̓
int itemFBImage[MAGIC_TYPE_MAX]; // ٗp摜iFFD̓,@BFق̓
bool itemFBFlag; // \,\p
//O̐_
CHARACTER itemB[ITEM_TYPE_B_MAX];
int itemBImage[ITEM_TYPE_B_MAX]; // _̉摜iBF̓
//-----я̏
void ItemSystmeInit(void)
{
//-----ϐ̏
//Diۯߗp
itemFmaster[MAGIC_TYPE_FIRE].charType = MAGIC_TYPE_FIRE; // D̎ F
itemFmaster[MAGIC_TYPE_WATER].charType = MAGIC_TYPE_WATER; // D̎ F
itemFmaster[MAGIC_TYPE_WIND].charType = MAGIC_TYPE_WIND; // D̎ F
itemFmaster[MAGIC_TYPE_HEAL].charType = MAGIC_TYPE_HEAL; // D̎ F
//D܂Ƃ߂ď
for (int i = 0; i < MAGIC_TYPE_MAX; i++)
{
itemFmaster[i].pos = { 0,0 }; //@D̒n}̍W
itemFmaster[i].size = { 20,20 }; // D̉摜
itemFmaster[i].offsetSize = { itemFmaster[i].size.x / 2,itemFmaster[i].size.y / 2 }; //@D̵̾
itemFmaster[i].point = 12; // D̖
itemFmaster[i].lifeMax = 200; // D̗͍̑őli\ԁj
itemFmaster[i].life = itemFmaster[i].lifeMax; // D̗̑
itemFmaster[i].hitFlag = false;
}
//Diٗp
itemFBFlag = false; // F\
//O̐_
itemB[ITEM_TYPE_KEN].charType = ITEM_TYPE_KEN; // O̐_@F@
itemB[ITEM_TYPE_KAGAMI].charType = ITEM_TYPE_KAGAMI; // O̐_@F@
itemB[ITEM_TYPE_MAGATAMA].charType = ITEM_TYPE_MAGATAMA; // O̐_@F@
//O̐_܂Ƃ߂ď
for (int i = 0; i < ITEM_TYPE_B_MAX; i++)
{
itemB[i].size = { 20,20 }; // O̐_̉摜
itemB[i].offsetSize = { itemB[i].size.x / 2,itemB[i].size.y / 2 }; //@O̐_̵̾
}
//-----̨̓o^
//D(ۯߗp
LoadDivGraph("item/fudaD.png", 4, 4, 1
, ITEM_M_SIZE, ITEM_M_SIZE, itemFImage);
//Diؗp
LoadDivGraph("item/fudaI.png", 4, 4, 1
, ITEM_M_SIZE, ITEM_M_SIZE, itemFIImage);
//Diٗp
LoadDivGraph("item/fuda_Big.png", 4, 4, 1
, ITEM_B_SIZE, ITEM_B_SIZE, itemFBImage);
//O̐_
LoadDivGraph("item/zingi20.png", 3, 3, 1
, ITEM_M_SIZE, ITEM_M_SIZE, itemBImage);
}
void ItemGameInit(void)
{
//Diۯߗp
for (int type = 0; type < MAGIC_TYPE_MAX;type++)
{
for (int i = 0; i < ITEM_MAX; i++)
{
itemF[i] = itemFmaster[type];
itemF[i].life = 0;
}
}
//O̐_
for (int i = 0; i < ITEM_TYPE_B_MAX; i++)
{
itemB[i].pos = { 50,120 }; //@O̐_̒n}̍W
itemB[i].lifeMax = 20; // O̐_̗͍̑őli\ԁj
itemB[i].life = itemB[i].lifeMax; // O̐_̗̑
}
}
void ItemDropControl(void)
{
for (int i = 0; i < ITEM_MAX; i++)
{
//ĂeT
if (itemF[i].life > 0)
{
//炷(˒)
itemF[i].life--;
}
}
}
bool ItemMobControl(MAGIC_TYPE type)
{
//Dꖇȏ゠ꍇA\
if (itemF[type].point > 0)
{
itemF[type].point--;
return true;
}
return false;
}
void ItemGameDraw(void)
{
//-----`揈
//Diۯߗp
for (int i = 0; i < ITEM_MAX; i++)
{
//ĂD̂ݕ\
if (itemF[i].life > 0)
{
//-----摜`
DrawGraph(itemF[i].pos.x - itemF[i].offsetSize.x + mapPos.x
, itemF[i].pos.y - itemF[i].offsetSize.y + mapPos.y
, itemFImage[itemF[i].charType]
, true);
}
}
//O̐_
//for (int i = 0; i < ITEM_TYPE_B_MAX; i++)
//{
// if (itemB[i].life > 0)
// {
// DrawGraph((itemB[i].pos.x - itemB[i].offsetSize.x) * i
// , itemB[i].pos.y - itemB[i].offsetSize.y
// , itemBImage[itemB[i].charType]
// , true);
// DrawBox((itemB[i].pos.x - itemB[i].offsetSize.x) * i
// , itemB[i].pos.y - itemB[i].offsetSize.y
// , (itemB[i].pos.x - itemB[i].offsetSize.x) * i + itemB[i].size.x
// , itemB[i].pos.y - itemB[i].offsetSize.y + itemB[i].size.y
// , 0xFF00FF, false);
// }
//}
}
//-----ؗp`
void ItemI_Draw(void)
{
//̌D
DrawGraph(430, 250, itemFIImage[MAGIC_TYPE_FIRE], true);
DrawFormatString(480, 254, 0xFF22FF, "~", true);
DrawFormatString(530, 253, 0xFF22FF, "%d", itemF[MAGIC_TYPE_FIRE].point);
DrawFormatString(560, 254, 0xFF22FF, "", true);
//̌D
DrawGraph(430, 300, itemFIImage[MAGIC_TYPE_WATER], true);
DrawFormatString(480, 304, 0xFF22FF, "~", true);
DrawFormatString(530, 303, 0xFF22FF, "%d", itemF[MAGIC_TYPE_WATER].point);
DrawFormatString(560, 304, 0xFF22FF, "", true);
//̌D
DrawGraph(430, 350, itemFIImage[MAGIC_TYPE_WIND], true);
DrawFormatString(480, 354, 0xFF22FF, "~", true);
DrawFormatString(530, 353, 0xFF22FF, "%d", itemF[MAGIC_TYPE_WIND].point);
DrawFormatString(560, 354, 0xFF22FF, "", true);
//̌D
DrawGraph(430, 420, itemFIImage[MAGIC_TYPE_HEAL], true);
DrawFormatString(480, 424, 0xFF22FF, "~", true);
DrawFormatString(530, 423, 0xFF22FF, "%d", itemF[MAGIC_TYPE_HEAL].point);
DrawFormatString(560, 424, 0xFF22FF, "", true);
}
//-----eƓG̓蔻@(true : , false : ͂)
bool ItemHitCheck(XY sPos, int sSize)
{
int point = GetRand(2) + 1;
//SĂ̓Gɓ蔻{
for (int i = 0; i < ITEM_MAX; i++)
{
if (itemF[i].life > 0)
{
if (((itemF[i].pos.x - itemF[i].size.x / 2) < (sPos.x + sSize / 2))
&& ((itemF[i].pos.x + itemF[i].size.x / 2) > (sPos.x - sSize / 2))
&& ((itemF[i].pos.y - itemF[i].size.y / 2) < (sPos.y + sSize / 2))
&& ((itemF[i].pos.y + itemF[i].size.y / 2) > (sPos.y - sSize / 2)))
{
//тE߲ĉZ
//DɐGꂽZ
if (itemF[i].charType == MAGIC_TYPE_FIRE)
{
itemF[i].point += point;
itemF[i].hitFlag = true;
}
if (itemF[i].charType == MAGIC_TYPE_WATER)
{
itemF[i].point += point;
itemF[i].hitFlag = true;
}
if (itemF[i].charType == MAGIC_TYPE_WIND)
{
itemF[i].point += point;
itemF[i].hitFlag = true;
}
if (itemF[i].charType == MAGIC_TYPE_HEAL)
{
itemF[i].point += point;
itemF[i].hitFlag = true;
}
return true;
}
}
}
//eOꂽ
return false;
}
//-----hbvACe
void ItemDrop(XY ePos, MAGIC_TYPE type)
{
//hbvĂȂ̂Ȃ`FbN
//ĂȂ̂͐
for (int item = 0; item < ITEM_MAX; item++)
{
//hbvĂȂ̂T
if (itemF[item].life <= 0)
{
//ACe𗎂Ƃ
itemF[item].charType = type;
itemF[item].pos = { ePos.x,ePos.y };
itemF[item].life = itemF[item].lifeMax;
break;
}
}
}
//-----hbvACe
void DeleteItem()
{
for (int item = 0; item < ITEM_MAX; item++)
{
if (itemF[item].life > 0 && itemF[item].hitFlag)
{
itemF[item].life = 0;
itemF[item].hitFlag = false;
break;
}
}
}
bool GameOverSet()
{
if ((itemF[MAGIC_TYPE_FIRE].point == 0)
&& (itemF[MAGIC_TYPE_WATER].point == 0)
&& (itemF[MAGIC_TYPE_WIND].point == 0))
{
return true;
}
return false;
}
| true |
80d3303ddf9d40e9f61f85881951548cfafbca08 | C++ | bsy6766/Volt3D | /Volt3D/Volt3D/Engine/Preference.h | UTF-8 | 871 | 2.515625 | 3 | [] | no_license | /**
* @file Preference.h
*
* @author Seung Youp Baek
* @copyright Copyright (c) 2019 Seung Youp Baek
*/
#ifndef V3D_PREFERENCE_H
#define V3D_PREFERENCE_H
#include <string>
#include <optional>
#include <nlohmann/json.hpp>
#include "Utils/Macros.h"
namespace v3d
{
/**
* @class Prefence
* @brief Read and write preference file
*
* @group core
*
* @since 1.0
*/
class VOLT3D_DLL Preference
{
friend class Engine;
private:
Preference();
std::wstring path;
nlohmann::json data;
bool init(const std::wstring& folderName);
bool readJson();
public:
DELETE_COPY_AND_COPY_ASSIGN_CONSTRUCTOR(Preference);
DEFAULT_MOVE_CONSTRUCTORS(Preference);
~Preference();
int getInt(const char* key);
bool reset();
bool load();
bool save();
std::wstring getPath() const { return path; }
const nlohmann::json& getData() const { return data; }
};
}
#endif | true |
e3225cb5210559d30d71135354f307624aeb9a74 | C++ | chenkunxiao/OrocosThread | /internal/ConnID.cpp | UTF-8 | 415 | 2.515625 | 3 | [] | no_license | #include "ConnID.hpp"
using namespace RTT::internal;
SimpleConnID::SimpleConnID(const ConnID* orig ) : cid( orig == 0 ? this : orig) {}
bool SimpleConnID::isSameID(ConnID const& id) const
{
SimpleConnID const* real_id = dynamic_cast<SimpleConnID const*>(&id);
if (!real_id) return false;
return real_id->cid == this->cid;
}
ConnID* SimpleConnID::clone() const
{
return new SimpleConnID( this->cid );
}
| true |
3b4d8d161a5c2619589d6194dbcbb77a4ea32705 | C++ | dilshadsallo/Cpp11Exploration | /CoreLanguage/UsabilityEnhancements/Lambda_ImplicitReturn.cpp | UTF-8 | 332 | 3.546875 | 4 | [] | no_license | /**
* \author Dilshad Sallo
* \date 2012/7/26
* \brief Lambda expression that have implicit return type.
*/
#include <iostream>
#include <typeinfo>
int main() {
auto result = [] (int x, double y) {
return x * y;
}(3,4.3);
std::cout << "The datatype of " << result << " is " << typeid(result).name() << "." << std::endl;
}
| true |
2b4f7a4244194e4a61aabd8d4452bba3c972f873 | C++ | Jfriesen222/Smoothieware | /src/modules/robot/arm_solutions/CoreXZSolution.cpp | UTF-8 | 1,195 | 2.53125 | 3 | [] | no_license | #include "CoreXZSolution.h"
#include "ConfigValue.h"
#include "checksumm.h"
#define x_reduction_checksum CHECKSUM("x_reduction")
#define z_reduction_checksum CHECKSUM("z_reduction")
CoreXZSolution::CoreXZSolution(Config* config)
{
x_reduction = config->value(x_reduction_checksum)->by_default(1.0f)->as_number();
z_reduction = config->value(z_reduction_checksum)->by_default(3.0f)->as_number();
}
void CoreXZSolution::cartesian_to_actuator(const float cartesian_mm[], float actuator_mm[] ){
actuator_mm[ALPHA_STEPPER] = (this->x_reduction * cartesian_mm[X_AXIS]) + (this->z_reduction * cartesian_mm[Z_AXIS]);
actuator_mm[BETA_STEPPER ] = (this->x_reduction * cartesian_mm[X_AXIS]) - (this->z_reduction * cartesian_mm[Z_AXIS]);
actuator_mm[GAMMA_STEPPER] = cartesian_mm[Y_AXIS];
}
void CoreXZSolution::actuator_to_cartesian(const float actuator_mm[], float cartesian_mm[] ){
cartesian_mm[X_AXIS] = (0.5F/this->x_reduction) * (actuator_mm[ALPHA_STEPPER] + actuator_mm[BETA_STEPPER]);
cartesian_mm[Z_AXIS] = (0.5F/this->z_reduction) * (actuator_mm[ALPHA_STEPPER] - actuator_mm[BETA_STEPPER]);
cartesian_mm[Y_AXIS] = actuator_mm[GAMMA_STEPPER];
}
| true |
3ad6e33a218ebf28c5288a16962283386377bef9 | C++ | ji-one/algorithm-study | /baekjoon_study_won/dynamic/9655.cpp | UTF-8 | 395 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int d[1001];
int main()
{
int n;
cin >> n;
d[2] = 1; //0 : SK, 1: CY
d[4] = 1;
for (int i = 4; i <= n; i++)
{
if (d[i - 1] == 0 || d[i - 3] == 0)
d[i] = 1;
else
d[i] = 0;
}
if (d[n] == 0)
cout << "SK";
else
cout << "CY";
return 0;
} | true |
9a4d7c76eb5eda1d4fe23813cfc980dca8dfebb7 | C++ | yclizhe/acm | /POJ/2182/2182.cpp | UTF-8 | 872 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int a[8005];
int c[8005];
int ans[8005];
int lowbit(int x) {
return x & (-x);
}
int sum(int n) {
int s = 0;
while(n>0) {
s += c[n];
n -= lowbit(n);
}
return s;
}
void change(int i, int num, int max) {
while(i<=max) {
c[i] += num;
i += lowbit(i);
}
}
int binarysearch(int x, int s, int e) {
if(s==e)
return s;
int m = (s+e)>>1;
int xm = m - sum(m);
if(xm < x)
return binarysearch(x,m+1,e);
else //此处注意,因为相等时并不一定正确,需要确保压缩到只剩一个位置时
return binarysearch(x,s,m);
}
int main() {
int N;
cin >> N;
memset(c,0,sizeof(c));
a[0] = 0;
for(int i=1; i<N; i++)
cin >> a[i];
for(int i=N-1; i>=0; i--) {
int x = binarysearch(a[i]+1, 1+a[i], N);
ans[i] = x;
change(x,1,N);
}
for(int i=0; i<N; i++)
cout << ans[i] << endl;
}
| true |
3bda514706391fa99aa4a9995d75f96b9916054d | C++ | cristinazhou/PAT | /PAT甲级(Advanced Level)/1029.Median(25).cpp | UTF-8 | 2,378 | 3.484375 | 3 | [] | no_license | 1029. Median (25)
Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1={11, 12, 13, 14} is 12, and the median of S2={9, 10, 15, 16, 17} is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
Given two increasing sequences of integers, you are asked to find their median.
Input
Each input file contains one test case. Each case occupies 2 lines, each gives the information of a sequence. For each sequence, the first positive integer N (<=1000000) is the size of that sequence. Then N integers follow, separated by a space. It is guaranteed that all the integers are in the range of long int.
Output
For each test case you should output the median of the two given sequences in a line.
Sample Input
4 11 12 13 14
5 9 10 15 16 17
Sample Output
13
题目大意:给出两个已排序序列,求这两个序列合并后的中间数
分析:用指针pq分别指向两个数组的第一个元素,然后根据中间数就是舍弃掉(n-1)/2个数,所以根据比较大小而向后移动pq指针,表示舍弃掉p和q指针前面的所有数字。当完成后,比较两个序列的指针所指数字的大小,输出较小的那个。如果一个序列已经到达最末端,则输出那个没有到达末端的指针所指向的数字~~~
#include <cstdio>
#include <vector>
using namespace std;
int main() {
int m, n, p = 0, q = 0;
scanf("%d", &m);
vector<long int> v1(m);
for(int i = 0; i < m; i++)
scanf("%ld", &v1[i]);
scanf("%d", &n);
vector<long int> v2(n);
for(int i = 0; i < n; i++)
scanf("%ld", &v2[i]);
int cnt = ((m + n) - 1) / 2;
while(cnt) {
while(p < m && q < n && v1[p] < v2[q] && cnt) {
p++;
cnt--;
}
while(p < m && q < n && v1[p] >= v2[q] && cnt) {
q++;
cnt--;
}
while(p < m && q >= n && cnt) {
p++;
cnt--;
}
while(p >= m && q < n && cnt) {
q++;
cnt--;
}
}
long int ans;
if(p < m && q < n)
ans = v1[p] < v2[q] ? v1[p] : v2[q];
else
ans = p < m ? v1[p] : v2[q];
printf("%ld", ans);
return 0;
} | true |
569a9b5631905177bac8a43d334c292a32a9721a | C++ | im6h/Cplusplus | /CTDL>/Sort_SapXepKhongNhanh.cpp | UTF-8 | 857 | 2.6875 | 3 | [] | no_license | # include <iostream>
# include <stdlib.h>
using namespace std;
int n;
long long a[100002], b[100002];
void _Input();
void radixSort();
void _Output();
main(){
_Input();
radixSort();
_Output();
}
void _Input(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> a[i];
}
}
void _Output(){
for(int i = 0; i < n; i++){
cout << a[i] << " ";
}
}
void radixSort(){
long long maxA = a[0], mod = 1;
int cs[12];
for(int i = 1; i < n; i++) maxA = max(maxA, a[i]);
while(maxA/mod){
//cout << mod << endl;
for(int i = 0; i < 12; i++) cs[i] = 0;
for(int i = 0; i < n; i++){
cs[(long long)(a[i]/mod)%10]++;
}
for(int i = 1; i < 12; i++) cs[i] += cs[i-1];
for(int i = n-1; i >= 0; i--){
//cout <<"-" << cs[(long long)(a[i]/mod)%10] << endl;
b[--cs[(a[i]/mod)%10]] = a[i];
}
for(int i = 0; i < n; i++) a[i] = b[i];
mod *= 10;
}
}
| true |
05f597b35bf0aa19e6ba06967287f3b36a320bcc | C++ | qingswu/Transim | /Transims60/Include/Memory_Pool.hpp | UTF-8 | 3,690 | 3.171875 | 3 | [] | no_license | //*********************************************************
// Memory_Pool.hpp - reusable memory allocated records
//*********************************************************
#ifndef MEMORY_POOL_HPP
#define MEMORY_POOL_HPP
#include "Data_Pack.hpp"
//---------------------------------------------------------
// Memory_Record class definition
//---------------------------------------------------------
class Memory_Record
{
public:
Memory_Record (void) { Clear (); }
int Next_Record (void) { return (next_rec); }
void Next_Record (int value) { next_rec = value; }
void Clear (void) { next_rec = -1; }
bool Pack (Data_Buffer &data) { return (data.Add_Data (this, sizeof (*this))); }
bool UnPack (Data_Buffer &data) { return (data.Get_Data (this, sizeof (*this))); }
private:
int next_rec;
};
//---------------------------------------------------------
// Memory_Pool class definition
//---------------------------------------------------------
template <typename Type>
class Memory_Pool : public Vector <Type>
{
public:
Memory_Pool (void) { Clear (); }
size_t size (void) { return (Vector <Type>::size ()); }
typename Type &at (size_t index) { return (Vector <Type>::at (index)); }
typename Memory_Pool <Type>::iterator begin (void) { return (Vector <Type>::begin ()); }
typename Memory_Pool <Type>::iterator end (void) { return (Vector <Type>::end ()); }
Type Get_Record (int index)
{
return (at (index));
}
int Put_Record (Type &rec, int from_index = -1)
{
int rec_id;
rec.Next_Record (-1); //---- end of list ----
if (free_count == 0) {
rec_id = (int) size ();
push_back (rec);
} else {
rec_id = first_free;
at (rec_id) = rec;
if (--free_count > 0) {
typename Vector <Type>::iterator itr;
for (itr = begin () + first_free; itr != end (); itr++, first_free++) {
if (itr->Next_Record () == -2) break; //---- free record ----
}
}
}
if (from_index >= 0) {
Type *rec_ptr = Record_Pointer (from_index);
rec_ptr->Next_Record (rec_id);
}
return (rec_id);
}
int Free_Record (Type *rec_ptr)
{
int next_rec = rec_ptr->Next_Record ();
rec_ptr->Next_Record (-2); //---- mark as free ----
return (next_rec);
}
int Free_Record (int index)
{
return (Free_Record (Record_Pointer (index)));
}
void Update_Record (Type &rec, int index)
{
Type *rec_ptr = Record_Pointer (index);
rec.Next_Record (rec_ptr->Next_Record ());
*rec_ptr = rec;
}
Type * Record_Pointer (int index)
{
return (&at (index));
}
bool Check_Free (void)
{
first_free = -1;
free_count = 0;
int rec = 0;
typename Vector <Type>::iterator itr;
for (itr = begin (); itr != end (); itr++, rec++) {
if (itr->Next_Record () == -2) { //---- free record ----
if (free_count++ == 0) {
first_free = rec;
}
}
}
return (free_count > 0);
}
void Clear (void)
{
first_free = -1; free_count = 0; clear ();
}
bool Pack (Data_Buffer &data)
{
if (data.Add_Data (&first_free, sizeof (first_free))) {
if (data.Add_Data (&free_count, sizeof (free_count))) {
return (Vector <Type>::Pack (data));
}
}
return (false);
}
bool UnPack (Data_Buffer &data)
{
if (data.Get_Data (&first_free, sizeof (first_free))) {
if (data.Get_Data (&free_count, sizeof (free_count))) {
return (Vector <Type>::UnPack (data));
}
}
return (false);
}
private:
int first_free;
int free_count;
};
#endif
| true |
d8f34b9437d9bdb54410cf68c3d391f79ac0346b | C++ | phial3/DataStruction | /DTLib/MatrixGraph.h | UTF-8 | 6,125 | 3.28125 | 3 | [] | no_license | #ifndef MATRIXGRAPH_H
#define MATRIXGRAPH_H
#include "Graph.h"
#include "Exception.h"
#include "DynamicArray.h"
namespace MyLib
{
// N:顶点个数 V:顶点的类型 E:权值的类型
template <int N, typename V, typename E>
class MartixGraph : public Graph<V, E>
{
protected:
V* m_vertexes[N];
E* m_edges[N][N];
int m_eCount;
public:
MartixGraph()
{
for(int i=0; i<vertexCount(); i++)
{
m_vertexes[i] = NULL;
for(int j=0; j<vertexCount(); j++)
{
m_edges[i][j] = NULL;
}
}
m_eCount = 0;
}
V getVertex(int i)
{
V ret;
if(!getVertex(i, ret))
{
THROW_EXCEPTION(InvalidParameterException, "index i is invalid...");
}
return ret;
}
bool getVertex(int i, V& value) // O(1)
{
bool ret = ((0 <= i) && (i < vertexCount()));
if(ret)
{
if(m_vertexes[i])
{
value = *(m_vertexes[i]);
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No value assigned to this vertex...");
}
}
return ret;
}
bool setVertex(int i, const V& value) // O(1)
{
bool ret = ((0 <= i) && (i < vertexCount()));
if(ret)
{
V* data = m_vertexes[i];
if(data == NULL)
{
data = new V();
}
if(data)
{
*data = value;
m_vertexes[i] = data;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to store new vettex value...");
}
}
return ret;
}
SharedPointer<Array<int>> getAdjacent(int i) // O(n)
{
DynamicArray<int>* ret = NULL;
if((0 <= i) && (i < vertexCount()))
{
int n = 0;
for(int j=0; j<vertexCount(); j++)
{
if(m_edges[i][j])
{
n++;
}
}
ret = new DynamicArray<int>(n);
if(ret)
{
for(int j=0, k=0; j<vertexCount(); j++)
{
if(m_edges[i][j])
{
ret->set(k++, j);
}
}
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create ret object...");
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "index i is invalid...");
}
return ret;
}
bool isAdjacent(int i, int j)
{
return ((0 <= i) && (i < vertexCount()) && (0 <= j) && (j < vertexCount()) && (m_edges[i][j] != NULL));
}
E getEdge(int i, int j)
{
E ret;
if(!getEdge(i, j, ret))
{
THROW_EXCEPTION(InvalidParameterException, "index <i, j> is invalid...");
}
return ret;
}
bool getEdge(int i, int j, E& value) // O(1)
{
bool ret = ( (0 <= i) && (i < vertexCount()) &&
(0 <= j) && (j < vertexCount()) );
if(ret)
{
if(m_edges[i][j])
{
value = *(m_edges[i][j]);
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No value assigned to this vertex...");
}
}
return ret;
}
bool setEdge(int i, int j, const E& value) // O(1)
{
bool ret = ( (0 <= i) && (i < vertexCount()) &&
(0 <= j) && (j < vertexCount()) );
if(ret)
{
E* ne = m_edges[i][j];
if(ne == NULL)
{
ne = new E();
if(ne)
{
*ne = value;
m_edges[i][j] = ne;
m_eCount++;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to store new edge calue...");
}
}
else
{
*ne = value;
}
}
return ret;
}
bool removeEdge(int i, int j) // O(1)
{
bool ret = ( (0 <= i) && (i < vertexCount()) &&
(0 <= j) && (j < vertexCount()) );
if(ret)
{
E* toDel = m_edges[i][j];
m_edges[i][j] = NULL;
if(toDel)
{
m_eCount--;
delete toDel;
}
}
return ret;
}
int vertexCount()
{
return N;
}
int edgeCount()
{
return m_eCount;
}
int OD(int i) // O(n)
{
int ret = 0;
if((0 <= i) && (i < vertexCount()))
{
for(int j=0; j<vertexCount(); j++)
{
if(m_edges[i][j])
{
ret++;
}
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "index i is invalid...");
}
return ret;
}
int ID(int i) // O(n)
{
int ret = 0;
if((0 <= i) && (i < vertexCount()))
{
for(int j=0; j<vertexCount(); j++)
{
if(m_edges[j][i])
{
ret++;
}
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "index i is invalid...");
}
return ret;
}
~MartixGraph()
{
for(int i=0; i<vertexCount(); i++)
{
for(int j=0; j<vertexCount(); j++)
{
delete m_edges[i][j];
}
delete m_vertexes[i];
}
}
};
}
#endif // MATRIXGRAPH_H
| true |
1afb51103eff83312e1c4bfefeb835ee33473000 | C++ | widefire/rtsp-server | /tcpCacherManager.cpp | GB18030 | 1,738 | 2.65625 | 3 | [] | no_license | #include "tcpCacher.h"
tcpCacherManager::tcpCacherManager()
{
}
tcpCacherManager::~tcpCacherManager()
{
for (m_Iterator=m_tcpCacherMap.begin();m_Iterator!=m_tcpCacherMap.end();++m_Iterator)
{
if (m_Iterator->second)
{
delete m_Iterator->second;
m_Iterator->second = 0;
}
}
m_tcpCacherMap.clear();
}
int tcpCacherManager::appendBuffer(unsigned int sockId, char * dataIn, unsigned int size)
{
//ǷѾ
m_Iterator = m_tcpCacherMap.find(sockId);
if (m_Iterator==m_tcpCacherMap.end())
{
//ڣһ
tcpCacher *tmpCacher = new tcpCacher();
m_tcpCacherMap.insert(std::pair<unsigned int, tcpCacher*>(sockId, tmpCacher));
m_Iterator = m_tcpCacherMap.find(sockId);
}
int ret = m_Iterator->second->appendBuffer(dataIn, size);
return ret;
}
int tcpCacherManager::getBuffer(unsigned int sockId, char * dataOut, unsigned int size, bool remove)
{
//ڣش
m_Iterator = m_tcpCacherMap.find(sockId);
if (m_Iterator == m_tcpCacherMap.end())
{
return 404;
}
int ret = m_Iterator->second->getBuffer(dataOut, size, remove);
return ret;
}
int tcpCacherManager::getValidBuffer(unsigned int sockId, std::list<DataPacket>& dataList, tcpBufAnalyzer analyzer)
{
//ڣش
m_Iterator = m_tcpCacherMap.find(sockId);
if (m_Iterator == m_tcpCacherMap.end())
{
return 404;
}
int ret = m_Iterator->second->getValidBuffer(dataList, analyzer);
return ret;
}
void tcpCacherManager::removeCacher(unsigned int sockId)
{
//ڣش
m_Iterator = m_tcpCacherMap.find(sockId);
if (m_Iterator == m_tcpCacherMap.end())
{
return ;
}
delete m_Iterator->second;
m_Iterator->second = 0;
m_tcpCacherMap.erase(sockId);
}
| true |
4c76deb1dfcad20053391a58ecc365ea6508eaf9 | C++ | RobertVoropaev/Algorithms | /dz2/sort.h | UTF-8 | 754 | 3.203125 | 3 | [] | no_license | #pragma once
#include "sortBasis.h"
template <class type, class Cmp>
int partitionCmp(type *arr, int left, int right, int pivot, Cmp cmp) {
swap(arr, pivot, right);
int j = left;
for (int i = left; i < right; i++) {
if (cmp(arr[i],arr[right])) {
swap(arr, i, j);
j++;
}
}
swap(arr, j, right);
return j;
}
template <class type, class Cmp>
void quicksortCmp(type *arr, int left, int right, Cmp cmp) {
if (left < right) {
int pivot = partitionCmp(arr, left, right, pivot_selection(arr, left, right), cmp);
quicksortCmp(arr, left, pivot - 1, cmp);
quicksortCmp(arr, pivot + 1, right, cmp);
}
}
template <class type, class Cmp>
void sort(type *arr, int len, Cmp cmp) {
quicksortCmp(arr, 0, len - 1, cmp);
}
| true |
9d135a4f40140fb810d3593bf888ac7820e5e71f | C++ | profornnan/Problem-Solving | /BOJ/구현/2064-IP 주소.cpp | UTF-8 | 1,512 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#define sws ios::sync_with_stdio(false), cin.tie(NULL)
using namespace std;
int n;
vector<string> ip_bin_arr;
string dec2bin(string str) {
int n = stoi(str);
string ret;
while (n) {
ret += to_string(n % 2);
n /= 2;
}
while (ret.size() < 8)
ret += '0';
reverse(ret.begin(), ret.end());
return ret;
}
string bin2dec(string str) {
string ret;
for (int i = 0; i < str.size(); i += 8) {
int n = 0;
string bin = str.substr(i, 8);
for (int j = 0; j < bin.size(); j++)
n += (bin[j] - '0') * pow(2, 7 - j);
ret += to_string(n) + '.';
}
ret.pop_back();
return ret;
}
int main(void)
{
sws;
freopen("input.txt", "r", stdin);
cin >> n;
for (int i = 0; i < n; i++) {
char ip[16];
cin >> ip;
string ip_bin;
char* ptr = strtok(ip, ".");
while (ptr != NULL) {
ip_bin += dec2bin(string(ptr));
ptr = strtok(NULL, ".");
}
ip_bin_arr.push_back(ip_bin);
}
string network_addr, network_mask;
for (int i = 0; i < ip_bin_arr[0].size(); i++) {
char now = ip_bin_arr[0][i];
bool is_correct = true;
for (string ip_bin : ip_bin_arr) {
if (now != ip_bin[i]) {
is_correct = false;
break;
}
}
if (!is_correct)
break;
network_addr += now;
network_mask += "1";
}
while (network_addr.size() < 32) {
network_addr += "0";
network_mask += "0";
}
cout << bin2dec(network_addr) << '\n';
cout << bin2dec(network_mask) << '\n';
return 0;
}
| true |
f0863296b299351759cf874c30199c71eb3f147d | C++ | HhTtLllL/algorithm | /leetcode/258.cpp | UTF-8 | 192 | 2.796875 | 3 | [] | no_license | class Solution {
public:
int addDigits(int num)
{
if(num >9 && (num%9)) return (num%9);
else if((num > 9) && (num%9 == 0)) return 9;
else return num;
}
};
| true |
737ad11f66f9e6092086bc1d6db8b177ef704ed9 | C++ | Palette25/C_plus_plus_codes | /C++_codes/3 The third week/课后题/Card Shuffling and Dealing (eden)/my deck of cards.cpp | UTF-8 | 628 | 3.296875 | 3 | [] | no_license | include "deck-of-cards.hpp"
DeckOfCards::DeckOfCards(){
for (unsigned int i(0); i <= 12; ++i)
{
for (unsigned int j(0); j <= 3; ++j)
{
Card card(i, j);
deck.push_back(card);
}
}
currentCard = 0;
}
// constructor initializes deck
Card DeckOfCards::dealCard(){
int card_, current = currentCard;
while(1){
if(current<=12) {
card_=current;
break;}
else current-=13;
}
Card card(card_, currentCard/13);
currentCard++;
return card;
} // deals cards in deck
bool DeckOfCards::moreCards() const{
if(currentCard>=52) return 0;
else return 1;
} | true |