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
acf50aec3ea04d881384fa8741610b3bfc11301b
C++
mei-t/algorithm_study
/cracking_the_coding_interview/17-16.cpp
UTF-8
979
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <unordered_map> using namespace std; int masseur(const vector<int>& times, size_t i, unordered_map<int, int>* memo){ if(i >= times.size()){ return 0; }else if(memo->find(i) != memo->end()){ return (*memo)[i]; } int timeSum = max(times[i] + masseur(times, i + 2, memo), masseur(times, i + 1, memo)); memo->insert({i, timeSum}); return timeSum; } int masseur(const vector<int>& times){ unordered_map<int, int> memo; return masseur(times, 0, &memo); } int masseur2(const vector<int>& times){ int onePrev = 0; int twoPrev = 0; for(int i = times.size() - 1; i >= 0; i--){ int current = max(onePrev, twoPrev + times[i]); twoPrev = onePrev; onePrev = current; } return onePrev; } int main(void){ vector<int> times = {30, 15, 60, 75, 45, 15, 15, 45}; cout << masseur(times) << endl; cout << masseur2(times) << endl; return 0; }
true
2a58a738acf1d56972fc98fb4f631a5c6bad3df7
C++
yalishanda42/oop2021
/week4/1/Product.hpp
UTF-8
420
2.84375
3
[]
no_license
#pragma once class Product { public: Product(const char *, double, unsigned int); /* THE BIG 4: */ Product(); Product(const Product&); Product& operator=(const Product&); ~Product(); /* ========== */ const char *getName() const; void setName(const char *); double price; unsigned int amount; private: char *name; // Helpers: void copyName(const char *); };
true
5cdfc4a6ce7a2fb9328ea9851b1f32a93d6d979c
C++
mshafer1/SteilHU
/170/NeedsOrganized/Organize last---messy/rough/cin.getline_example.cpp
UTF-8
668
3.28125
3
[]
no_license
//this does not work #include<iostream> using namespace std; int main() { //advantages of using getline over >> //can get multiple words (it does not stop at white space) //has bounds checking //when more characters are entered than the limit // set, an error flag is set char s[100]; cin.getline(s,10); cout << s << endl; //removes the error that may have been set by //entering too many characters cin.clear(); //throws away all of the characters in the input buffer int bufferSize = cin.rdbuf()->in_avail(); cin.ignore(bufferSize); cin.getline(s,10); cout << s << endl; return 0; }
true
fa44b10eaf723efb8b1e4ffc480873e04fc5090a
C++
hunterbeebe/Codebreakers
/Game.cpp
UTF-8
23,936
3.59375
4
[]
no_license
#include "Game.h" Game::Game() { dealCards(); dealQuestions(); } int Game::dealCards() { m_deck.shuffle(); // shuffle the deck for (int i = 0; i < 5; i++) { m_human.addCardtoHand(m_deck.draw()); // draw cards for the human } m_human.sortHand(); // sort the humans hand for (int j = 0; j < 5; j++) { m_robot.addCardtoHand(m_deck.draw()); // draw cards for the robot } m_robot.sortHand(); // sort the robots hand std::vector<std::string> humstring = m_human.giveStringHand(); // set up the history function by adding in a recap of every card the player has m_history.push_back("Your cards are " + humstring[0] + ", " + humstring[1] + ", " + humstring[2] + ", " + humstring[3] + ", " + humstring[4]); m_history.push_back("You know the following about your opponent's cards: "); return 1; } int Game::dealQuestions() { m_questions.shuffle(); for (int i = 0; i < 6; i++) { m_availquestions.push_back(m_questions.draw()); // draw the top 6 question cards and get them ready to display } return 1; } void Game::displayboard() { std::vector<card> humanhand = m_human.giveHand(); // Get the players hand and display each value along with color if (showHandOnce == false) { std::cout << "Your cards are: " << std::endl; std::cout << "a) " << humanhand[0].color << " " << humanhand[0].value << std::endl; std::cout << "b) " << humanhand[1].color << " " << humanhand[1].value << std::endl; std::cout << "c) " << humanhand[2].color << " " << humanhand[2].value << std::endl; std::cout << "d) " << humanhand[3].color << " " << humanhand[3].value << std::endl; std::cout << "e) " << humanhand[4].color << " " << humanhand[4].value << std::endl; //std::vector<std::string> robothand = m_robot.giveStringHand(); // (for testing) display the robot's hand as well //std::cout << "The robot's cards are: " << std::endl; //std::cout << "a) " << robothand[0] << std::endl; //std::cout << "b) " << robothand[1] << std::endl; //std::cout << "c) " << robothand[2] << std::endl; //std::cout << "d) " << robothand[3] << std::endl; //std::cout << "e) " << robothand[4] << std::endl; std::cout << std::endl; } showHandOnce = true; std::cout << "The questions you can choose from are: " << std::endl; // list the questions that are available to be asked for (int i = 0; i < 6; i++) { std::cout << i+1 << ") " << m_availquestions[i] << std::endl; } } void Game::humanTakeTurn() { std::string response; response = "0"; //displayboard(); std::cout << std::endl; std::cout << "If you would like to ask a question, type the number of it" << std::endl; // prompt the player with their options std::cout << "Otherwise, if you want to guess, type Guess" << std::endl; std::cout << "Lastly, if you would like a recap of the information you know, type Recap" << std::endl << std::endl; while (response != "1" && response != "2" && response != "3" && response != "4" && response != "5" && response != "6" && response != "Guess" && response != "guess" && response != "recap" && response != "Recap") { // make sure the response is reasonable before continuing std::getline(std::cin, response); } if (response == "Recap" || response == "recap") { std::cout << std::endl << "Your information: " << std::endl; // if they asked for a recap, print out the history member for (auto iterator = m_history.begin(); iterator != m_history.end(); iterator++) { std::cout << *iterator << std::endl; } std::cout << std::endl << std::endl; std::string presstocontinue; std::getline(std::cin, presstocontinue); } else if (response == "Guess" || response == "guess") { if (humanMakeGuess()) { // if they want to make a guess, delegate it to the guess member function and see if they were right humanGotIt = true; } if (!humanGotIt) { std::cout << "Incorrect" << std::endl << std::endl; } } else { std::cout << humanAskQuestion(response) << std::endl << std::endl; /*<< "Press enter to continue" << std::endl;*/ // otherwise, they're asking a question, call that function std::string presstocontinue; std::getline(std::cin, presstocontinue); } } std::string Game::humanAskQuestion(std::string qchoice) { int qnumber = std::stoi(qchoice); std::string qprompt = m_availquestions[qnumber - 1]; m_availquestions[qnumber - 1] = m_questions.draw(); std::cout << "You asked: " + qprompt << std::endl; std::string answer = QuestionResolver(qprompt, m_robot); m_history.push_back(answer); return answer; } bool Game::humanMakeGuess() { std::vector<std::string> robothand = m_robot.giveStringHand(); std::string first; std::string second; std::string third; std::string fourth; std::string fifth; std::cout << "The format of a guess is: 'White 2', 'Green 5', etc." << std::endl; std::cout << "You will enter the guesses one by one, and be told if you are correct at the end." << std::endl; std::cout << "First card: "; std::getline(std::cin, first); std::cout << std::endl; std::cout << "Second card: "; std::getline(std::cin, second); std::cout << std::endl; std::cout << "Third card "; std::getline(std::cin, third); std::cout << std::endl; std::cout << "Fourth card: "; std::getline(std::cin, fourth); std::cout << std::endl; std::cout << "Fifth card: "; std::getline(std::cin, fifth); std::cout << std::endl; std::vector<std::string> guess; guess.push_back(first); guess.push_back(second); guess.push_back(third); guess.push_back(fourth); guess.push_back(fifth); bool correct = true; for (int i = 0; i < 5; i++) { if (guess[i] != robothand[i]) { correct = false; } } return correct; } Player Game::retrieveHuman() { return m_human; } Player Game::retrieveRobot() { return m_robot; } bool Game::didHumanGetIt() { return humanGotIt; } void Game::play() { while (humanGotIt == false) { displayboard(); humanTakeTurn(); } std::cout << std::endl << "You did it!" << std::endl; } std::string QuestionResolver(std::string qprompt, Player target) { std::vector<card> hand = target.giveHand(); std::string answer; if (qprompt == "What is the total sum of your cards?") { int totalsum = 0; for (int i = 0; i < 5; i++) { totalsum += hand[i].value; } answer = "The total sum of the cards is " + std::to_string(totalsum); } if (qprompt == "What is the sum of your leftmost cards?") { int totalsum = 0; for (int i = 0; i < 3; i++) { totalsum += hand[i].value; } answer = "The sum of the leftmost cards is " + std::to_string(totalsum); } if (qprompt == "What is the sum of your middle cards?") { int totalsum = 0; for (int i = 1; i < 4; i++) { totalsum += hand[i].value; } answer = "The sum of the middle cards is " + std::to_string(totalsum); } if (qprompt == "What is the sum of your rightmost cards?") { int totalsum = 0; for (int i = 2; i < 5; i++) { totalsum += hand[i].value; } answer = "The sum of the rightmost cards is " + std::to_string(totalsum); } if (qprompt == "What is the sum of your black cards?") { int totalsum = 0; for (int i = 0; i < 5; i++) { if (hand[i].color == "Black") { totalsum += hand[i].value; } } answer = "The sum of the black cards is " + std::to_string(totalsum); } if (qprompt == "What is the sum of your white cards?") { int totalsum = 0; for (int i = 0; i < 5; i++) { if (hand[i].color == "White") { totalsum += hand[i].value; } } answer = "The sum of the white cards is " + std::to_string(totalsum); } if (qprompt == "How many odd cards do you have?") { int totalodd = 0; for (int i = 0; i < 5; i++) { if (hand[i].value % 2 != 0) { totalodd++; } } answer = "The number of odd cards is " + std::to_string(totalodd); } if (qprompt == "How many even cards do you have?") { int totaleven = 0; for (int i = 0; i < 5; i++) { if (hand[i].value % 2 == 0) { totaleven++; } } answer = "The number of even cards is " + std::to_string(totaleven); } if (qprompt == "Which of your cards are adjacent to a consecutive number?") { for (int i = 0; i < 4; i++) { if (hand[i + 1].value == hand[i].value + 1) { if (i == 0) { answer += "A B "; } if (i == 1) { if (answer == "A B ") { answer = "A B C "; } else { answer += "B C "; } } if (i == 2) { if (answer == "A B C ") { answer = "A B C D "; } else if (answer == "B C") { answer = "B C D "; } else { answer += "C D "; } } if (i == 3) { if (answer == "A B C D ") { answer = "A B C D E "; } else if (answer == "B C D ") { answer = "B C D E "; } else if (answer == "C D ") { answer = "C D E "; } else { answer += "D E "; } } } } if (answer == "") { answer += "There are no cards adjacent to consecutive numbers"; } else { answer += "are adjacent to consecutive numbers"; } } if (qprompt == "How many pairs do you have?") { int totalpairs = 0; for (int i = 0; i < 4; i++) { if (hand[i + 1].value == hand[i].value) { totalpairs++; } } if (totalpairs == 0 || totalpairs == 1) { answer += "There are no pairs"; } else { answer += "There number of pairs is " + std::to_string(totalpairs); } } if (qprompt == "Which adjacent cards of yours are the same color?") { for (int i = 0; i < 4; i++) { if (hand[i].color == hand[i + 1].color) { if (i == 0) { answer += "A and B"; } if (i == 1) { if (answer == "A and B") { answer = "A, B, and C"; } else { answer = "B and C"; } } if (i == 2) { if (answer == "A, B, and C") { answer = "A, B, C, and D"; } else if (answer == "B and C") { answer = "B, C, and D"; } else if (answer == "A and B") { answer = "A and B, C and D"; } else { answer = "C and D"; } } if (i == 3) { if (answer == "A, B, C, and D") { answer = "All of the cards are the same color"; return answer; } else if (answer == "A and B") { answer = "A and B, D and E"; } else if (answer == "A, B, and C") { answer = "A and B, B and C, D and E"; } else if (answer == "B and C") { answer = "B and C, D and E"; } else if (answer == "B, C, and D") { answer = "B and C, D and E"; } else if (answer == "A and B, C and D") { answer = "A and B, C and D, D and E"; } else if (answer == "C and D") { answer = "C and D, D and E"; } else { answer = "D and E"; } } } } if (answer == "") { answer = "There are no adjacent cards that are the same color"; } else { answer += " are the adjacent cards that are the same color"; } } if (qprompt == "How many black cards do you have?") { int blackcards = 0; for (int i = 0; i < 5; i++) { if (hand[i].color == "Black") { blackcards++; } } answer += "The number of black cards is " + std::to_string(blackcards); } if (qprompt == "How many white cards do you have?") { int whitecards = 0; for (int i = 0; i < 5; i++) { if (hand[i].color == "White") { whitecards++; } } answer += "The number of white cards is " + std::to_string(whitecards); } if (qprompt == "How many green cards do you have?") { int greencards = 0; for (int i = 0; i < 5; i++) { if (hand[i].color == "Green") { greencards++; } } answer += "The number of green cards is " + std::to_string(greencards); } if (qprompt == "Where are your 0's?") { if (hand[0].value == 0 && hand[1].value == 0) { answer = "There is a 0 in A and B"; } else if (hand[0].value == 0 && hand[1].value != 0) { answer = "There is a 0 in A"; } else { answer = "There are no 0's"; } } if (qprompt == "Where are your 1's or 2's?") { std::string choice = "0"; std::cout << "1 or 2?" << std::endl; while (choice != "1" && choice != "2") { std::getline(std::cin, choice); } if (choice == "1") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 1) { howmany++; } } if (howmany == 0) { answer = "There are no 1's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 1) { if (j == 0) { answer = "There is a 1 in A"; } if (j == 1) { answer = "There is a 1 in B"; } if (j == 2) { answer = "There is a 1 in C"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 1 && !done) { if (k == 0) { done = true; answer = "There is a 1 in A and B"; } if (k == 1) { done = true; answer = "There is a 1 in B and C"; } if (k == 2) { done = true; answer = "There is a 1 in C and D"; } } } } } if (choice == "2") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 2) { howmany++; } } if (howmany == 0) { answer = "There are no 2's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 2) { if (j == 0) { answer = "There is a 2 in A"; } if (j == 1) { answer = "There is a 2 in B"; } if (j == 2) { answer = "There is a 2 in C"; } if (j == 3) { answer = "There is a 2 in D"; } if (j == 4) { answer = "There is a 2 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 2 && !done) { if (k == 0) { done = true; answer = "There is a 2 in A and B"; } if (k == 1) { done = true; answer = "There is a 2 in B and C"; } if (k == 2) { done = true; answer = "There is a 2 in C and D"; } if (k == 3) { done = true; answer = "There is a 2 in D and E"; } } } } } } if (qprompt == "Where are your 3's or 4's?") { std::string choice = "0"; std::cout << "3 or 4?" << std::endl; while (choice != "3" && choice != "4") { std::getline(std::cin, choice); } if (choice == "3") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 3) { howmany++; } } if (howmany == 0) { answer = "There are no 3's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 3) { if (j == 0) { answer = "There is a 3 in A"; } if (j == 1) { answer = "There is a 3 in B"; } if (j == 2) { answer = "There is a 3 in C"; } if (j == 3) { answer = "There is a 3 in D"; } if (j == 4) { answer = "There is a 3 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 3 && !done) { if (k == 0) { done = true; answer = "There is a 3 in A and B"; } if (k == 1) { done = true; answer = "There is a 3 in B and C"; } if (k == 2) { done = true; answer = "There is a 3 in C and D"; } if (k == 3) { done = true; answer = "There is a 3 in D and E"; } } } } } if (choice == "4") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 4) { howmany++; } } if (howmany == 0) { answer = "There are no 4's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 4) { if (j == 0) { answer = "There is a 4 in A"; } if (j == 1) { answer = "There is a 4 in B"; } if (j == 2) { answer = "There is a 4 in C"; } if (j == 3) { answer = "There is a 4 in D"; } if (j == 4) { answer = "There is a 4 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 4 && !done) { if (k == 0) { done = true; answer = "There is a 4 in A and B"; } if (k == 1) { done = true; answer = "There is a 4 in B and C"; } if (k == 2) { done = true; answer = "There is a 4 in C and D"; } if (k == 3) { done = true; answer = "There is a 4 in D and E"; } } } } } } if (qprompt == "Where are your 5's?") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 5) { howmany++; } } if (howmany == 0) { answer = "There are no 5's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 5) { if (j == 0) { answer = "There is a 5 in A"; } if (j == 1) { answer = "There is a 5 in B"; } if (j == 2) { answer = "There is a 5 in C"; } if (j == 3) { answer = "There is a 5 in D"; } if (j == 4) { answer = "There is a 5 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 5 && !done) { if (k == 0) { done = true; answer = "There is a 5 in A and B"; } if (k == 1) { done = true; answer = "There is a 5 in B and C"; } if (k == 2) { done = true; answer = "There is a 5 in C and D"; } if (k == 3) { done = true; answer = "There is a 5 in D and E"; } } } } } if (qprompt == "Where are your 6's or 7's?") { std::string choice = "0"; std::cout << "6 or 7?" << std::endl; while (choice != "6" && choice != "7") { std::getline(std::cin, choice); } if (choice == "6") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 6) { howmany++; } } if (howmany == 0) { answer = "There are no 6's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 6) { if (j == 0) { answer = "There is a 6 in A"; } if (j == 1) { answer = "There is a 6 in B"; } if (j == 2) { answer = "There is a 6 in C"; } if (j == 3) { answer = "There is a 6 in D"; } if (j == 4) { answer = "There is a 6 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 6 && !done) { if (k == 0) { done = true; answer = "There is a 6 in A and B"; } if (k == 1) { done = true; answer = "There is a 6 in B and C"; } if (k == 2) { done = true; answer = "There is a 6 in C and D"; } if (k == 3) { done = true; answer = "There is a 6 in D and E"; } } } } } if (choice == "7") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 7) { howmany++; } } if (howmany == 0) { answer = "There are no 7's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 7) { if (j == 0) { answer = "There is a 7 in A"; } if (j == 1) { answer = "There is a 7 in B"; } if (j == 2) { answer = "There is a 7 in C"; } if (j == 3) { answer = "There is a 7 in D"; } if (j == 4) { answer = "There is a 7 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 7 && !done) { if (k == 0) { done = true; answer = "There is a 7 in A and B"; } if (k == 1) { done = true; answer = "There is a 7 in B and C"; } if (k == 2) { done = true; answer = "There is a 7 in C and D"; } if (k == 3) { done = true; answer = "There is a 7 in D and E"; } } } } } } if (qprompt == "Where are your 8's or 9's?") { std::string choice = "0"; std::cout << "8 or 9?" << std::endl; while (choice != "8" && choice != "9") { std::getline(std::cin, choice); } if (choice == "8") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 8) { howmany++; } } if (howmany == 0) { answer = "There are no 8's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 8) { if (j == 0) { answer = "There is an 8 in A"; } if (j == 1) { answer = "There is an 8 in B"; } if (j == 2) { answer = "There is an 8 in C"; } if (j == 3) { answer = "There is an 8 in D"; } if (j == 4) { answer = "There is an 8 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 8 && !done) { if (k == 0) { done = true; answer = "There is an 8 in A and B"; } if (k == 1) { done = true; answer = "There is an 8 in B and C"; } if (k == 2) { done = true; answer = "There is an 8 in C and D"; } if (k == 3) { done = true; answer = "There is an 8 in D and E"; } } } } } if (choice == "9") { int howmany = 0; for (int i = 0; i < 5; i++) { if (hand[i].value == 9) { howmany++; } } if (howmany == 0) { answer = "There are no 9's"; } if (howmany == 1) { for (int j = 0; j < 5; j++) { if (hand[j].value == 9) { if (j == 0) { answer = "There is a 9 in A"; } if (j == 1) { answer = "There is a 9 in B"; } if (j == 2) { answer = "There is a 9 in C"; } if (j == 3) { answer = "There is a 9 in D"; } if (j == 4) { answer = "There is a 9 in E"; } } } } if (howmany == 2) { bool done = false; for (int k = 0; k < 5; k++) { if (hand[k].value == 9 && !done) { if (k == 0) { done = true; answer = "There is a 9 in A and B"; } if (k == 1) { done = true; answer = "There is a 9 in B and C"; } if (k == 2) { done = true; answer = "There is a 9 in C and D"; } if (k == 3) { done = true; answer = "There is a 9 in D and E"; } } } } } } if (qprompt == "Is your middle card greater than 4?") { if (hand[2].value > 4) { answer = "The middle card is greater than 4"; } else { answer = "The middle card is not greater than 4"; } } if (qprompt == "What is the difference between your largest and smallest number?") { int diff = hand[4].value - hand[0].value; answer = "The difference between the largest and smallest number is " + std::to_string(diff); } return answer; }
true
5b7481413c2d2a25f454ca46266d98e0fe13711d
C++
RobertoLorenzoAguilar/UsingCorCplusplusFunctions-inPython
/main.cpp
UTF-8
364
3.234375
3
[]
no_license
#include "main.h" #include <iostream> int main(char * path_str) { // Using strcmp() int res = strcmp(path_str, "Santiago & Roberto"); if (res==0) printf("Strings are equal"); else printf("Strings are unequal"); printf("\nValue returned by strcmp() is: %d" , res); return res; }
true
38798960901c0bb342f285c6494dc4fab42c0d73
C++
profrog-jeon/cppcore
/Src/300_Formatter/HelperFunc.cpp
UTF-8
3,014
2.921875
3
[]
permissive
#include "stdafx.h" #include "HelperFunc.h" namespace fmt_internal { ////////////////////////////////////////////////////////////////////////// void TokenToVector(std::tstring& strContext, std::tstring strDelimiter, std::vector<std::tstring>& outTokenVec) { int nOffset = 0; while(nOffset >= 0) { std::tstring strToken = Tokenize(strContext, strDelimiter, nOffset); outTokenVec.push_back(strToken); } } ////////////////////////////////////////////////////////////////////////// void TokenToVector(std::tstring& strContext, const TCHAR cSeperator, const TCHAR cQuotator, std::vector<std::tstring>& outTokenVec) { if( strContext.empty() ) return; size_t tLength = strContext.length(); LPCTSTR pszContext = strContext.c_str(); size_t tLastPos = 0; bool bInsideQuotation = false; size_t i; for(i=0; i<tLength; i++) { if( pszContext[i] == cQuotator ) { if( !bInsideQuotation ) { bInsideQuotation = true; continue; } if( (i+1) < tLength && pszContext[i+1] == cQuotator ) { i++; continue; } bInsideQuotation = false; } if( pszContext[i] == cSeperator ) { if( bInsideQuotation ) continue; outTokenVec.push_back(strContext.substr(tLastPos, i - tLastPos)); tLastPos = i+1; } } outTokenVec.push_back(strContext.substr(tLastPos)); } ////////////////////////////////////////////////////////////////////////// void TokenToVectorByExactDelimiter(std::tstring& strContext, std::tstring strExactDelimiter, std::vector<std::tstring>& outTokenVec) { size_t tOffset = 0; while(1) { size_t tIndex = strContext.find(strExactDelimiter, tOffset); if( std::tstring::npos == tIndex ) break; std::tstring strToken = strContext.substr(tOffset, (int)tIndex - tOffset); tOffset = tIndex + strExactDelimiter.length(); outTokenVec.push_back(strToken); } outTokenVec.push_back(strContext.substr(tOffset)); } ////////////////////////////////////////////////////////////////////////// std::tstring WrapupSpecialChar(std::tstring strValue, TCHAR cSeperator, TCHAR cQuotator) { if( std::tstring::npos == strValue.find(cSeperator) && std::tstring::npos == strValue.find(cQuotator) ) return strValue; TCHAR tzTarget[2] = { cQuotator, 0 }; TCHAR tzReplace[3] = { cQuotator, cQuotator, 0 }; Replace(strValue, tzTarget, tzReplace); return Format(TEXT("\"%s\""), strValue.c_str()); } ////////////////////////////////////////////////////////////////////////// std::tstring StripSpecialChar(std::tstring strValue, TCHAR cSeperator, TCHAR cQuotator) { Trim(strValue); size_t tLength = strValue.length(); if( tLength < 2 ) return strValue; // strip outter quotation if( strValue.at(0) == cQuotator && strValue.at(tLength-1) == cQuotator ) strValue = strValue.substr(1, tLength - 2); TCHAR tzTarget[3] = { cQuotator, cQuotator, 0 }; TCHAR tzReplace[2] = { cQuotator, 0 }; Replace(strValue, tzTarget, tzReplace); return strValue; } }
true
65f2e2f5560e09b9d0c5a0642e5b699ae5c4da78
C++
j-a-h-i-r/Online-Judge-Solutions
/LightOj/1238 - PowerPuffGirls.cpp
UTF-8
1,729
2.515625
3
[]
no_license
#include<iostream> #include<queue> #include<vector> #include<cstdio> using namespace std; int fx[] = {0, 0, 1, -1}; int fy[] = {1, -1, 0, 0}; int bfs(int sx,int sy, char ara[30][30]) { int dis[30][30]; for (int i=0; i<30; i++) { for (int j=0; j<30; j++) dis[i][j] = -1; } queue<int> qx, qy; qx.push(sx); qy.push(sy); dis[sx][sy] = 0; while(!qx.empty()) { int ux = qx.front(); qx.pop(); int uy = qy.front(); qy.pop(); for (int i=0; i<4; i++) { int nx = ux + fx[i]; int ny = uy + fy[i]; if (ara[nx][ny]!='#'&&ara[nx][ny]!='m'&&dis[nx][ny]==-1) { dis[nx][ny] = dis[ux][uy] + 1; qx.push(nx); qy.push(ny); //cout<<"d "<<dis[nx][ny]<<endl; if (ara[nx][ny]=='h') return dis[nx][ny]; } } } } int main() { //freopen("in.txt", "r", stdin); int t, cs=0; cin>>t; while(t--) { int m,n; cin>>m>>n; char ara[30][30]; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cin>>ara[i][j]; //cout<<ara[i][j]; } //cout<<endl; } int ans = -2; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(ara[i][j]=='a'||ara[i][j]=='b' ||ara[i][j]=='c') { ans = max(ans, bfs(i,j,ara) ); } } } cout<<"Case "<<++cs<<": "; cout<<ans<<"\n"; } return 0; }
true
6628f96ceeabf5bce14d56e5795dc66df67f1bfd
C++
ktonon/cog
/spec/fixtures/seeds/lib/trainer.cpp
UTF-8
192
2.90625
3
[ "MIT" ]
permissive
#include "Dog.h" #include <iostream> using namespace std; int main(int argc, char** argv) { Animals::Dog dog; cout << "A dog says: " << dog.speak("hungry!") << endl; return 0; }
true
51aa67ee732a7b0482dfd042382179ddcd1d7a72
C++
15831944/TRiAS
/TRiAS/TRiAS/Fachschalen/Kompakt (Fachschale Gewässer)/GEWBAUM.HXX
ISO-8859-1
15,078
2.59375
3
[]
no_license
// Klassendefinitionen fuer Identifikator-Baum ------------------------------------------ // File: GEWBAUM.HXX #if !defined(_GEWBAUM_HXX) #define _GEWBAUM_HXX class TR_OCL { // In Trias definierte Gew.Klassen private: long _lIdent; long _lMCode; short _isValid; short _iDefine; class TR_OBJTree *_pOBJ; public: // Konstruktor/Destruktor TR_OCL (long Ident, long MCode ,short isValid, TR_OBJTree *pOBJ); ~TR_OCL (void); // ZugriffsFunktionen fr IDBaum friend void _XTENSN_EXPORT *GetID (void *pObj); friend int _XTENSN_EXPORT CmpIDs (void *pObj1, void *pObj2); long &Ident ( void ) { return _lIdent; }; long &MCode ( void ) { return _lMCode; }; TR_OBJTree *OBJ ( void ) { return _pOBJ; }; void StoreObj ( TR_OBJTree *pObj ); void DeleteObj(void); short &Define ( void ) { return _iDefine; } short &isValid ( void ) { return _isValid; } void StoreValidation ( short isValid ) { _isValid = isValid; } void StoreDefinition ( short iDefine ) { _iDefine = iDefine; } }; class TR_OCLTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TR_OCLTree (void); ~TR_OCLTree (void); }; DeclareLock (TR_OCLTree, TR_OCL); // notwendige Klassendefinitionen //-------------------------Objekte -------------------------------- //----------------------------------------------------------------- class TR_OBJ { // TRiAS - Objekte private: long _lObject; char *_pGewNr; char *_pGewName; char *_pBez; long _lLaenge; long _lVon; long _lBis; long _lRechts; long _lHoch; long _lObjectIdent; short _iTyp; public: // Konstruktor/Destruktor TR_OBJ (long Object, char *pGewNr, short iTyp = 0); ~TR_OBJ (void); // ZugriffsFunktionen fr OBJBaum friend void _XTENSN_EXPORT *GetObject (void *pObj); friend int _XTENSN_EXPORT CmpObjects (void *pObj1, void *pObj2); long &Object ( void ) { return _lObject; }; long &ObjectIdent ( void ) { return _lObjectIdent; }; long &Laenge ( void ) { return _lLaenge; }; long &Von ( void ) { return _lVon; }; long &Bis ( void ) { return _lBis; }; long &Rechts ( void ) { return _lRechts; }; long &Hoch ( void ) { return _lHoch; }; short &Typ (void) { return _iTyp;}; char *GewNr ( void ) { return _pGewNr; }; char *GewName ( void ) { return _pGewName; }; char *Bez ( void ) { return _pBez; }; void StoreObjLaenge ( long lLen ); void SetObjectIdent (long); void SetTyp( short iTyp) { _iTyp = iTyp;}; void SpeichernGewaesserNummer ( char *); void SpeichernGewaesserName ( char *); void SpeichernBezeichnung ( char *); void SetIntervall ( long, long ); void SetKoordinate ( long, long ); bool GetIntervall ( long *, long *); }; class TR_OBJTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TR_OBJTree (void); ~TR_OBJTree (void); }; DeclareLock (TR_OBJTree, TR_OBJ); // notwendige Klassendefinitionen ///////////////////////////////////////////////////////////////// //-------------------------Text/Symbol-Objekte -------------------------------- //----------------------------------------------------------------- class TS_OBJ { // TRiAS - Objekte private: long _lObject; long _lStart; long _lEnde; short _iTyp; public: // Konstruktor/Destruktor TS_OBJ (long Object, long lStart, long lEnde); ~TS_OBJ (void); // ZugriffsFunktionen fr OBJBaum friend void _XTENSN_EXPORT *GetTObject (void *pObj); friend int _XTENSN_EXPORT CmpTObjects (void *pObj1, void *pObj2); long &Object ( void ) { return _lObject; }; long &Start ( void ) { return _lStart; }; long &Ende ( void ) { return _lEnde; }; void SetTextInformation(long, long); short &Typ (void) { return _iTyp;}; }; class TS_OBJTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TS_OBJTree (void); ~TS_OBJTree (void); }; DeclareLock (TS_OBJTree, TS_OBJ); // notwendige Klassendefinitionen ///////////////////////////////////////////////////////////////// //---------------------------------------------------------------- class KP_GEW { // Kompakt-Gewaesser private: LPSTR _pGewNr; LPSTR _pGewName; short _iHerkunft; short _iZuordnung; long _lONr; long _lCount; long _lCountKompakt; long _lBeginn; long _lEnde; long _lBeginnKompakt; long _lEndeKompakt; class KP_LATree *_pLA; class KP_LATree *_pPA; class TR_OBJTree *_pOBJ; //-------Hilfsgroesse short _iPos; // n-tes Objekt gleicher GewNr public: // Konstruktor/Destruktor KP_GEW ( GEWAESSER *l, KP_LATree *pLA); ~KP_GEW (void); // ZugriffsFunktionen fr GEW_Baum friend void _XTENSN_EXPORT *GetIdent (void *pObj); friend int _XTENSN_EXPORT CmpIdents (void *pObj1, void *pObj2); char *GewNr (void) { return _pGewNr; }; char *GewName (void) { return _pGewName; }; short &GetPosition ( void ) { return _iPos;}; void SetPosition ( short); long &Beginn (void) { return _lBeginn; }; long &Ende (void ) { return _lEnde; }; long &BeginnKompakt (void) { return _lBeginnKompakt; }; long &EndeKompakt (void ) { return _lEndeKompakt; }; long &Count (void) { return _lCount; }; long &CountKompakt (void ) { return _lCountKompakt; }; void AddCount (void ) { _lCount++; }; void AddCountKompakt (void ) { _lCountKompakt++; }; void TauscheZuKompakt (void ); void TauscheZuTRiAS (void ); void TRiASKompaktAbgleich (void ); void KompaktTRiASAbgleich (void ); void StoreCountKompakt ( long lCount ) { _lCountKompakt = lCount; }; void StoreCount ( long lCount ) { _lCount = lCount; }; void StoreBeginnKompakt ( long lBeginn ) { _lBeginnKompakt = lBeginn; }; void StoreEndeKompakt ( long lEnde ) { _lEndeKompakt = lEnde; }; void SetKompaktLen ( long lLen ); void SetStartEndPunkt ( long,long); void StoreGewName ( char *); long &Objekt (void ) { return _lONr; }; KP_LATree *LA ( void ) { return _pLA; }; KP_LATree *PA ( void ) { return _pPA; }; TR_OBJTree *GetOBJ ( void ) { return _pOBJ; }; void SpeichereLeistung ( KP_LATree * pLA); void SpeicherePunkt ( KP_LATree * pPA); void SetOBJ ( TR_OBJTree *pOBJ); void SpeichereObjekt ( long lONr); void SpeichereObjektLaenge ( long lLen); void SetObjekt ( long lONr); //--------------------------------------------------------------- }; class KPTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor KPTree (void); ~KPTree (void); }; DeclareLock (KPTree, KP_GEW); // notwendige Klassendefinitionen ///////////////////////////////////////////////////////////////// //---------------------------------------------------------------- class KP_GEB { // Kompakt-GewaesserBereiche private: LPSTR _pGewNr; LPSTR _pObjKlasse; LPSTR _pObjBez; short _iIdentNr; short _iLRBeide; long _lONr; long _lPos; long _lBeginn; long _lEnde; double _dFlaeche; public: // Konstruktor/Destruktor KP_GEB ( long lPos, long lONr, FLAECHENANABSCHNITTEN *l); ~KP_GEB (void); // ZugriffsFunktionen fr GEB_Baum friend void _XTENSN_EXPORT *GetArea (void *pObj); friend int _XTENSN_EXPORT CmpAreas (void *pObj1, void *pObj2); char *GewNr (void) { return _pGewNr; }; char *ObjKlasse (void) { return _pObjKlasse; }; char *ObjBez (void) { return _pObjBez; }; short &IdentNr (void) { return _iIdentNr; }; short &LRBeide (void ) { return _iLRBeide; }; long &Beginn (void) { return _lBeginn; }; long &Ende (void ) { return _lEnde; }; long &Pos (void) { return _lPos; }; long &ONr (void) { return _lONr; }; double &Flaeche (void) { return _dFlaeche; }; //--------------------------------------------------------------- }; class KPBTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor KPBTree (void); ~KPBTree (void); }; DeclareLock (KPBTree, KP_GEB); // notwendige Klassendefinitionen //------------------------------------------------------------------ //----------------------LeistungsArten------------------------------ //------------------------------------------------------------------ class KP_LA { // Klasse der KompaktDaten(Leistungen/Bauwerke) private: long _lCount; // Zaehler in der Kette LPSTR _pGewNr; LPSTR _pLeistung; LPSTR _pZuordnung; short _iHerkunft; short _iZuordnung; short _iLinksRechtsMitte; long _lBeginn; long _lEnde; long _lMeterOffen; long _lObjectIdent; double _dKostet; short _iRechnNr; long _lONr; double _dHoehe; LPSTR _pKurzText; LPSTR _pLangText; LPSTR _pComment; // BauwerkeTeil LPSTR _pBauwBez; LPSTR _pBez1; LPSTR _pBez2; long _lHoch; long _lRechts; long _lAnlageNr; double _dBauwHoehe; double _dWasserSpDiff; public: // Konstruktor/Destruktor KP_LA ( long, KOMPAKTDATEN *); ~KP_LA (void); // ZugriffsFunktionen fr IDBaum friend void _XTENSN_EXPORT *GetArt (void *pObj); friend int _XTENSN_EXPORT CmpArts (void *pObj1, void *pObj2); long &Count ( void ) { return _lCount; }; char *Leistung (void) { return _pLeistung; }; long &Beginn (void) { return _lBeginn; }; long &Ende (void) { return _lEnde; }; long &MeterOffen (void) { return _lMeterOffen; }; long &ObjectIdent (void) { return _lObjectIdent; }; short &RechnungsNr (void) {return _iRechnNr; }; double &Hoehe ( void ) { return _dHoehe;}; double &Kosten ( void ) { return _dKostet;}; void SpeichereHoehe ( double dHoehe) { _dHoehe = dHoehe; }; short &Herkunft (void) { return _iHerkunft; }; short &Zuordnung (void) { return _iZuordnung; }; void SpeichereObjekt (long lONr); long &Objekt(void) { return _lONr; }; // Links/Rechts/Mitte short LinksRechtsMitte (void) { return _iLinksRechtsMitte; }; void SetLinksRechtsMitte ( short); //------BauwerksTeil--------------------------------- char *BauwerksBez (void) { return _pBauwBez; }; char *Bezeichner1 (void) { return _pBez1; }; char *Bezeichner2 (void) { return _pBez2; }; long &HochWert (void) { return _lHoch; }; long &RechtsWert (void) { return _lRechts; }; long &AnlageNr (void) { return _lAnlageNr; }; double &BauwerksHoehe (void) { return _dBauwHoehe; }; double &WasserSpiegelDiff ( void ) { return _dWasserSpDiff; }; }; class KP_LATree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor KP_LATree (void); ~KP_LATree (void); }; DeclareLock (KP_LATree, KP_LA); // notwendige Klassendefinitionen //------------------------------------------------------------------ ////////////////////////////////////////////////////////////////////////// class TR_IDM { // In Trias definierte F.Klassen private: long _lIdent; short _iTyp; class TR_IDOTree *_pOBJP; class TR_IDOTree *_pOBJLI; class TR_IDOTree *_pOBJLIA; class TR_IDOTree *_pOBJFI; class TR_IDOTree *_pOBJFIA; public: // Konstruktor/Destruktor TR_IDM (long Ident, short iTyp); ~TR_IDM (void); // ZugriffsFunktionen fr IDBaum friend void _XTENSN_EXPORT *GetIDM (void *pObj); friend int _XTENSN_EXPORT CmpIDMs (void *pObj1, void *pObj2); long &Ident ( void ) { return _lIdent; }; short &Typ(void) { return _iTyp; }; TR_IDOTree *OBJP ( void ) { return _pOBJP; }; TR_IDOTree *OBJLI ( void ) { return _pOBJLI; }; TR_IDOTree *OBJLIA ( void ) { return _pOBJLIA; }; TR_IDOTree *OBJFI ( void ) { return _pOBJFI; }; TR_IDOTree *OBJFIA ( void ) { return _pOBJFIA; }; void StoreObject( long,Relat); void SetTyp( short); void StoreKanteInnen(long); void StoreKanteInAus(long); void StoreFlaecheInnen(long); void StoreFlaecheInAus(long); void StorePunktInnen(long); }; class TR_IDMTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TR_IDMTree (void); ~TR_IDMTree (void); }; DeclareLock (TR_IDMTree, TR_IDM); // notwendige Klassendefinitionen //-------------------------IDO-Objekte -------------------------------- //----------------------------------------------------------------- class TR_IDO { // TRiAS - Objekte private: long _lObject; TR_IDMTree *_pIDM; public: // Konstruktor/Destruktor TR_IDO (long Object); ~TR_IDO (void); // ZugriffsFunktionen fr OBJBaum friend void _XTENSN_EXPORT *GetIDO (void *pObj); friend int _XTENSN_EXPORT CmpIDOs (void *pObj1, void *pObj2); long &Object ( void ) { return _lObject; }; TR_IDMTree *IDM (void) { return _pIDM;}; }; class TR_IDOTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TR_IDOTree (void); ~TR_IDOTree (void); }; DeclareLock (TR_IDOTree, TR_IDO); // notwendige Klassendefinitionen ///////////////////////////////////////////////////////////////// //OKSKlassen //----------------------------------------------------------------- class TR_OKS { // TRiAS - Objekte private: char * _pOKS; ulong _lIdent1; ulong _lIdent2; public: // Konstruktor/Destruktor TR_OKS (char *pOKS, ulong lIdent); ~TR_OKS (void); // ZugriffsFunktionen fr OBJBaum friend void _XTENSN_EXPORT *GetOKS (void *pObj); friend int _XTENSN_EXPORT CmpOKSs (void *pObj1, void *pObj2); char *OKS ( void ) { return _pOKS; }; ulong UIdent1 (void) { return _lIdent1;}; ulong UIdent2 (void) { return _lIdent2;}; void StoreSecondIdent ( ulong lIdent ) { _lIdent2 = lIdent;}; }; class TR_OKSTree : public CTree { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor TR_OKSTree (void); ~TR_OKSTree (void); }; DeclareLock (TR_OKSTree, TR_OKS); // notwendige Klassendefinitionen ///////////////////////////////////////////////////////////////// //------------------------------------------------------------------------- //Datenquellenverwaltung //-------------------ListContainer------------------------------------------ // class fr ObjClass-ListContainer class DATACL { private: // Attribute short _DATATyp; HPROJECT _DATAhPr; char _DATALong[128]; char _DATAShort[128]; public: // Konstruktor/Destruktor DATACL ( short Typ, char * pLong, char *pShort, HPROJECT hPr); ~DATACL (void); // Member char &DATALong ( void ) { return _DATALong[0]; }; char &DATAShort ( void ) { return _DATAShort[0]; }; short &DATATyp ( void ) { return _DATATyp; }; HPROJECT &DATAhPr(void) { return _DATAhPr; }; }; // Verwaltung einer ObjClass-Liste class DATACLList : public CListContainer { protected: void _XTENSN_EXPORT UserDelete (void *pObj); public: // Konstruktor/Destruktor DATACLList (void); ~ DATACLList (void); }; DeclareLock (DATACLList, DATACL); //////////////////////////////////////////////////////////////////////////// //-------------------------------------------------------------------------- #endif // _GEWBAUM_HXX
true
41fb3860d0b5009121d99ca7574c15b8d97b02ad
C++
HersonaREAL/my_cpp_primer_code
/chapter06/611.cpp
UTF-8
273
2.796875
3
[]
no_license
#include<iostream> #include<vector> #include<cctype> #include<stdexcept> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; void reset(int &x){ x = 0; } int main(){ int x; cout<<"x:"; cin>>x; reset(x); cout<<"reset x:"<<x<<endl; }
true
947fd59515d4114d8e8eaa2e97b3c466130a1e34
C++
crstyhs/algoritmos-e-programacao
/lista 1/ex4.cpp
UTF-8
327
2.90625
3
[]
no_license
#include<stdio.h> #include<iostream> int main(){ int A,B,RESTO,QUOCIENTE; printf("insira o dividendo: "); scanf("%d", &A); printf("insira o divisor: "); scanf("%d", &B); QUOCIENTE=A/B; RESTO=A%B; printf("o quociente e: %d\n", QUOCIENTE); printf("o resto e: %d\n", RESTO); system("pause"); return 0; }
true
44a05312cf57fb56d09ea1e733f07f58f593023d
C++
NataliVol4ica/UF-CPP-Pool
/Day05/ex04/Intern.hpp
UTF-8
765
2.625
3
[]
no_license
#ifndef INTERN_HPP # define INTERN_HPP #include "defines.hpp" #include "Form.hpp" #include "PresidentialPardonForm.hpp" #include "RobotomyRequestForm.hpp" #include "ShrubberyCreationForm.hpp" class Intern { public: /* EXCEPTIONS */ class UnknownFormException : public exception { public: UnknownFormException(); UnknownFormException(UnknownFormException const &ref); ~UnknownFormException() throw(); UnknownFormException &operator=(UnknownFormException const &ref); virtual const char* what() const throw(); }; /* CLASS */ Intern(); Intern(Intern const &ref); ~Intern(); Intern &operator=(Intern const &ref); Form *makeForm(string type, string target); private: }; std::ostream &operator<<(std::ostream &o, Intern const &ref); #endif
true
55d02a70cc249396d7cf681e2451abaabdef4eac
C++
neeji/codechef_solution
/codechef/beginner/sort.cpp
UTF-8
1,416
3.046875
3
[]
no_license
#include <iostream> #include <vector> #define ll long long #define ull unsigned long long #define ui unsigned int using namespace std; void merge(vector<int> &a, int start, int mid, int end) { int left = mid - start + 1; int right = end - mid; vector<int> left_part; vector<int> right_part; for (int i = 0; i < left; i++) { left_part.push_back(a[start + i]); } left_part.push_back(INT32_MAX); for (int j = 0; j < right; j++) { right_part.push_back(a[mid + 1 + j]); } right_part.push_back(INT32_MAX); int i = 0, j = 0; for (int k = start; k <= end; k++) { if (left_part[i] < right_part[j] && left_part[i] != INT32_MAX) { a[k] = left_part[i]; i++; } else { a[k] = right_part[j]; j++; } } } void merge_sort(vector<int> &a, int start, int end) { if (start < end) { int mid = (start + end) / 2; merge_sort(a, start, mid); merge_sort(a, mid + 1, end); merge(a, start, mid, end); } } int main(void) { vector<int> arr; int n; cin >> n; for (int i = 0; i < n; i++) { int temp; cin >> temp; arr.push_back(temp); } merge_sort(arr, 0, arr.size() - 1); for (int i = 0; i < arr.size(); i++) { cout << arr[i] << endl; } return 0; }
true
53a8b909315fbb2646b3cc74c4114815d0b958d2
C++
jgabriel98/EcoSimulation
/code_in_C++/Simulation/src/Grid.h
UTF-8
1,881
2.53125
3
[]
no_license
#ifndef GRID_H #define GRID_H #include "SimTypes.h" #include "Helper.h" #include <unordered_map> #include <vector> //#define MAX_CELLS 2566 //#define NUM_FOUNDERS 4 using namespace std; namespace SimEco { class Grid{ public: //Specie *species; vector<Specie> species; //uint speciesSize; //static Cell *cells; static int cellsSize; static Connectivity *connectivityMatrix; //matriz esparça compactada ( ver CUsparse) static MatIdx_2D *indexMatrix; static unordered_map<uint, uint> indexMap; //mapeia indice de linha (normal) para o indice na matriz compactada //troquei int por u_int, pois 50k x 50k dá um valor maior que MAX_INT, mas unsinged int aguenta static uint matrixSize; constexpr static float connThreshold = 0.1f; Grid(uint num_cells, uint num_especies); ~Grid(); void setCells(Cell celulas[], size_t size); //seta as celulas void setCellsConnectivity(Connectivity *adjMatrix, size_t size); //passa a matriz de adjacencia, e lá dentro compacta ela //void setFounders(Specie sp[], size_t sp_num); void addCell(const Cell &novaCelula); //void addCells(const array<Cell, Configuration::MAX_CELLS> &novasCelulas); //pega o vector novasCelulas e copia/passa os elementos para a Grid Cell* getCellat(uint index); //lê a serie climatica das celulas, e retorna o número de celulas lidas static int setCellsClimate(const char *minTemp_src, const char *maxTemp_src, const char *minPptn_src, const char *maxPptn_src, const char *NPP_src, size_t timeSteps); //lê a area de todas as células, e retorna o número de celulas lidas; static int setCellsArea(const char *area_src); //lê a conectividade de todas as celulas, e retorna o número de celulas lidas static int setCellsConnectivity(const char *geo_src, const char *topo_src, const char *rivers_src); }; } #endif
true
b3ce57968dc2adff0d358c7de803c373b57c251d
C++
Nikita-L/Study
/ipt/year_1/cpp_and_cs/labs/labs/2.lab4 (ред.3) (menu)/2.lab2/head.h
UTF-8
10,271
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <typeinfo> #include <windows.h> #include <typeinfo> using namespace std; void menu(); class Worker { protected: string name; int age; string post; int experience; public: Worker() : name("UNKNOWN"), age(0), post("UNKNOWN"), experience(0) { } Worker(string n, unsigned int a, string p, unsigned int exp) : name(n), age(a), post(p), experience(exp) { } Worker(const Worker & w) { name=w.name; age=w.age; post=w.post; experience=w.experience; } virtual ~Worker() { }; virtual void get(); virtual void show() const; void postchange(); void expcompare(Worker, Worker) const; friend ostream& operator <<(ostream& c, Worker& a); friend istream& operator >>(istream& c, Worker& a); string infoname() const; int infoage() const; string infopost() const; int infoexperience() const; void getinfoname(string); void getinfoage(int); void getinfopost(string); void getinfoexperience(int); virtual Worker& operator =(const Worker& a); }; class PrimeWorker : public Worker { private: int quantity; string* bonus; public: PrimeWorker(): quantity(0), bonus(0) { } PrimeWorker(string n, unsigned int a, string p, unsigned int exp, unsigned int q):Worker(n, a, p, exp), quantity(q) { bonus = new string[quantity]; } PrimeWorker(const PrimeWorker & w):Worker(w) { quantity = w.quantity; delete [] bonus; bonus=new string[w.quantity]; for (int i=0;i<w.quantity;i++) bonus[i]=w.bonus[i]; } ~PrimeWorker() { delete [] bonus; } void get(); void show() const; void getbonus(); friend ostream& operator<<(ostream& c, PrimeWorker& w); friend istream& operator>>(istream& c, PrimeWorker& w); int infoquantity() const; string* infobonus() const; void getinfoquantity(int); void getinfobonus(string, int); void getinfoquantity1(); void deleteinfobonus(); void getmass(); PrimeWorker& operator =(const PrimeWorker& a); }; class Base { private: int workersinbase; Worker* baseofworkers; int pworkersinbase; PrimeWorker* baseofpworkers; public: Base(): workersinbase(0), pworkersinbase(0), baseofworkers(0), baseofpworkers(0) { //baseofworkers = new Worker[0]; //baseofpworkers = new PrimeWorker[0]; } Base (const Base & b) { workersinbase=b.workersinbase; delete [] baseofworkers; baseofworkers = new Worker[workersinbase]; for (int i=0; i<workersinbase; i++) baseofworkers[i]=b.baseofpworkers[i]; pworkersinbase=b.pworkersinbase; for (int i=0; i<pworkersinbase; i++) { for (int j=0; j<baseofpworkers[i].infoquantity(); j++) baseofpworkers[i].deleteinfobonus(); } delete [] baseofpworkers; for (int i=0; i<pworkersinbase; i++) { for (int j=0; j<baseofpworkers[i].infoquantity(); j++) baseofpworkers[i].getinfobonus(b.baseofpworkers[i].infobonus()[j], j); //baseofpworkers[i].bonus[j]=b.baseofpworkers[i].bonus[j]; } baseofpworkers=b.baseofpworkers; } ~Base() { delete [] baseofworkers; //for (int i=0; i<pworkersinbase; i++) //{ // for (int j=0; j<baseofpworkers[i].infoquantity(); j++) // baseofpworkers[i].deleteinfobonus(); // //delete [] baseofpworkers[i].bonus; //} delete [] baseofpworkers; } bool getBase(); bool editBase(); bool showBase(); bool postBase(); //bool compareBase() //{ // cout<<endl<<baseofworkers[0]; // system("pause"); //* // system("CLS"); // if (workersinbase==0) // { // cout<< "///////////////////////////////////////////" << endl // << " //" << endl // << "Base of workers is emprty //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << "///////////////////////////////////////////" << endl; // cin.get(); // cin.get(); // return 1; // } // else if (workersinbase==1) // { // cout<< "///////////////////////////////////////////" << endl // << " //" << endl // << "There is just one worker in the base //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << "///////////////////////////////////////////" << endl; // cin.get(); // cin.get(); // return 1; // } // else // { // cout<<endl<<"Enter the post of the first worker: "; // string p1; // cin>>p1; // bool one=0; // bool two=0; // Worker A1; // PrimeWorker B1; // int co=-1; // for (int i=0; i<workersinbase; i++) // { // if ((baseofworkers[i].infopost()==p1)&&(baseofworkers[i].infoname()!="2")) // { // //system("CLS"); // A1=baseofworkers[i]; // co=0; // i=workersinbase; // } // else // { // one=1; // } // if ((baseofpworkers[i].infopost()==p1)&&(baseofpworkers[i].infoname()!="2")) // { // //system("CLS"); // B1=baseofpworkers[i]; // co=1; // i=workersinbase; // } // else // { // two=1; // } // } // //if (B1.infoname()=="UNKNOWN") // //{ // // Worker Q1=A1; // //} // //else if (B1.infoname()!="UNKNOWN") // //{ // // PrimeWorker Q1=B1; // //} // cout<<A1; // system("pause"); // if ((one==1)&&(two==1)) // { // system("CLS"); // cout<< "///////////////////////////////////////////" << endl // << " //" << endl // << "There is no such worker //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << "///////////////////////////////////////////" << endl; // cin.get(); // cin.get(); // return 1; // } // cout<<endl<<"Enter the post of the second worker: "; // string p2; // cin>>p2; // bool one1=0; // bool two1=0; // Worker A2; // PrimeWorker B2; // int co1=-2; // for (int i=0; i<workersinbase; i++) // { // if ((baseofworkers[i].infopost()==p2)&&(baseofworkers[i].infoname()!="2")) // { // //system("CLS"); // A2=baseofworkers[i]; // co1=0; // } // else // { // one1=1; // } // if ((baseofpworkers[i].infopost()==p2)&&(baseofpworkers[i].infoname()!="2")) // { // //system("CLS"); // B2=baseofpworkers[i]; // co1=1; // //baseofpworkers[i].deleteinfobonus(); // //cin>>baseofpworkers[i]; // } // else // { // two1=1; // } // } // //if (B2.infoname()=="UNKNOWN") // //{ // // Worker Q2=A2; // //} // //else if (B1.infoname()!="UNKNOWN") // //{ // // PrimeWorker Q2=B2; // //} // if ((one1==1)&&(two1==1)) // { // system("CLS"); // cout<< "///////////////////////////////////////////" << endl // << " //" << endl // << "There is no such worker //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << " //" << endl // << "///////////////////////////////////////////" << endl; // cin.get(); // cin.get(); // return 1; // } // system("CLS"); // if ((co==co1)&&(co==0)) // { // Worker T; // T.expcompare(A1, A2); // return 0; // } // else if ((co==co1)&&(co==1)) // { // PrimeWorker T1; // T1.expcompare(B1, B2); // return 0; // } // else // { // if (A1.infoname()!="UNKNOWN") // { // if (A1.infoexperience() > B2.infoexperience()) // cout<<endl<<A1.infoname()<<" has more experience than "<<B2.infoname(); // else if (A1.infoexperience() > B2.infoexperience()) // cout<<endl<<B2.infoname()<<" has more experience than "<<A1.infoname(); // else cout<<endl<<A1.infoname()<<" and "<<B2.infoname()<<" has equal years of experience"; // cout<<endl; // return 0; // } // else if (A1.infoname()=="UNKNOWN") // { // if (B1.infoexperience() > A2.infoexperience()) // cout<<endl<<B1.infoname()<<" has more experience than "<<A2.infoname(); // else if (B1.infoexperience() > A2.infoexperience()) // cout<<endl<<A2.infoname()<<" has more experience than "<<B1.infoname(); // else cout<<endl<<B1.infoname()<<" and "<<A2.infoname()<<" has equal years of experience"; // cout<<endl; // return 0; // } // } // }*/ // return 0; //} bool compareBase(); bool showallBase(); };
true
cd1bfebfe0886af15aad30c2a479452e534fb50f
C++
GLUD/GomA
/Arduino/NFC_W_R/reader/reader.ino
UTF-8
2,202
2.59375
3
[]
no_license
#include <SPI.h> #include <MFRC522.h> #define RST_PIN 9 // Configurable, see typical pin layout above #define SS_PIN 10 // Configurable, see typical pin layout above MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance. MFRC522::MIFARE_Key key; /** * Initialize. */ void setup() { Serial.begin(9600); // Initialize serial communications with the PC while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4) SPI.begin(); // Init SPI bus mfrc522.PCD_Init(); // Init MFRC522 card // using FFFFFFFFFFFFh which is the default at chip delivery from the factory for (byte i = 0; i < 6; i++) { key.keyByte[i] = 0xFF; } Serial.println(F("Ingrese Tarjeta")); } /** * Main loop. */ void loop() { // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) return; // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) return; byte sector = 1; byte blockAddr = 6; //Se especifica que bloque se leera _____------______-----______ byte dataBlock[] = { 0x01, 0x02, 0x03, 0x04, // 1, 2, 3, 4, 0x05, 0x06, 0x07, 0x08, // 5, 6, 7, 8, 0x08, 0x09, 0xff, 0x0b, // 9, 10, 255, 12, 0x0c, 0x0d, 0x0e, 0x0f // 13, 14, 15, 16 }; byte trailerBlock = 7; MFRC522::StatusCode status; byte buffer[18]; byte size = sizeof(buffer); Serial.println(F("Datos actuales en el sector:")); mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector); Serial.println(); // Read data from the block Serial.print(F("Cargando dato del bloque ")); Serial.print(blockAddr); Serial.println(F(" ...")); status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(blockAddr, buffer, &size); if (status != MFRC522::STATUS_OK) { Serial.print(F("MIFARE_Read() failed: ")); Serial.println(mfrc522.GetStatusCodeName(status)); } Serial.print(F("Dato en el bloque ")); Serial.print(blockAddr); Serial.println(F(":")); dump_byte_array(buffer, 16); Serial.println(); Serial.println(); } /** * Helper routine to dump a byte array as hex values to Serial. */ void dump_byte_array(byte *buffer, byte bufferSize) { for (byte i = 0; i < bufferSize; i++) { // Serial.print(buffer[i] < 0x10 ? " 0" : " "); // Serial.print(buffer[i], HEX); Serial.write(buffer[i]); } }
true
741e1de1d37ade5e5e6b7072b575dcc8de56d49e
C++
rmros/swagger
/qt5cpp/client/SWGPasswordChangeBody.cpp
UTF-8
2,468
2.578125
3
[]
no_license
#include "SWGPasswordChangeBody.h" #include "SWGHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace Swagger { SWGPasswordChangeBody::SWGPasswordChangeBody(QString* json) { init(); this->fromJson(*json); } SWGPasswordChangeBody::SWGPasswordChangeBody() { init(); } SWGPasswordChangeBody::~SWGPasswordChangeBody() { this->cleanup(); } void SWGPasswordChangeBody::init() { oldPassword = new QString(""); newPassword = new QString(""); key = new QString(""); } void SWGPasswordChangeBody::cleanup() { if(oldPassword != NULL) { delete oldPassword; } if(newPassword != NULL) { delete newPassword; } if(key != NULL) { delete key; } } SWGPasswordChangeBody* SWGPasswordChangeBody::fromJson(QString &json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGPasswordChangeBody::fromJsonObject(QJsonObject &pJson) { setValue(&oldPassword, pJson["oldPassword"], "QString", "QString"); setValue(&newPassword, pJson["newPassword"], "QString", "QString"); setValue(&key, pJson["key"], "QString", "QString"); } QString SWGPasswordChangeBody::asJson () { QJsonObject* obj = this->asJsonObject(); QJsonDocument doc(*obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject* SWGPasswordChangeBody::asJsonObject() { QJsonObject* obj = new QJsonObject(); toJsonValue(QString("oldPassword"), oldPassword, obj, QString("QString")); toJsonValue(QString("newPassword"), newPassword, obj, QString("QString")); toJsonValue(QString("key"), key, obj, QString("QString")); return obj; } QString* SWGPasswordChangeBody::getOldPassword() { return oldPassword; } void SWGPasswordChangeBody::setOldPassword(QString* oldPassword) { this->oldPassword = oldPassword; } QString* SWGPasswordChangeBody::getNewPassword() { return newPassword; } void SWGPasswordChangeBody::setNewPassword(QString* newPassword) { this->newPassword = newPassword; } QString* SWGPasswordChangeBody::getKey() { return key; } void SWGPasswordChangeBody::setKey(QString* key) { this->key = key; } } /* namespace Swagger */
true
c37d04f33bf7df367f315cc143cd83126e849a7d
C++
stamaniorec/playing-with-c-and-cpp
/exercise_problems/sieve_oop.cpp
UTF-8
673
3.46875
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; class Sieve { private: int n; bool array1[100]; public: Sieve(int a) : n(a){}; void init_sieve() { for(int i = 0; i <= n; i++) { array1[i] = true; } } void run_sieve() { array1[0] = array1[1] = false; for(int i = 2; i <= sqrt(n); i++) { if(array1[i]) { for(int j = i + i; j <= n; j += i) { array1[j] = false; } } } } void print_sieve() { for(int i = 0; i <= n; i++) { if(array1[i]) cout << i << endl; } } }; int main(int argc, char const *argv[]) { Sieve sieve(100); sieve.init_sieve(); sieve.run_sieve(); sieve.print_sieve(); return 0; }
true
3527f0fa4635026685e40ab60747cfe41c47a9c3
C++
HTC77/cocos2d-x-Bazooka
/Classes/ParticleSpin.cpp
UTF-8
1,013
2.546875
3
[ "MIT" ]
permissive
#include "ParticleSpin.h" ParticleSpin::ParticleSpin() { spinCounter = 0; } ParticleSpin::~ParticleSpin() { } ParticleSpin* ParticleSpin::create(Vec2 _cp, char* _fileName) { ParticleSpin *pc = new ParticleSpin(); if (pc && pc->initWithFile(_fileName)) { pc->setPosition(_cp); pc->init(); pc->autorelease(); return pc; } CC_SAFE_DELETE(pc); return NULL; } // on "init" you need to initialize your instance bool ParticleSpin::init() { ////////////////////////////// // 1. super init first if ( !Node::init() ) { return false; } gravity = Vec2(0, -0.25); speed.x = CCRANDOM_MINUS1_1() * 2.0f; speed.y = rand() % 3 + 1; return true; } void ParticleSpin::update(float delta) { spinCounter += delta * 4; Vec2 initpos = this->getPosition(); Vec2 finalpos; finalpos.x = initpos.x + speed.x; speed.y += gravity.y; finalpos.y = initpos.y + speed.y + gravity.y; this->setPosition(finalpos); this->setRotation(CC_RADIANS_TO_DEGREES(spinCounter * speed.x)); }
true
9db6dba2cef5fac4c3c16473be53c0e17aaf474c
C++
qq1679781770/Mushroom
/src/latch_manager.hpp
UTF-8
1,118
2.78125
3
[]
no_license
/** * > Author: UncP * > Mail: 770778010@qq.com * > Github: https://www.github.com/UncP/Mushroom * > Description: * * > Created Time: 2016-10-21 16:50:18 **/ #ifndef _LATCH_MANAGER_HPP_ #define _LATCH_MANAGER_HPP_ #include <mutex> #include "shared_lock.hpp" namespace Mushroom { class LatchSet { public: LatchSet():head_(nullptr) { } SharedLock* FindLock(page_id page_no); void PinLock(SharedLock *lk); SharedLock* UnpinLock(); ~LatchSet(); private: SharedLock *head_; }; class LatchManager { public: LatchManager(); void LockShared(page_id page_no); void UnlockShared(page_id page_no); void Lock(page_id page_no); void Unlock(page_id page_no); void Upgrade(page_id page_no); void Downgrade(page_id page_no); ~LatchManager(); private: SharedLock* AllocateFree(page_id id); static const int Max = 16; static const int Hash = 4; static const int Mask = Hash - 1; std::mutex mutex_; SharedLock *free_; std::mutex latch_mutex_[Hash]; LatchSet latch_set_[Hash]; }; } // namespace Mushroom #endif /* _LATCH_MANAGER_HPP_ */
true
4e624dc1f4a258660bf98161d931e951d405b2b6
C++
GUAN-XINGQUAN/LeetCode
/Unclassified/50Anagrams.cpp
UTF-8
1,194
3.515625
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> result; unordered_map<string, int> map; for (unsigned i = 0; i < strs.size(); i++) { string str = strs[i]; sort(str.begin(), str.end()); if (map.count(str) == 0) { map[str] = result.size(); result.push_back({}); } result[map[str]].push_back(strs[i]); } return result; } }; int main() { Solution sol; vector<string> strs = { "eat", "tea", "tan", "ate", "nat", "bat" }; vector<vector<string>> result = sol.groupAnagrams(strs); // Two way to iterate through the vector // Use iterator vector<vector<string>>::iterator outIT = result.begin(); while (outIT != result.end()) { vector<string>::iterator innerIT = (*outIT).begin(); while (innerIT != (*outIT).end()) { cout << *innerIT << ' '; innerIT++; } cout << endl; outIT++; } // Use index //for (int i = 0; i < result.size(); i++) //{ // for (int j = 0; j < result[i].size(); j++) // cout << result[i][j] << '\t'; // cout << endl; //} }
true
a1602c8b33a2c8c658f9c75d745185bc8f243644
C++
wydahai/datastructure_algorithm
/bit_operation/excel_sheet_column_number.cc
UTF-8
1,682
4.5625
5
[]
no_license
/** * 题目:Excel Sheet Column Number * 描述:在Excel中,用A表示第一列,B表示第二列...Z表示第26列,AA表示第27列, * AB表示第28列...依次列推。请写出一个函数,输入用字母表示的列号编码, * 输出它是第几列。 * 分析:这道题实际上考察的是把二十六进制表示成十进制数字,将输入的字符串先 * 转换成字符数组,遍历数组中的每一个字符,用这个字符减去A再加1就是该 * 位对应的十进制数,然后乘以26的相应次方,最后把这些数加起来就是结果 * 了。 * 可能很多人会有疑惑为什么要加1,因为十进制是用0-9表示,那么二十六进 * 制就应该用0-25表示,但是这里是A-Z,就相当于1-26,所以算出来的数需要 * 加1。 */ #include <iostream> #include <cstring> int ExcelSheetNumber(char nums[], int len) { if (!nums || len<=0) { return 0; } int num = 0; for (int idx=0; idx<len; ++idx) { num *= 26; // 字母是26个,所以是26进制 num += nums[idx] - 'A' + 1; } return num; } int main() { char nums1[] = "A"; std::cout << ExcelSheetNumber(nums1, strlen(nums1)) << std::endl; char nums2[] = "Z"; std::cout << ExcelSheetNumber(nums2, strlen(nums2)) << std::endl; char nums3[] = "AA"; std::cout << ExcelSheetNumber(nums3, strlen(nums3)) << std::endl; char nums4[] = "AB"; std::cout << ExcelSheetNumber(nums4, strlen(nums4)) << std::endl; char nums5[] = "AAA"; std::cout << ExcelSheetNumber(nums5, strlen(nums5)) << std::endl; return 0; }
true
4d00c1c1ba90d2f127383cc3e9d7e02ab522efa8
C++
AmberWangjie/qsx_duke_course
/ece551AlgorithmAndDataStructure/classwork/c17/p4/bstset.h
UTF-8
5,230
3.453125
3
[]
no_license
#include"set.h" #include<iostream> template<typename K> class BstSet : public Set<K> { public: int size; ////////////////////////////////////////////////////// class Pair{ public: K key; Pair* left; Pair* right; Pair(const K & in_key, Pair* in_left, Pair* in_right):key(in_key),left(in_left),right(in_right){} }; ////////////////////////////////////////////////////// Pair* root; BstSet():size(0),root(NULL){} ~BstSet(){ size=0; destroy(root); } ////////////////////////////////////////////////////// void destroy(Pair* current){ if(current!=NULL){ destroy(current->left); destroy(current->right); delete current; } } ////////////////////////////////////////////////////// void inorder(Pair* current){ if(current!=NULL){ inorder(current->left); std::cout<<current->key<<" "; inorder(current->right); } } void inorder_print(){ inorder(root); std::cout<<std::endl; } ////////////////////////////////////////////////////// void preorder(Pair* current){ if(current!=NULL){ std::cout<<current->key<<" "; preorder(current->left); preorder(current->right); } } virtual void preorder_print(){ preorder(root); std::cout<<std::endl; } ////////////////////////////////////////////////////// void postorder(Pair* current){ if(current!=NULL){ postorder(current->left); postorder(current->right); std::cout<<current->key<<" "; } } void postorder_print(){ postorder(root); std::cout<<std::endl; } ////////////////////////////////////////////////////// void add_helper(const K &key,Pair* current){ if(key<current->key){ if(current->left==NULL){ current->left=new Pair(key,NULL,NULL); return; } else{ add_helper(key,current->left); return; } } else if(key>current->key){ if(current->right==NULL){ current->right=new Pair(key,NULL,NULL); return; } else{ add_helper(key,current->right); return; } } } void add(const K &key){ if(root==NULL){ root=new Pair(key,NULL,NULL); size++; return; } else{ add_helper(key,root); size++; return; } } ////////////////////////////////////////////////////////////// bool lookup_helper(const K& key,const Pair* current) const{ if(current==NULL){ return false; } else if(current->key==key){ return true; } else if(key<current->key){ return lookup_helper(key,current->left); } else{ return lookup_helper(key,current->right); } } bool contains(const K& key) const { return lookup_helper(key,root); } ////////////////////////////////////////////////////////////// Pair* remove_lookup_helper(const K& key,Pair* current, Pair* father) const{ if(current==NULL){ return NULL; } else if(current->key==key){ return father; } else if(key<current->key){ return remove_lookup_helper(key,current->left,current); } else{ return remove_lookup_helper(key,current->right,current); } } Pair* remove_lookup(const K& key) const { return remove_lookup_helper(key,root,NULL); } ////////////////////////////////////////////////////////////// Pair* right_mostleft(Pair* current, Pair* father){ if(current->left==NULL){ father->right=current->right; return current; } else{ while(current->left!=NULL){ father=current; current=current->left; } father->left=current->right; return current; } } bool branch_check(Pair* father,const K& key){ if(father->left==NULL) return false; else if(father->right==NULL) return true; else if(father->left->key==key) return true; else return false; } void remove(const K& key){ Pair* father=remove_lookup(key); if(father==NULL){ if(root->key!=key) return; } Pair* temp=NULL; Pair* current=NULL; size--; if(father==NULL){ if(root->left==NULL){ temp=root; root=root->right; delete temp; } else if(root->right==NULL){ temp=root; root=root->left; delete temp; } else{ temp=right_mostleft(root->right,root); temp->right=root->right; temp->left=root->left; delete root; root=temp; } } else{ if(branch_check(father,key)){ current=father->left; if(current->left==NULL){ father->left=current->right; delete current; } else if(current->right==NULL){ father->left=current->left; delete current; } else{ father->left=right_mostleft(current,father); father->left->left=current->left; father->left->right=current->right; delete current; } } else{ current=father->right; if(current->left==NULL){ father->right=current->right; delete current; } else if(current->right==NULL){ father->right=current->left; delete current; } else{ father->right=right_mostleft(current,father); father->right->left=current->left; father->right->right=current->right; delete current; } } } } };
true
b9ab0137c15fce95968eed9ce4dd9bc788cba643
C++
hunanhd/pyga
/ga/bpy_wrapper.h
GB18030
592
2.53125
3
[]
no_license
#pragma once #include <boost/python.hpp> using namespace boost; /* boost pythonװһЩ: (1) ַʹconst char* (2) ֵַstd::string (3) ͷֵһ(arrayvectorlist),ijpython::object(һpython) (4) жֵ,ֵʹpython::tuple(pythontupleǶӦ) */ namespace ga { extern int add( int a, int b ); extern python::object test( const char* name, python::object datas ); extern void printf(const char* msg); } // namespace JL
true
b3bd8dfb100554f5290237b98900ac4904036a2f
C++
janplaehn/MinecraftClone
/Jan's Minecraft/halcyon/halcyon/source/halcyon_render_system.cc
UTF-8
18,083
2.59375
3
[]
no_license
// halcyon_render_system.cc #include <halcyon.h> #define HC_ARRAYCOUNT(x) (sizeof(x) / sizeof(x[0])) vertex_format::vertex_format() : stride_(0) , attribute_count_(0) { //for (int i = 0; i < RENDER_SYSTEM_MAX_VERTEX_ATTRIBUTES; i++) for (auto &attrib : attributes_) { attrib = {}; } } void vertex_format::add_attribute(attribute_sematic semantic, attribute_format format, int count, bool normalized) { static int format_sizes[] = { sizeof(float), sizeof(uint8_t), }; HC_ASSERT(attribute_count_ < RENDER_SYSTEM_MAX_VERTEX_ATTRIBUTES); int index = attribute_count_++; attributes_[index].semantic_ = semantic; attributes_[index].format_ = format; attributes_[index].count_ = count; attributes_[index].offset_ = stride_; attributes_[index].normalized_ = normalized; stride_ += count * format_sizes[format]; } // render system static void opengl_error_check() { GLenum err = glGetError(); if (err != GL_NO_ERROR) { HC_ASSERT(!"opengl error code!"); } } static const GLenum gl_texture_format_internal[] = { GL_RGB, GL_RGBA, }; static const GLenum gl_texture_format[] = { GL_RGB, GL_RGBA, }; static const GLenum gl_texture_target[] = { GL_TEXTURE_2D, GL_TEXTURE_CUBE_MAP, }; static const GLenum gl_sampler_filter[] = { GL_NEAREST, GL_LINEAR, GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST_MIPMAP_LINEAR, GL_LINEAR_MIPMAP_NEAREST, GL_LINEAR_MIPMAP_LINEAR, }; static const GLenum gl_sampler_address[] = { GL_CLAMP_TO_EDGE, GL_REPEAT, GL_MIRRORED_REPEAT }; static const GLenum gl_blend_eq[] = { GL_FUNC_ADD, GL_FUNC_SUBTRACT, GL_FUNC_REVERSE_SUBTRACT, GL_MIN, GL_MAX, }; static const GLenum gl_blend_ft[] = { GL_ZERO, GL_ONE, GL_SRC_COLOR, GL_ONE_MINUS_SRC_COLOR, GL_DST_COLOR, GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_CONSTANT_COLOR, GL_ONE_MINUS_CONSTANT_COLOR, GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA, GL_SRC_ALPHA_SATURATE, }; static const GLenum gl_compare_func[] = { GL_NEVER, GL_LESS, GL_EQUAL, GL_LEQUAL, GL_GREATER, GL_NOTEQUAL, GL_GEQUAL, GL_ALWAYS, }; static const GLenum gl_stencil_op[] = { GL_KEEP, GL_ZERO, GL_REPLACE, GL_INCR, GL_INCR_WRAP, GL_DECR, GL_DECR_WRAP, GL_INVERT, }; static const GLenum gl_cull_mode[] = { GL_NONE, GL_BACK, GL_FRONT, GL_FRONT_AND_BACK, }; static const GLenum gl_front_face[] = { GL_CCW, GL_CW, }; static const GLenum gl_primitive_topology[] = { GL_POINTS, GL_LINES, GL_TRIANGLES, }; static const GLenum gl_index_type[] = { GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT, }; static const GLuint gl_index_size[] = { sizeof(uint8_t), sizeof(uint16_t), sizeof(uint32_t), }; static const GLenum gl_attribute_type[] = { GL_FLOAT, GL_UNSIGNED_BYTE, }; static const GLuint gl_attribute_size[] = { sizeof(float), sizeof(char), }; static const GLenum gl_uniform_type[] = { GL_FLOAT, GL_FLOAT_VEC2, GL_FLOAT_VEC3, GL_FLOAT_VEC4, GL_INT, GL_BOOL, GL_SAMPLER_2D, GL_FLOAT_MAT4, }; static const GLuint gl_uniform_size[] = { sizeof(float), sizeof(int), sizeof(int), sizeof(int), sizeof(float) * 16, }; const GLenum gl_buffer_type[] = { GL_ARRAY_BUFFER, GL_ELEMENT_ARRAY_BUFFER, }; const GLenum gl_buffer_access[] = { GL_STATIC_DRAW, GL_STREAM_DRAW, }; const GLenum gl_framebuffer_format_internal[] = { GL_NONE, GL_RGB, GL_RGBA, GL_DEPTH24_STENCIL8, }; const GLenum gl_framebuffer_format[] = { GL_NONE, GL_RGB, GL_RGBA, GL_DEPTH_STENCIL, }; static GLenum gl_framebuffer_type[] = { GL_NONE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_INT_24_8, }; static GLuint gl_vertex_array_object = 0; render_system::render_system() { gl_vertex_array_object = 0; glGenVertexArrays(1, &gl_vertex_array_object); glBindVertexArray(gl_vertex_array_object); opengl_error_check(); } render_system::~render_system() { glBindVertexArray(0); glDeleteVertexArrays(1, &gl_vertex_array_object); } void render_system::get_render_system_info(render_system_info &info) { info.version_ = (const char *)glGetString(GL_VERSION); info.renderer_ = (const char *)glGetString(GL_RENDERER); info.vendor_ = (const char *)glGetString(GL_VENDOR); } bool render_system::create_shader(shader_program &handle, const char *vertex_shader_source, const char *fragment_shader_source) { GLuint vid = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vid, 1, &vertex_shader_source, NULL); glCompileShader(vid); GLuint fid = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fid, 1, &fragment_shader_source, NULL); glCompileShader(fid); GLuint pid = glCreateProgram(); glAttachShader(pid, vid); glAttachShader(pid, fid); glLinkProgram(pid); GLint link_status = 0; glGetProgramiv(pid, GL_LINK_STATUS, &link_status); if (link_status == GL_FALSE) { GLchar vertex_error[1024]; GLchar fragment_error[1024]; GLchar program_error[1024]; glGetShaderInfoLog(vid, sizeof(vertex_error), NULL, vertex_error); glGetShaderInfoLog(fid, sizeof(fragment_error), NULL, fragment_error); glGetProgramInfoLog(pid, sizeof(program_error), NULL, program_error); HC_ASSERT(!"shader program error"); glDetachShader(pid, vid); glDetachShader(pid, fid); glDeleteProgram(pid); } else { handle.id_ = pid; } glDeleteShader(vid); glDeleteShader(fid); opengl_error_check(); return true; } void render_system::destroy_shader(shader_program &handle) { glDeleteProgram(handle.id_); handle.id_ = 0; opengl_error_check(); } bool render_system::create_texture(texture &handle, render_system_texture_format format, int width, int height, const void *data) { GLuint id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 0, // mip level gl_texture_format_internal[format], width, height, 0, gl_texture_format[format], GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); opengl_error_check(); handle.id_ = id; return true; } bool render_system::create_cubemap(texture &handle, render_system_texture_format format, int width, int height, const void *data[6]) { GLuint id = 0; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_CUBE_MAP, id); for (int index = 0; index < 6; index++) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + index, 0, gl_texture_format_internal[format], width, height, 0, gl_texture_format[format], GL_UNSIGNED_BYTE, data[index]); opengl_error_check(); } handle.id_ = id; return true; } void render_system::update_texture(texture &handle, render_system_texture_format format, int width, int height, const void *data) { GLuint id = handle.id_; glBindTexture(GL_TEXTURE_2D, id); glTexImage2D(GL_TEXTURE_2D, 0, gl_texture_format_internal[format], width, height, 0, gl_texture_format[format], GL_UNSIGNED_BYTE, data); glBindTexture(GL_TEXTURE_2D, 0); opengl_error_check(); } void render_system::destroy_texture(texture &handle) { glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &handle.id_); handle.id_ = 0; opengl_error_check(); } bool render_system::create_sampler_state(sampler_state &handle, render_system_sampler_filter filter, render_system_sampler_address_mode addr_u, render_system_sampler_address_mode addr_v, render_system_sampler_address_mode addr_w/* = RENDER_SYSTEM_SAMPLER_ADDRESS_MODE_CLAMP*/) { GLuint id = 0; glGenSamplers(1, &id); glBindSampler(0, id); glSamplerParameteri(id, GL_TEXTURE_MIN_FILTER, gl_sampler_filter[filter]); glSamplerParameteri(id, GL_TEXTURE_MAG_FILTER, filter == RENDER_SYSTEM_SAMPLER_FILTER_NEAREST ? GL_NEAREST : GL_LINEAR); glSamplerParameteri(id, GL_TEXTURE_WRAP_S, gl_sampler_address[addr_u]); glSamplerParameteri(id, GL_TEXTURE_WRAP_T, gl_sampler_address[addr_v]); glSamplerParameteri(id, GL_TEXTURE_WRAP_R, gl_sampler_address[addr_w]); glBindSampler(0, 0); opengl_error_check(); handle.id_ = id; return true; } void render_system::destroy_sampler_state(sampler_state &handle) { glDeleteSamplers(1, &handle.id_); handle.id_ = 0; opengl_error_check(); } bool render_system::create_vertex_buffer(vertex_buffer &handle, render_system_buffer_access access, int size, const void *data) { GLuint id = 0; glGenBuffers(1, &id); glBindBuffer(GL_ARRAY_BUFFER, id); glBufferData(GL_ARRAY_BUFFER, size, data, gl_buffer_access[access]); glBindBuffer(GL_ARRAY_BUFFER, 0); opengl_error_check(); handle.id_ = id; return true; } void render_system::update_vertex_buffer(vertex_buffer &handle, int size, const void *data) { glBindBuffer(GL_ARRAY_BUFFER, handle.id_); glBufferSubData(GL_ARRAY_BUFFER, 0, size, data); glBindBuffer(GL_ARRAY_BUFFER, 0); opengl_error_check(); } void render_system::destroy_vertex_buffer(vertex_buffer &handle) { glDeleteBuffers(1, &handle.id_); handle.id_ = 0; opengl_error_check(); } bool render_system::create_index_buffer(index_buffer &handle, int size, const void *data) { GLuint id = 0; glGenBuffers(1, &id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); opengl_error_check(); handle.id_ = id; return true; } void render_system::destroy_index_buffer(index_buffer &handle) { glDeleteBuffers(1, &handle.id_); handle.id_ = 0; opengl_error_check(); } bool render_system::create_framebuffer(framebuffer &handle, int width, int height, int color_attachment_format_count, const render_system_framebuffer_format *color_attachment_formats, render_system_framebuffer_format depth_attachment_format /* = RENDER_SYSTEM_FRAMEBUFFER_FORMAT_NONE */) { HC_ASSERT(width > 0); HC_ASSERT(height > 0); HC_ASSERT(color_attachment_format_count > 0); HC_ASSERT(color_attachment_format_count < RENDER_SYSTEM_MAX_FRAMEBUFFER_ATTACHMENTS); GLuint id = 0; glGenFramebuffers(1, &id); glBindFramebuffer(GL_FRAMEBUFFER, id); GLuint textures[RENDER_SYSTEM_MAX_FRAMEBUFFER_ATTACHMENTS] = {}; glGenTextures(color_attachment_format_count, textures); int color_attachment_count = 0; int depth_attachment_count = 0; for (int attachment_index = 0; attachment_index < color_attachment_format_count; attachment_index++) { const render_system_framebuffer_format format = color_attachment_formats[attachment_index]; glBindTexture(GL_TEXTURE_2D, textures[attachment_index]); glTexImage2D(GL_TEXTURE_2D, 0, gl_framebuffer_format_internal[format], width, height, 0, gl_framebuffer_format[format], gl_framebuffer_type[format], nullptr); opengl_error_check(); if (format == RENDER_SYSTEM_FRAMEBUFFER_FORMAT_D32) { HC_ASSERT(depth_attachment_count < 1); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, textures[attachment_index], 0); depth_attachment_count++; } else { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + color_attachment_count, GL_TEXTURE_2D, textures[attachment_index], 0); color_attachment_count++; } opengl_error_check(); } GLuint rbo = 0; if (depth_attachment_format != RENDER_SYSTEM_FRAMEBUFFER_FORMAT_NONE) { glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, gl_framebuffer_format_internal[depth_attachment_format], width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); } GLenum complete_status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (complete_status != GL_FRAMEBUFFER_COMPLETE) { HC_ASSERT(false); } opengl_error_check(); handle.width_ = width; handle.height_ = height; handle.id_ = id; handle.depth_attachment_ = rbo; for (int index = 0; index < RENDER_SYSTEM_MAX_FRAMEBUFFER_ATTACHMENTS; index++) { handle.color_attachments_[index] = textures[index]; } GLenum attachment_indices[RENDER_SYSTEM_MAX_FRAMEBUFFER_ATTACHMENTS] = { GL_COLOR_ATTACHMENT0 + 0, GL_COLOR_ATTACHMENT0 + 1, GL_COLOR_ATTACHMENT0 + 2, GL_COLOR_ATTACHMENT0 + 3, }; glDrawBuffers(color_attachment_count, attachment_indices); return true; } void render_system::destroy_framebuffer(framebuffer &handle) { glBindFramebuffer(GL_FRAMEBUFFER, 0); handle.width_ = 0; handle.height_ = 0; glDeleteFramebuffers(1, &handle.id_); handle.id_ = 0; if (handle.depth_attachment_) glDeleteRenderbuffers(1, &handle.depth_attachment_); handle.depth_attachment_ = 0; for (uint32_t index = 0; index < RENDER_SYSTEM_MAX_FRAMEBUFFER_ATTACHMENTS; index++) { if (handle.color_attachments_[index]) { glDeleteTextures(1, handle.color_attachments_ + index); handle.color_attachments_[index] = 0; } } opengl_error_check(); } void render_system::clear(v4 clear_color) { glClearColor(clear_color.r_, clear_color.g_, clear_color.b_, clear_color.a_); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void render_system::set_viewport(int x, int y, int width, int height) { glViewport(x, y, width, height); } void render_system::set_framebuffer(framebuffer &handle) { glBindFramebuffer(GL_FRAMEBUFFER, handle.id_); set_viewport(0, 0, handle.width_, handle.height_); if (!handle.id_) return; } void render_system::set_shader_program(shader_program &handle) { glUseProgram(handle.id_); } void render_system::set_shader_uniform(shader_program &handle, render_system_uniform_type type, const char *name, int count, const void *value) { GLint location = glGetUniformLocation(handle.id_, name); if (location == -1) return; switch (type) { case RENDER_SYSTEM_UNIFORM_TYPE_FLOAT: { glUniform1fv(location, count, (const GLfloat *)value); opengl_error_check(); } break; case RENDER_SYSTEM_UNIFORM_TYPE_VEC2: { glUniform2fv(location, count, (const GLfloat *)value); opengl_error_check(); } break; case RENDER_SYSTEM_UNIFORM_TYPE_VEC3: { glUniform3fv(location, count, (const GLfloat *)value); opengl_error_check(); } break; case RENDER_SYSTEM_UNIFORM_TYPE_VEC4: { glUniform4fv(location, count, (const GLfloat *)value); opengl_error_check(); } break; case RENDER_SYSTEM_UNIFORM_TYPE_INT: case RENDER_SYSTEM_UNIFORM_TYPE_BOOL: case RENDER_SYSTEM_UNIFORM_TYPE_SAMPLER: { glUniform1iv(location, count, (const GLint *)value); opengl_error_check(); } break; case RENDER_SYSTEM_UNIFORM_TYPE_MATRIX: { glUniformMatrix4fv(location, count, GL_FALSE, (const GLfloat *)value); opengl_error_check(); } break; } } void render_system::set_index_buffer(index_buffer &handle) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, handle.id_); opengl_error_check(); } void render_system::set_vertex_buffer(vertex_buffer &handle) { glBindBuffer(GL_ARRAY_BUFFER, handle.id_); opengl_error_check(); } void render_system::set_vertex_format(vertex_format &format) { // note: disable all attributes for (int i = 0; i < RENDER_SYSTEM_MAX_VERTEX_ATTRIBUTES; i++) { glDisableVertexAttribArray(i); } const int vertex_stride = format.stride_; const int attribute_count = format.attribute_count_; for (int attribute_index = 0; attribute_index < attribute_count; attribute_index++) { const vertex_format::attribute &attribute = format.attributes_[attribute_index]; glEnableVertexAttribArray(attribute.semantic_); glVertexAttribPointer(attribute.semantic_, attribute.count_, gl_attribute_type[attribute.format_], attribute.normalized_, vertex_stride, (const void *)(uintptr_t)attribute.offset_); } opengl_error_check(); } void render_system::set_texture(texture &handle, int unit/* = 0 */, render_system_texture_target target/* = RENDER_SYSTEM_TEXTURE_TARGET_TEXTURE_2D*/) { glActiveTexture(GL_TEXTURE0 + unit); glBindTexture(gl_texture_target[target], handle.id_); opengl_error_check(); } void render_system::set_sampler_state(sampler_state &handle, int unit/* = 0 */) { glBindSampler(unit, handle.id_); opengl_error_check(); } void render_system::set_blend_state(bool enabled, render_system_blend_equation eq_rgb, render_system_blend_factor src_rgb, render_system_blend_factor dst_rgb, render_system_blend_equation eq_alpha, render_system_blend_factor src_alpha, render_system_blend_factor dst_alpha) { if (enabled) { glEnable(GL_BLEND); glBlendFuncSeparate(gl_blend_ft[src_rgb], gl_blend_ft[dst_rgb], gl_blend_ft[src_alpha], gl_blend_ft[dst_alpha]); glBlendEquationSeparate(gl_blend_eq[eq_rgb], gl_blend_eq[eq_alpha]); } else { glDisable(GL_BLEND); } opengl_error_check(); } void render_system::set_depth_state(bool write_enabled, bool read_enabled, float range_near/* = -1.0f */, float range_far/* = 1.0f */, render_system_compare_func func/* = RENDER_SYSTEM_COMPARE_FUNC_LESS */) { if (read_enabled) { glEnable(GL_DEPTH_TEST); glDepthFunc(gl_compare_func[func]); if (write_enabled) glDepthMask(GL_TRUE); else glDepthMask(GL_FALSE); } else { glDisable(GL_DEPTH_TEST); //glDepthMask(GL_FALSE); } glDepthRange(range_near, range_far); opengl_error_check(); } void render_system::set_rasterizer_state(render_system_cull_mode cull_mode, render_system_front_face front_face/* = RENDER_SYSTEM_FRONT_FACE_CW */) { if (cull_mode != RENDER_SYSTEM_CULL_MODE_NONE) { glEnable(GL_CULL_FACE); glCullFace(gl_cull_mode[cull_mode]); } else { glDisable(GL_CULL_FACE); } glFrontFace(gl_front_face[front_face]); opengl_error_check(); } void render_system::draw(render_system_primitive_topology topology, int start_index, int primitive_count) { glDrawArrays(gl_primitive_topology[topology], start_index, primitive_count); opengl_error_check(); } void render_system::draw_indexed(render_system_primitive_topology topology, render_system_index_type type, int start_index, int primitive_count) { glDrawElements(gl_primitive_topology[topology], primitive_count, gl_index_type[type], (const void *)(uintptr_t)(gl_index_size[type] * start_index)); opengl_error_check(); }
true
5881bbd2c125f30736a6efc066ecd02a7d592db6
C++
sork777/PortFolio
/Framework/Utilities/Path.h
UTF-8
3,563
2.671875
3
[]
no_license
#pragma once struct DirectoryHierarchy { wstring DirectoryPath; wstring DirectoryName; vector< DirectoryHierarchy> Children; }; class Path { private: static vector<string> TextureFormats; static vector<string> AudioFormats; static vector<string> RawModelDataFormats; static vector<string> MeshFormats; static vector<string> RawModelFormats; static vector<string> ConvertedModelFormats; static vector<string> ConvertedAnimationFormats; static vector<string> MapFormats; public: static bool IsSupportTextureFile(string path); static bool IsSupportTextureFile(wstring path); static bool IsSupportAudioFile(string path); static bool IsSupportAudioFile(wstring path); static bool IsSupportMeshFile(string path); static bool IsSupportMeshFile(wstring path); static bool IsRawModelFile(string path); static bool IsRawModelFile(wstring path); static bool IsConvertedModelFile(string path); static bool IsConvertedModelFile(wstring path); static bool IsConvertedAnimationFile(string path); static bool IsConvertedAnimationFile(wstring path); static bool IsSupportMapFile(string path); static bool IsSupportMapFile(wstring path); public: static void GetDirectoryHierarchy(string path, DirectoryHierarchy* parent); static void GetDirectoryHierarchy(wstring path, DirectoryHierarchy* parent); static bool IsDirectory(string path); static bool IsDirectory(wstring path); public: static bool ExistFile(string path); static bool ExistFile(wstring path); static bool ExistDirectory(string path); static bool ExistDirectory(wstring path); static string Combine(string path1, string path2); static wstring Combine(wstring path1, wstring path2); static string Combine(vector<string> paths); static wstring Combine(vector<wstring> paths); static string GetDirectoryName(string path); static wstring GetDirectoryName(wstring path); static string GetDirectDirectoryName(string path); static wstring GetDirectDirectoryName(wstring path); static string GetExtension(string path); static wstring GetExtension(wstring path); static string GetFileName(string path); static wstring GetFileName(wstring path); static string GetFileNameWithoutExtension(string path); static wstring GetFileNameWithoutExtension(wstring path); public: const static WCHAR* ImageFilter; const static WCHAR* BinModelFilter; const static WCHAR* FbxModelFilter; const static WCHAR* ShaderFilter; const static WCHAR* XmlFilter; const static WCHAR* TextFilter; static void OpenFileDialog(wstring file, const WCHAR* filter, wstring folder, function<void(wstring)> func, HWND hwnd = NULL); static void SaveFileDialog(wstring file, const WCHAR* filter, wstring folder, function<void(wstring)> func, HWND hwnd = NULL); public: static void GetFiles(vector<string>* files, string path, string filter, bool bFindSubFolder, bool bFindDirectSubFolder); static void GetFiles(vector<wstring>* files, wstring path, wstring filter, bool bFindSubFolder, bool bFindDirectSubFolder); static bool IsRelativePath(string path); static bool IsRelativePath(wstring path); static void CreateFolder(string path); static void CreateFolder(wstring path); static void CreateFolders(string path); static void CreateFolders(wstring path); static bool DeleteFolder(const string& path); static bool DeleteFolder(const wstring& path); static bool Delete_File(const string& path); static bool Delete_File(const wstring& path); static bool Copy_File(const string& src, const string& dst); static bool Copy_File(const wstring& src, const wstring& dst); };
true
af6e906b7d0e01d6f6c642554f552fab65b73262
C++
prestonneal/TempleOS-TomAwezome-ZenithOS
/src/Home/Net/NetQueue.CC
UTF-8
2,090
2.9375
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
/* Shrine mentions possibly using two FIFOs (in our case, Queues) for pending and empty frames. If logical to implement, perhaps Zenith NetQueue code should do something similar to that idea. Each Ethernet Frame will be represented as an entry in a CQueue. */ class CNetQueueEntry:CQueue { I64 length; //todo: change to packet_length? U8 frame[ETHERNET_FRAME_SIZE]; }; /* global variable, holds pointer of Ethernet Queue. This acts as the Head of the Queue, Entries act as the Tail of the Queue. Upon QueueInit, ->next and ->last are set to itself, the Head. */ CQueue *net_queue; // no QueueRemove the Head! only Entries! /* PCNet reroutes PCI interrupts to software. See $LK,"PCNet",A="FF:C:/Home/Net/PCNet.CC,I_PCNET0"$. Net Handler interrupt is generated whenever an entry is pushed to the NetQueue. See $LK,"NetHandler",A="FF:C:/Home/Net/NetHandler.CC,I_NETHANDLER"$ */ #define I_PCNET0 I_USER + 0 #define I_PCNET1 I_USER + 1 #define I_PCNET2 I_USER + 2 #define I_PCNET3 I_USER + 3 #define I_NETHANDLER I_USER + 4 #define INT_DEST_CPU 0 U0 NetQueueInit() { net_queue = CAlloc(sizeof(CQueue)); QueueInit(net_queue); } CNetQueueEntry *NetQueuePull() {/* Returns a pointer to a CNetQueueEntry, or NULL pointer if Net Queue is empty. */ CNetQueueEntry *entry; if (net_queue->next != net_queue) { entry = net_queue->next; NetLog("NETQUEUE PULL: Removing entry from queue."); QueueRemove(entry); } else // Queue is empty if head->next is head itself. { entry = NULL; } return entry; } U0 NetQueuePush(U8 *data, I64 length) {/* Pushes a copy of the packet data and length into the Net Queue. The NetQueueEntry is inserted after the last entry of net_queue to keep new items in the back of the Queue, old in front. */ CNetQueueEntry *entry = CAlloc(sizeof(CNetQueueEntry)); entry->length = length; MemCopy(entry->frame, data, length); QueueInsert(entry, net_queue->last); // Generate Net Handler interrupt. NetLog("NETQUEUE PUSH COPY: Generating NetHandler interrupt."); MPInt(I_NETHANDLER, INT_DEST_CPU); } NetQueueInit;
true
a8d91123758870b67df2ccf5e4bc803415967fe0
C++
billtong/data-structure-and-algorithm
/leetcode/1462CourseScheduleIV.cpp
UTF-8
1,582
3.34375
3
[]
no_license
#include "stdafx.h" /** * There are a total of n courses you have to take, labeled from 0 to n-1. * Some courses may have direct prerequisites, for example, to take course 0 you have first to take course 1, which is expressed as a pair: [1,0] * Given the total number of courses n, a list of direct prerequisite pairs and a list of queries pairs. * You should answer for each queries[i] whether the course queries[i][0] is a prerequisite of the course queries[i][1] or not. * Return a list of boolean, the answers to the given queries. * Please note that if course a is a prerequisite of course b and course b is a prerequisite of course c, then, course a is a prerequisite of course c. */ //graph bfs class Solution { public: vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) { vector<vector<bool>> graph(n, vector<bool>(n, false)); vector<bool> ans; queue<int> q; for (auto pair : prerequisites) //read all the prerequisites informations graph[pair[0]][pair[1]] = true; for (int i = 0; i < n; i++) //perfor bfs on every course { for (int j = 0; j < n; j++) //push child nodes of course i into queue if (graph[i][j]) q.push(j); while (!q.empty()) { for (int j = 0; j < n; j++) { if (graph[q.front()][j] && !graph[i][j]) //prevent search unecessary nodes { graph[i][j] = true; q.push(j); } } q.pop(); } } for (auto pair : queries) //iterate queries and get answers ans.push_back(graph[pair[0]][pair[1]]); return ans; } };
true
67b734b9f70153a46829751096cfd59a14118240
C++
armageddon89/AdrianProjects
/Project/GraphMatcher/include/Node.h
UTF-8
2,097
3.25
3
[]
no_license
#pragma once #include "Statistics.h" template <typename N> class Node { public: Node(/* in */ const N &node, /* in */ const std::function<const std::wstring(const N &)> toString = [] (/* in */ const N &n) { return n; }) :m_node(node), m_label(toString(node)), m_bUnknown(false), m_bHasCorrespondent(false), m_bHasAssignment(false), m_correspondent(nullptr), m_bRegex(false) { if (m_label.empty() || m_label.front() == L'?') m_bUnknown = true; } inline const std::wstring GetLabel(void) const { return m_label; } inline void SetUnknown(/* in */ bool bUnknown = true, std::wstring newLabel = L"") { m_bUnknown = bUnknown; m_label = newLabel; } inline bool IsUnknown(void) const { return m_bUnknown; } inline const N& GetNode(void) const { return m_node; } inline bool HasAssignment(void) const { return m_bHasAssignment; } inline void SetAssignment(/* in */ bool bHasAssignment) { m_bHasAssignment = bHasAssignment; } inline bool operator== (/* in */ const Node<N> &other) const { return m_label == other.GetLabel(); } inline bool operator!= (/* in */ const Node<N> &other) const { return m_label != other.GetLabel(); } inline bool IsRegex(void) const { return m_bRegex; } inline void SetRegex(/* in */ std::wstring regex) { m_bRegex = true; m_label = regex; } inline void SetCorespondent(/* in */ bool bCorrespondent, /* in */ const Node<N> *correspondent = nullptr) { m_bHasCorrespondent = bCorrespondent; if (correspondent) m_correspondent = const_cast<Node<N> *>(correspondent); } inline bool HasCorrespondent(void) const { return m_bHasCorrespondent; } inline const Node<N> &GetCorrespondent(void) const { return *m_correspondent; } friend std::wostream& operator<<(/* inout */ std::wostream &stream, /* in */ const Node &n) { stream << n.GetLabel(); return stream; } private: N m_node; std::wstring m_label; bool m_bUnknown; bool m_bHasCorrespondent; bool m_bHasAssignment; Node<N> *m_correspondent; bool m_bRegex; }; typedef Node<std::wstring> CNode; static const CNode NIL = CNode(L"?");
true
5f9f562aea8250d6837acc30f34da4886140824d
C++
maunsell/MWorks
/0.4.3_dev/MonkeyWorksTools/MonkeyWorksStreamUtilities/monkeyWorksStreamUtilities.cpp
UTF-8
11,300
2.578125
3
[]
no_license
/* * monkeyWorksStreamUtilities.cpp * MonkeyWorksMatlab * * Created by David Cox on 12/20/06. * Copyright 2006 MIT. All rights reserved. * */ #include <string> #include "monkeyWorksStreamUtilities.h" double scarab_extract_float(ScarabDatum *datum){ #if __LITTLE_ENDIAN__ return *((double *)(datum->data.opaque.data)); #else int i; unsigned char swap_buffer[sizeof(double)]; unsigned char *datum_bytes = (unsigned char *)datum->data.opaque.data; for(i = 0; i < sizeof(double); i++){ swap_buffer[i] = datum_bytes[sizeof(double) - i - 1]; } return *((double *)swap_buffer); #endif } int getScarabEventCode(ScarabDatum *datum){ ScarabDatum *code_datum = scarab_list_get(datum, SCARAB_EVENT_CODEC_CODE_INDEX); return code_datum->data.integer; } long long getScarabEventTime(ScarabDatum *datum){ ScarabDatum *time_datum = scarab_list_get(datum, SCARAB_EVENT_TIME_INDEX); return time_datum->data.integer; } ScarabDatum *getScarabEventPayload(ScarabDatum *datum){ ScarabDatum *payload_datum = scarab_list_get(datum, SCARAB_EVENT_PAYLOAD_INDEX); return payload_datum; } mxArray *recursiveGetScarabList(ScarabDatum *datum){ int i; //mexPrintf("recursiveGetScarabList"); if(datum->type != SCARAB_LIST){ return NULL; } int n = datum->data.list->size; ScarabDatum **values = datum->data.list->values; mxArray *cell_matrix = mxCreateCellMatrix(1, n); for(i = 0; i < n; i++){ mxArray *mx_datum; if(values[i] != NULL){ switch(values[i]->type){ case SCARAB_INTEGER: mx_datum = mxCreateDoubleScalar((double)values[i]->data.integer); break; case SCARAB_FLOAT: mx_datum = mxCreateDoubleScalar((double)values[i]->data.floatp); break; case SCARAB_FLOAT_OPAQUE: mx_datum = mxCreateDoubleScalar(scarab_extract_float(values[i])); break; case SCARAB_OPAQUE: { char *buffer = scarab_extract_string(values[i]); mx_datum = mxCreateString(buffer); free(buffer); break; } case SCARAB_DICT: mx_datum = recursiveGetScarabDict(values[i]); break; case SCARAB_LIST: mx_datum = recursiveGetScarabList(values[i]); break; default: mx_datum = NULL; break; } if(mx_datum != NULL){ mxSetCell(cell_matrix, i, mx_datum); } } } return cell_matrix; } mxArray *recursiveGetScarabDict(ScarabDatum *datum){ int i; //mexPrintf("recursiveGetScarabDict"); if(datum->type != SCARAB_DICT){ return NULL; } int n = scarab_dict_number_of_elements(datum); ScarabDatum **keys = scarab_dict_keys(datum); ScarabDatum **values = scarab_dict_values(datum); char **fields = (char **) calloc(n, sizeof(char *)); int dictionaries = 0; int lists = 0; int floats = 0; int unknowns = 0; // fix me here for(i = 0; i < n; i++){ if(keys[i]) { switch(keys[i]->type) { case SCARAB_OPAQUE: //mexPrintf(" key is SCARAB_OPAQUE (keys[%d]->type): %d\n", i, keys[i]->type); fields[i] = (char *)scarab_extract_string(keys[i]); break; case SCARAB_DICT: //mexPrintf(" key is SCARAB_DICT (keys[%d]->type): %d\n", i, keys[i]->type); { const char *dictPrefix = "dict"; ++dictionaries; int len = snprintf(0, 0, "%s%d", dictPrefix, dictionaries); char *str = (char *)malloc((len + 1) * sizeof(char)); len = snprintf(str, len + 1, "%s%d", dictPrefix, dictionaries); fields[i]=str; } break; case SCARAB_LIST: //mexPrintf(" key is SCARAB_LIST (keys[%d]->type): %d\n", i, keys[i]->type); { const char *listPrefix = "list"; ++lists; int len = snprintf(0, 0, "%s%d", listPrefix, lists); char *str = (char *)malloc((len + 1) * sizeof(char)); len = snprintf(str, len + 1, "%s%d", listPrefix, lists); fields[i]=str; } break; case SCARAB_FLOAT: case SCARAB_FLOAT_INF: case SCARAB_FLOAT_NAN: case SCARAB_FLOAT_OPAQUE: //mexPrintf(" key is SCARAB_FLOAT (keys[%d]->type): %d\n", i, keys[i]->type); { const char *floatPrefix = "float"; ++floats; int len = snprintf(0, 0, "%s%d", floatPrefix, floats); char *str = (char *)malloc((len + 1) * sizeof(char)); len = snprintf(str, len + 1, "%s%d", floatPrefix, floats); fields[i]=str; } break; case SCARAB_INTEGER: //mexPrintf(" key is SCARAB_INTEGER (keys[%d]->type): %d\n", i, keys[i]->type); { const char *intPrefix = "int"; long long intValue = keys[i]->data.integer; int len = snprintf(0, 0, "%s%lld", intPrefix, intValue); char *str = (char *)malloc((len + 1) * sizeof(char)); len = snprintf(str, len + 1, "%s%lld", intPrefix, intValue); fields[i]=str; } break; default: //mexPrintf(" key is unknown (keys[%d]->type): %d\n", i, keys[i]->type); { const char *unknownPrefix = "unknown"; ++unknowns; int len = snprintf(0, 0, "%s%d", unknownPrefix, unknowns); char *str = (char *)malloc((len + 1) * sizeof(char)); len = snprintf(str, len + 1, "%s%d", unknownPrefix, unknowns); fields[i]=str; } break; } } else { fields[i] = NULL; } } mwSize dims = 1; mwSize ndims = 1; mxArray *struct_array = mxCreateStructArray(ndims, &dims, n, (const char **)fields); for(i = 0; i < n; i++){ mxArray *mx_datum; if(values[i] != NULL){ switch(values[i]->type){ case SCARAB_INTEGER: mx_datum = mxCreateDoubleScalar((double)values[i]->data.integer); break; case SCARAB_FLOAT: mx_datum = mxCreateDoubleScalar((double)values[i]->data.floatp); break; case SCARAB_FLOAT_OPAQUE: mx_datum = mxCreateDoubleScalar(scarab_extract_float(values[i])); break; case SCARAB_OPAQUE: { char *buffer = scarab_extract_string(values[i]); mx_datum = mxCreateString(buffer); free(buffer); break; } case SCARAB_DICT: mx_datum = recursiveGetScarabDict(values[i]); break; case SCARAB_LIST: mx_datum = recursiveGetScarabList(values[i]); break; default: mx_datum = NULL; break; } if(mx_datum != NULL){ mxArray *old_thing = mxGetField(struct_array, 0, fields[i]); if(old_thing){ mxDestroyArray(old_thing); } mxSetField(struct_array, 0, fields[i], mx_datum); } } } for(i = 0; i < n; i++){ if(fields[i]) { free(fields[i]); } } free(fields); return struct_array; } MonkeyWorksTime getMonkeyWorksTime(const mxArray *time) { if(!mxIsNumeric(time)) { return -1; } return (MonkeyWorksTime)mxGetScalar(time); } mxArray *getScarabEventData(ScarabDatum *datum){ if(datum == NULL){ return mxCreateDoubleScalar(0.0); } ScarabDatum *payload = getScarabEventPayload(datum); if(!payload){ return mxCreateDoubleScalar(0.0); } mxArray *retVal; switch(payload->type) { case SCARAB_INTEGER: retVal = mxCreateDoubleScalar(payload->data.integer); break; case SCARAB_FLOAT: retVal = mxCreateDoubleScalar((double)payload->data.floatp); break; case SCARAB_FLOAT_NAN: case SCARAB_FLOAT_OPAQUE: retVal = mxCreateDoubleScalar(scarab_extract_float(payload)); // HACK break; case SCARAB_OPAQUE: { char *buffer = scarab_extract_string(payload); retVal = mxCreateString(buffer); free(buffer); break; } case SCARAB_DICT: retVal = recursiveGetScarabDict(payload); break; case SCARAB_LIST: retVal = recursiveGetScarabList(payload); break; default: retVal = mxCreateDoubleScalar(0.0); break; } return retVal; } mxArray *getCodec(ScarabDatum *datum){ ScarabDatum *codec = getScarabEventPayload(datum); int n_codec_entries = codec->data.dict->tablesize; ScarabDatum **keys = scarab_dict_keys(codec); const char *codec_field_names[] = {"code", "tagname", "logging", "defaultvalue", "shortname", "longname", "editable", "nvals", "domain", "viewable", "persistant"}; // more to come later? int n_codec_fields = 11; mwSize codec_size = n_codec_entries; mxArray *codec_struct = mxCreateStructArray(1, &codec_size, n_codec_fields, codec_field_names); for(int c = 0; c < n_codec_entries; ++c){ if(keys[c]) { int code = keys[c]->data.integer; ScarabDatum *serializedVar = scarab_dict_get(codec, keys[c]); mxSetField(codec_struct, c, "code", mxCreateDoubleScalar(code)); if(serializedVar && serializedVar->type == SCARAB_DICT) { for(int d = 0; d < serializedVar->data.dict->tablesize; ++d) { ScarabDatum **varKeys = scarab_dict_keys(serializedVar); if(varKeys[d]) { char *buffer = scarab_extract_string(varKeys[d]); ScarabDatum *varValue = scarab_dict_get(serializedVar, varKeys[d]); if(varValue == NULL){ } else if(varValue->type == SCARAB_INTEGER){ mxSetField(codec_struct, c, buffer, mxCreateDoubleScalar(varValue->data.integer)); } else if(varValue->type == SCARAB_OPAQUE){ char *val = scarab_extract_string(varValue); mxSetField(codec_struct, c, buffer, mxCreateString(val)); } free(buffer); } } } } } return codec_struct; } int insertDatumIntoEventList(mxArray *eventlist, const int index, ScarabDatum *datum){ long code = getScarabEventCode(datum); long long time = getScarabEventTime(datum); mxArray *data; data = getScarabEventData(datum); mxArray *old_code = mxGetField(eventlist, index, "event_code"); if(old_code != NULL){ mxDestroyArray(old_code); } mxSetField(eventlist, index, "event_code", mxCreateDoubleScalar((double)code)); mxArray *old_time = mxGetField(eventlist, index, "time_us"); if(old_time != NULL){ mxDestroyArray(old_time); } mxSetField(eventlist, index, "time_us", mxCreateDoubleScalar((double)time)); mxArray *old_data = mxGetField(eventlist, index, "data"); if(old_data){ mxDestroyArray(old_data); } mxSetField(eventlist, index, "data", data); return code; } int insertDatumIntoCodecList(mxArray *eventlist, const int index, ScarabDatum *datum){ long code = getScarabEventCode(datum); if(code == 0) { long long time = getScarabEventTime(datum); mxArray *data; data = getCodec(datum); mxArray *old_time = mxGetField(eventlist, index, "time_us"); if(old_time != NULL){ mxDestroyArray(old_time); } mxSetField(eventlist, index, "time_us", mxCreateDoubleScalar((double)time)); mxArray *old_data = mxGetField(eventlist, index, "codec"); if(old_data){ mxDestroyArray(old_data); } mxSetField(eventlist, index, "codec", data); } else { //mexErrMsgTxt("Trying to insert a datum that isn't a codec"); } return code; } std::string getString(const mxArray *string_array_ptr) { // Allocate enough memory to hold the converted string. mwSize buflen = mxGetNumberOfElements(string_array_ptr) + 1; char *buf = (char *)mxCalloc(buflen, sizeof(char)); // Copy the string data from string_array_ptr and place it into buf. if (mxGetString(string_array_ptr, buf, buflen) != 0) { mxFree(buf); return std::string(); } std::string new_string(buf); mxFree(buf); return new_string; }
true
558fbeaf7533df222e1ec2d395b10d240b2e88ad
C++
DISTRHO/DISTRHO-Ports
/ports-juce5/drowaudio-common/dRowAudio_TappedDelayLine.h
UTF-8
5,021
2.875
3
[]
no_license
/* * dRowAudio_TappedDelayLine.h * * Created by David Rowland on 13/04/2009. * Copyright 2009 dRowAudio. All rights reserved. * */ #ifndef _DROWAUDIO_TAPPEDDELAYLINE_H_ #define _DROWAUDIO_TAPPEDDELAYLINE_H_ #include "includes.h" // #include "../../utility/dRowAudio_Utility.h" // #include "../dRowAudio_AudioUtility.h" struct Tap { int delaySamples; int originalDelaySamples; int sampleRateWhenCreated; float tapGain; float tapFeedback; float originalTapFeedback; /* float tapPan; float tapHPCutoff; float tapLPCutoff; */ }; class TappedDelayLine { public: /** Creates a TappedDelayline with a given size in samples. If no size is specified a default of 9600 is used. */ TappedDelayLine(int initialBufferSize =96000); TappedDelayLine(float bufferLengthMs, double sampleRate); /// Destructor ~TappedDelayLine(); /** Adds a tap to the delay line at a given number of samples. This will not make a note of the current sample rate being used unless you explecity specify it. Use addTap(int newTapPosMs, double sampleRate) if you need the delay to be dependant on time. */ void addTap(int noDelaySamples, int sampleRate =0); /** Adds a tap to the delay line at a given time. If the sample rate changes make sure you call updateDelayTimes() to recalculate the number of samples for the taps to delay by. */ void addTapAtTime(int newTapPosMs, double sampleRate); /** Moves a specific tap to a new delay position. This will return true if a tap was actually changed. */ bool setTapDelayTime(int tapIndex, int newTapPosMs, double sampleRate); /** Changes the number of samples a specific tap will delay. This will return true if a tap was actually changed. */ bool setTapDelaySamples(int tapIndex, int newDelaySamples); /** Scales the spacing between the taps. This value must be greater than 0. Values < 1 will squash the taps, creating a denser delay, values greater than 1 will expand the taps spacing creating a more sparse delay. The value is used as a proportion of the explicitly set delay time. This is simpler than manually setting all of the tap positions. */ void setTapSpacing(float newSpacingCoefficient); /** This has the same effect as setTapSpacing() but does not check to see if the coeficient has changed so will always update the spacing. */ void setTapSpacingExplicitly(float newSpacingCoefficient); /** Scales all of the taps feedback coeficients in one go. This should be between 0 and 1 to avoid blowing up the line. The value is a proportion of the explicitly set feedback coefficient for each tap so setting this to 1 will return them all to their default. */ void scaleFeedbacks(float newFeedbackCoefficient); /** Returns an array of sample positions where there are taps. This can then be used to remove a specific tap. */ Array<int> getTapSamplePositions(); /** Removes a tap at a specific index. Returns true if a tap was removed. */ bool removeTapAtIndex(int tapIndex); /** Removes a tap with a specific delay samples. Returns true if a tap was revoved, false otherwise. */ bool removeTapAtSample(int sampleForRemovedTap); /** Attempts to remove a tap at a specific time. Returns true if a tap was revoved, false otherwise. */ bool removeTapAtMs(int timeMsForRemovedTap, int sampleRate); /** Removes all the taps. */ void removeAllTaps(); /** Updates the delay samples of all the taps based on their time. Call this if you change sample rates to make sure the taps are still positioned at the right time. */ void updateDelayTimes(double newSampleRate); /** Resizes the buffer to a given number of samples. This will return the number of taps that have been removed if they overrun the new buffer size. */ int setBufferSize(int noSamples); /** Resizes the buffer to a size given the time and sample rate. This will return the number of taps that have been removed if they overrun the new buffer size. */ int setBufferSize(int timeMs, double sampleRate); /// Returns the current size in samples of the buffer. int getBufferSize() { return bufferSize; } /// Returns the current length in milliseconds of the buffer for a given sample rate. int getBufferLengthMs(double sampleRate) { return bufferSize * sampleRate; } /// Returns the number of taps currently being used. int getNumberOfTaps() { return readTaps.size(); } /// Processes a single sample returning a new sample with summed delays. float processSingleSample(float newSample) throw(); /// Processes a number of samples in one go. void processSamples(float* const samples, const int numSamples) throw(); private: CriticalSection processLock; float *pfDelayBuffer; int bufferSize, bufferWritePos; float inputGain, feedbackGain; int noTaps; Array<Tap> readTaps; float spacingCoefficient, feedbackCoefficient; void initialiseBuffer(int bufferSize); JUCE_LEAK_DETECTOR (TappedDelayLine); }; #endif //_DROWAUDIO_TAPPEDDELAYLINE_H_
true
0def44d019e3576f8c882d9ebbb4918c8d563c68
C++
killf/leetcode_cpp
/src/0171.cpp
UTF-8
349
3.03125
3
[ "MIT" ]
permissive
#include <iostream> #include <string> #include <vector> #include <sstream> #include <algorithm> using namespace std; class Solution { public: int titleToNumber(string s) { int sum = 0, m = 1; for (int i = s.size() - 1; i >= 0; i--) { int c = s[i] - 'A' + 1; sum += m * c; if (i > 0)m *= 26; } return sum; } };
true
a5b70de29f8a138b163bac92c6e6744ecce9c907
C++
SotaLuciano/Library
/Code/2. ArraySortSumLine/functions.cpp
UTF-8
848
3.15625
3
[]
no_license
#include<iostream> #include "functions.h" using namespace std; void matrixInput(int** a, int n, int m) { cout << "Enter matrix: " << "\n"; for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) { cout << "A[" << i << "][" << j << "]= "; cin >> a[i][j]; cout << "\n"; } } void matrixSum(int** a, int* sum, int n, int m) { for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) sum[i] = sum[i] + a[i][j]; } void matrixSort(int** a, int* sum, int n) { int* c; for(int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (sum[i]>sum[j]) { c = *&a[i]; *&a[i] = *&a[j]; *&a[j] = c; } } void matrixPrint(int** a, int n, int m) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { cout << "A[" << i << "][" << j << "]= " << (*&a[i][j]); cout << "\t"; } cout << "\n"; } } //By Nazar
true
4f4b47710bab3f602263175b63fdd2d1411d7c85
C++
hjarmstrong/cs247
/model/Model.h
UTF-8
898
2.609375
3
[]
no_license
#ifndef MVC_MODEL_H #define MVC_MODEL_H #include "subject.h" #include <Card.h> #include <Game.h> #include <Player.h> #include <Table.h> #include <sstream> #include <string> class Model : public Subject { public: // Constructor Model(); // GUI event handelers void newGame(int seed, bool*); void endGame(); void ragequit(); void select(Card); void nextHuman(); // Data access for view // Flushes the dialog messages and returns them const std::vector<std::string> dialogMessages(); // Accessors const Table *currentTable() const; const std::vector<Card *> &hand() const; const std::vector<Card> legalCards() const; const std::string currentPlayer() const; const std::string currentAction() const; std::string *currentScoreBoard() const; private: Game *currentGame; std::stringstream events; }; #endif
true
eba47b73cf64ff0975d5dbd16491f90473390197
C++
frankiescott/coursework
/CS 240/Project 3/LLC.h
UTF-8
566
2.96875
3
[]
no_license
#include <string> using namespace std; struct Node { string data; Node* next; }; class LLC { public: LLC(); LLC(const LLC &source); ~LLC(); bool insert(const string &s); void head(int n); friend ostream& operator<<(ostream &os, const LLC &list); int len(); bool contains(const string &s); string tail(); bool remove(const string &s); bool join(LLC other); LLC& operator+=(const int &n); LLC& operator=(const LLC &source); LLC operator+(const LLC &rightlist); void shuffle(); private: Node *first; Node *last; int size; };
true
7b6a4a347ad33aaa2c0d4095ee36413c66a82a8d
C++
olalatr-js/LeetCodeTasks
/LeetCodeTasks/ClimbingStairs.cpp
UTF-8
800
3.25
3
[]
no_license
#include <cassert> namespace { class Solution { public: int climbStairs(int n) { m_N = n; m_res = 0; recursive(1); recursive(2); return m_res; } private: void recursive(int count) { if (count > m_N) return; if (count == m_N) { ++m_res; return; } recursive(count + 1); recursive(count + 2); } int m_N; int m_res; }; } void ClimbingStairs() { Solution sol; auto n = 2; auto res = sol.climbStairs(n); assert(res == 2); n = 3; res = sol.climbStairs(n); assert(res == 3); n = 17; res = sol.climbStairs(n); assert(res == 2584); n = 40; res = sol.climbStairs(n); assert(res == 165580141); }
true
d73d24ef36cf977ac5529a73cee4fb32c74cf853
C++
Lbardoux/file_io
/src/file_io.hpp
UTF-8
3,127
3.484375
3
[]
no_license
/** * @brief This file provides some simple functions to read files with * the *stream libraries from C++ standard * @example example.cpp * @author MTLCRBN * @version 1.0 */ #ifndef FILE_IO_HPP_INCLUDED #define FILE_IO_HPP_INCLUDED #include <fstream> #include <sstream> #include <string> #include <vector> #if defined(__GNUC__) && !defined(NONNULL) //! @brief USAGE : void func_name(args) NONNULL((index0, index1, etc)) #define NONNULL(argNumbers) __attribute__((nonnull (argNumbers))) #else #define NONNULL(argNumbers) #endif #ifndef DECLSPEC #if defined(__WIN32__) || defined(__WINRT__) #define DECLSPEC __declspec(dllexport) #else #if defined(__GNUC__) && __GNUC__ >= 4 #define DECLSPEC __attribute__((visibility("default"))) #elif defined(__GNUC__) && __GNUC__ >= 2 #define DECLSPEC __declspec(dllexport) #else #define DECLSPEC #endif #endif #endif /** * @brief An input file wrapper class. * * You could use it with a fstream or an ifstream. * It doesn't not make sense to try with a ofstream. */ template<typename FileType=std::ifstream> class File final { private: FileType file; public: //! @brief This function is forbidden File(void) = delete; /** * @brief The only constructor, which open \a fname. * @param[in] fname The path to the file you want to open, relative or absolute * @throw std::string If this function was unable to open \a fname. */ File(const std::string &fname) { this->file.open(fname.c_str()); if (!this->file.good()) { throw std::string("Error while opening ") + fname; } } //! @brief Close the internal file. ~File(void) { this->file.close(); } /** * @brief Try to get a Container of TypeValueToRead from a single line of the internal file. * @code * * @endcode * @throw std::string When there is no more line to read. * @return An empty container if the line doesn't contain the required value type, a full vector otherwise. */ template<typename TypeValueToRead, template<typename...> class Container=std::vector> Container<TypeValueToRead> readFromLine(void) { std::string line; Container<TypeValueToRead> container; if (!std::getline(this->file, line)) { throw std::string("No more line to read !"); } std::stringstream s(line); TypeValueToRead value; while (s >> value) { container.push_back(value); } return container; } //! @return the internal file as a reference. FileType& getFile(void) { return this->file; } }; /** * @brief Get the absolute name of \a nameFromRoot, using \a argv0, and storing the result * on \a out. * @throw std::string if an error occurs. * * @param[in] nameFromRoot Considering the root of your project tree, the relative path to get your file. * @param[in] argv0 the first argument of the program (argv[0]). * @param[out] out The storage place for the result. * @return A reference on \a out. */ DECLSPEC std::string& getFullNameOfFile(const std::string &nameFromRoot, const char *const argv0, std::string &out) NONNULL((2)); #endif
true
a1cbc2fa89fe5ac8032c803be949d1f29a29fbfa
C++
Lreneee/IROB
/PotmeterLed/PotmeterLed.ino
UTF-8
656
2.515625
3
[]
no_license
int potPin = A0; int ledPin = 13; int val = 0; int newVal = 0; int difference = 0; String offset = "Hoog"; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); } void loop() { val = analogRead(potPin); if(val > 510 && offset!="Hoog"){ Serial.println("Hoog"); offset = "Hoog"; } else if(val <490 && offset!="Laag"){ Serial.println("Laag"); offset = "Laag"; } Serial.println(analogRead(potPin)); newVal = analogRead(potPin); difference = newVal - val; digitalWrite(ledPin, HIGH); delay(val); digitalWrite(ledPin, LOW); delay(val); }
true
6980022408f3ff2224b0061035f5fd378cd15273
C++
Abhishek-s-1902/C_codes
/assign 5/backup/SAE.cpp
UTF-8
2,822
3.265625
3
[]
no_license
#include "SAE.h" #include <cmath> SAE::SAE(float x1,float x2) { a = x1*12; b = x2; inches = a+b; degree = 1; } float SAE::getInches() const{ return inches; } float SAE::putInches(float inches) { return this->inches = inches; } SAE SAE::operator +( SAE S1){ SAE S2(0,0); float inches = this->getInches() + S1.getInches(); // cout<<"in add"<<inches<<endl; S1.putInches(inches); return S1; } SAE SAE::operator -( SAE S1){ SAE S2(0,0); float inches = this->getInches() - S1.getInches(); // cout<<"in add"<<inches<<endl; S1.putInches(inches); return S2; } SAE SAE::operator *(SAE S_mul ){ SAE S1(0,0); float inches = this->getInches() * S_mul.getInches(); S1.putInches(inches); S1.degree = this->degree+S_mul.degree; cout<<"s mul.degree"<< S1.degree<<endl; return S1; } SAE SAE::operator /(SAE S_div ){ SAE S1(0,0); float inches = this->getInches() / S_div.getInches(); S1.degree = this->degree-S_div.degree; cout<<"s div.degree"<< S1.degree<<endl; if(inches<1||S1.degree<1){ throw underflow_error("Not enough dimensions"); } else{ S1.putInches(inches); return S1;} } SAE SAE::operator *(float S_mul){ SAE S1(0,0); float inches = this->getInches() *S_mul ; S1.putInches(inches); return S1; } SAE SAE::operator /(float S_div){ SAE S1(0,0); float inches = this->getInches()/S_div ; cout<<"scal div: "<<inches<<endl; S1.putInches(inches); return S1; } void SAE::operator +=(SAE S_div){ //SAE S1(0,0); float inches = this->getInches() + S_div.getInches() ; this->putInches(inches); //cout<<"this:+="<<inches<<endl; } void SAE::operator -=(SAE S_div){ float inches = this->getInches() - S_div.getInches() ; this->putInches(inches); //cout<<"this:+="<<inches<<endl; } void SAE::operator *=(SAE S_mul){ float inches = this->getInches() * S_mul.getInches() ; this->degree = S_mul.degree+1; cout<<"s1.degree"<< this->degree<<endl; this->putInches(inches); //cout<<"this:+="<<inches<<endl; } void SAE::operator /=(SAE S_div){ float inches = this->getInches() / S_div.getInches() ; this->degree = this->degree-S_div.degree; cout<<"s1.degree"<< this->degree<<endl; if(inches<1||this->degree<1){ throw underflow_error("Not enough dimensions"); } this->putInches(inches); //cout<<"this:+="<<inches<<endl; } std::ostream& operator<<(std::ostream& os, const SAE S_out){ ostringstream osstr ; if(S_out.degree>1){ int degreetoDiv = pow(12,S_out.degree); os << setw(2)<<setfill('0') <<"inches :"<<S_out.getInches()/degreetoDiv<<" feet^"<<S_out.degree; } else { float in_feet = S_out.getInches()/12; //float mod_inches = S_out.getInches()-(int)in_feet; os << (int)in_feet<<" feet "<<(in_feet- (int)in_feet)*12<<" inches"; } return os; //cout<<"operator<<"<<endl; }
true
b97e58b26726c92c6054d02248a81bbd65ab7609
C++
Mirjang/BA_PointClouds
/LoD4ptC/src/lod/LodUtils.cpp
UTF-8
3,670
2.53125
3
[]
no_license
#include "LodUtils.h" namespace LOD_Utils { VertexBuffer createVertexBufferFromNode(NestedOctreeNode<Vertex>* pNode, ID3D11Device* device) { HRESULT result; ID3D11Buffer* vbuffer = nullptr; //create vertex buffer D3D11_BUFFER_DESC descVertexBuffer; ZeroMemory(&descVertexBuffer, sizeof(D3D11_BUFFER_DESC)); descVertexBuffer.Usage = D3D11_USAGE_DEFAULT; descVertexBuffer.ByteWidth = pNode->data.size() * sizeof(Vertex); descVertexBuffer.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA dataVertexBuffer; ZeroMemory(&dataVertexBuffer, sizeof(D3D11_SUBRESOURCE_DATA)); dataVertexBuffer.pSysMem = pNode->data.data(); result = device->CreateBuffer(&descVertexBuffer, &dataVertexBuffer, &vbuffer); if (FAILED(result)) { std::cout << "failed to create vertex buffer " << result << std::endl; std::cin.get(); } return VertexBuffer(vbuffer, pNode->data.size()); } EllipticalVertexBuffer createSphereVertexBufferFromNode(NestedOctreeNode<SphereVertex>* pNode, ID3D11Device* device) { float boundingSphere =0; for (auto vert : pNode->data) { boundingSphere = max(boundingSphere, vert.radius); } HRESULT result; ID3D11Buffer* vbuffer = nullptr; //create vertex buffer D3D11_BUFFER_DESC descVertexBuffer; ZeroMemory(&descVertexBuffer, sizeof(D3D11_BUFFER_DESC)); descVertexBuffer.Usage = D3D11_USAGE_DEFAULT; descVertexBuffer.ByteWidth = pNode->data.size() * sizeof(SphereVertex); descVertexBuffer.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA dataVertexBuffer; ZeroMemory(&dataVertexBuffer, sizeof(D3D11_SUBRESOURCE_DATA)); dataVertexBuffer.pSysMem = pNode->data.data(); result = device->CreateBuffer(&descVertexBuffer, &dataVertexBuffer, &vbuffer); if (FAILED(result)) { std::cout << "failed to create vertex buffer " << result << std::endl; std::cin.get(); } return EllipticalVertexBuffer(vbuffer, pNode->data.size(), boundingSphere); } EllipticalVertexBuffer createEllipsisVertexBufferFromNode(NestedOctreeNode<EllipticalVertex>* pNode, ID3D11Device* device) { XMVECTOR boundingSphere = XMVectorZero(); for (auto vert : pNode->data) { boundingSphere = XMVectorMax(boundingSphere, XMLoadFloat3(&vert.major)); } HRESULT result; ID3D11Buffer* vbuffer = nullptr; //create vertex buffer D3D11_BUFFER_DESC descVertexBuffer; ZeroMemory(&descVertexBuffer, sizeof(D3D11_BUFFER_DESC)); descVertexBuffer.Usage = D3D11_USAGE_DEFAULT; descVertexBuffer.ByteWidth = pNode->data.size() * sizeof(EllipticalVertex); descVertexBuffer.BindFlags = D3D11_BIND_VERTEX_BUFFER; D3D11_SUBRESOURCE_DATA dataVertexBuffer; ZeroMemory(&dataVertexBuffer, sizeof(D3D11_SUBRESOURCE_DATA)); dataVertexBuffer.pSysMem = pNode->data.data(); result = device->CreateBuffer(&descVertexBuffer, &dataVertexBuffer, &vbuffer); if (FAILED(result)) { std::cout << "failed to create vertex buffer " << result << std::endl; std::cin.get(); } return EllipticalVertexBuffer(vbuffer, pNode->data.size(), XMVector3Length(boundingSphere).m128_f32[0]); } void printTreeStructure(const std::vector<OctreeVectorNode<VertexBuffer>>& verts, UINT32 nodeIndex, UINT32 maxDepth, UINT32 depth) { for (UINT32 i = 0; i < depth; ++i) { std::cout << "--"; } std::cout << nodeIndex << std::endl; if (depth != maxDepth) { UINT8 numchildren = 0; for (int i = 0; i < 8; ++i) { if (verts[nodeIndex].children & (0x01 << i)) //ist ith flag set T->the child exists { printTreeStructure(verts, verts[nodeIndex].firstChildIndex + numchildren, maxDepth, depth + 1); ++numchildren; } } } } }
true
5e7aa63b7e10e93b2100c051d527f08b4df5a645
C++
pkoppise/CSCI104
/7.2_vect.cpp
UTF-8
4,311
3.671875
4
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; template <typename T> void printVector(vector<T> gvector) { for(unsigned int i=0; i < gvector.size(); i++) { //cout << gvector[i] << endl; cout << gvector.at(i) << endl; } cout << "-----------------" << endl; } int main () { vector<int> vec0; //no size cout << "The default size is:" << vec0.size() << endl; vector<int> vec1(5); //size 5 with default value is 0 cout << "using size and defualt" << endl; printVector<int>(vec1); vector<int> vec11 = {1,2,3,4,5}; cout << "using { } brackets" << endl; printVector<int>(vec11); vector<int> vec2(5,10); //size 5 with default value is 10 cout << "using size and value 10" << endl; printVector<int>(vec2); for(unsigned int i=0; i < vec1.size(); i++) //assigning { vec1[i]= i+51; } cout << vec1.front() << endl; cout << vec1.back() << endl; cout << "-------------" << endl; cout << "using assigning" << endl; printVector<int>(vec1); vector<int> vec3(vec1.begin(),vec1.end()); //iterating through vec1 cout << "using iterator" << endl; printVector<int>(vec3); vector<int> vec4(vec2); //copying vec2 cout << "using copying" << endl; printVector<int>(vec4); int myInt[] = {1,2,3}; // construct from arrays: vector<int> vec5(myInt, myInt + 3); cout << "using array initialization" << endl; printVector<int>(vec5); vector<string> Scientist; Scientist.push_back("James Maxwell"); cout << Scientist.capacity() << endl; //1 -1 Scientist.push_back("Edwin Hubble"); cout << Scientist.capacity() << endl; //2 - 2 Scientist.push_back("Charles Augustin de Coulomb"); cout << Scientist.capacity() << endl; //4 - 3 Scientist.push_back("Louis Pasteur"); cout << Scientist.capacity() << endl; //4 - 4 cout << "---------------" << endl; cout << "Now, we have " << Scientist.size() << " scientists.\n"; Scientist.pop_back(); cout << "Now, we have " << Scientist.size() << " scientists.\n"; Scientist.insert(Scientist.begin(),"Leonardo da Vinci"); cout << Scientist.capacity() << endl; //4 -4 Scientist.insert(Scientist.begin() + 2,"Phanendra"); cout << Scientist.capacity() << endl; //8 - 5 vector<string>::iterator iter; for (iter = Scientist.begin(); iter != Scientist.end(); ++iter) cout << *iter << endl; cout << "-------------------" << endl; Scientist.erase(Scientist.begin() + 2); // 4 - 4 Scientist.push_back("Ravi"); //8 -5 cout << Scientist.capacity() << endl; Scientist.push_back("Sukesh"); Scientist.push_back("Suresh"); Scientist.push_back("Chiru"); //8 -8 cout << Scientist.capacity() << endl; Scientist.push_back("Hello"); cout << Scientist.capacity() << endl; //16 - 9 vector<string>::iterator iter1; for (iter1 = Scientist.begin(); iter1 != Scientist.end(); ++iter1) cout << *iter1 << endl; cout << "---------" << endl; cout << Scientist.capacity() << endl; cout << Scientist.size() << endl; Scientist.erase(Scientist.begin() + 2, Scientist.begin() + 5); cout << Scientist.size() << endl; vector<string> a(3,"Hello2"); Scientist.insert(Scientist.begin() + 2, begin(a), end(a)); cout << "After inerting range of elements:" << endl; printVector<string>(Scientist); cout << Scientist.size() << endl; if(find(Scientist.begin(), Scientist.end(),"Suresh") != Scientist.end()) { cout << "Suresh found " << endl; } else { cout << "Suresh not found" << endl; } Scientist.clear(); if(Scientist.empty()) cout << "Nothing in the list\n"; else cout << "You have something in the list\n"; //According to Scott Meyers, the following code requires 2-18 reallocations: //vector<int> v; //for(int i = 0; i < 1000; ++i) // v.push_back(i); //So, he suggested we should use resever() to reduce the costs: //vector<int> v; //v.reserve(1000); //for(int i = 0; i < 1000; ++i) v.push_back(i); return 0; }
true
677a0a1b0c411a553220ec7ceb806973855b74b3
C++
Alesh/Squall
/tests/core/test_OutcomingBuffer.cxx
UTF-8
7,870
2.96875
3
[]
no_license
#include <string> #include <memory> #include <iostream> #include <squall/core/Buffers.hxx> #include "../catch.hpp" using squall::core::Event; using squall::core::OutcomingBuffer; using std::placeholders::_1; using std::placeholders::_2; enum : intptr_t { MARK = -1, HANDLER = -2, TRANSMITER = -3, TRANSMITER_ERR = -4, RESUME = -5, PAUSE = -6 }; inline std::vector<char> cnv(const std::string& str) { return std::vector<char>(str.begin(), str.end()); } class OutcomingBufferTest : public OutcomingBuffer { int buffer_error; size_t apply_size; std::vector<intptr_t>& callog_; std::pair<size_t, int> transmiter(const char* buff, size_t size) { if (buffer_error == 0) { callog_.push_back(TRANSMITER); callog_.push_back(size); auto transmited = (apply_size < block_size) ? apply_size : block_size; transmited = size < transmited ? size : transmited; callog_.push_back(transmited); return std::make_pair(transmited, 0); } else { callog_.push_back(TRANSMITER_ERR); callog_.push_back(size); callog_.push_back(buffer_error); return std::make_pair(0, buffer_error); } } public: /* Constructor */ OutcomingBufferTest(std::vector<intptr_t>& callog, OutcomingBuffer::FlowCtrl&& flow_ctrl, size_t block_size, size_t max_size) : OutcomingBuffer(std::bind(&OutcomingBufferTest::transmiter, this, _1, _2), std::forward<FlowCtrl>(flow_ctrl), block_size, max_size), buffer_error(0), apply_size(max_size), callog_(callog) {} void setBufferError(int value) { buffer_error = value; } void setApplySize(size_t value) { value = value < block_size ? value : block_size; apply_size = value; } using OutcomingBuffer::operator(); using OutcomingBuffer::cleanup; }; TEST_CASE("Unittest squall::core::OutcommingBuffer", "[buffers]") { std::vector<intptr_t> callog; auto flow_ctrl = [&callog](bool resume) { if (resume) callog.push_back(RESUME); else callog.push_back(PAUSE); return true; }; OutcomingBufferTest out(callog, flow_ctrl, 8, 16); auto handler = [&callog](int revents, void* payload) { auto p_buff = static_cast<OutcomingBufferTest*>(payload); callog.push_back(HANDLER); callog.push_back(revents); callog.push_back(p_buff->size()); callog.push_back(p_buff->lastError()); }; callog.push_back(MARK); callog.push_back(1000); REQUIRE(!out.active()); REQUIRE(out.running()); REQUIRE((out.size()) == 0); REQUIRE((out.write(cnv("01234567")) == 8)); REQUIRE(!out.active()); REQUIRE(out.running()); REQUIRE((out.size()) == 8); REQUIRE((out.write(cnv("89ABCDEFZZZ")) == 8)); REQUIRE((out.size()) == 16); out(Event::WRITE); REQUIRE((out.size()) == 8); out.setApplySize(4); out(Event::WRITE); REQUIRE((out.size()) == 4); out(Event::WRITE); REQUIRE((out.size()) == 0); // #2 callog.push_back(MARK); callog.push_back(2000); REQUIRE(!out.active()); REQUIRE(!out.running()); REQUIRE(out.setup(handler, 0) == 1); // early result (buffer size <= 0) REQUIRE(out.setup(handler, 8) == 1); // early result (buffer size <= 8) REQUIRE(out.active()); REQUIRE(!out.running()); REQUIRE((out.write(cnv("0123456789ABCDEFZZZ")) == 16)); REQUIRE((out.size()) == 16); REQUIRE(out.running()); out(Event::WRITE); REQUIRE((out.size()) == 12); out(Event::WRITE); REQUIRE((out.size()) == 8); // event! callog.push_back(MARK); callog.push_back(3000); out.setApplySize(8); REQUIRE((out.size()) == 8); REQUIRE(out.setup(handler, 0) == 0); // await flushing (buffer size > 0) out(Event::WRITE); REQUIRE((out.size()) == 0); // event! REQUIRE(!out.running()); REQUIRE(out.active()); callog.push_back(MARK); callog.push_back(4000); REQUIRE((out.write(cnv("01234")) == 5)); REQUIRE(out.running()); out(Event::WRITE); REQUIRE(!out.running()); REQUIRE(out.active()); callog.push_back(MARK); callog.push_back(5000); REQUIRE(out.active()); REQUIRE(!out.running()); out.cancel(); // cancels buffer task; no more call handler REQUIRE(!out.running()); REQUIRE(!out.active()); REQUIRE((out.write(cnv("01234")) == 5)); REQUIRE(out.running()); REQUIRE(!out.active()); out(Event::WRITE); REQUIRE(!out.active()); REQUIRE(!out.running()); callog.push_back(MARK); callog.push_back(6000); REQUIRE(!out.running()); REQUIRE(!out.active()); REQUIRE((out.write(cnv("012345")) == 6)); REQUIRE(!out.active()); REQUIRE(out.running()); out(Event::ERROR); // emul. internal event loop error REQUIRE(!out.active()); REQUIRE(!out.running()); callog.push_back(MARK); callog.push_back(7000); REQUIRE((out.size()) == 6); REQUIRE(out.setup(handler, 0) == 0); // await flushing (buffer size > 0) REQUIRE(out.active()); REQUIRE(out.running()); out(Event::ERROR); // emul. internal event loop error REQUIRE(!out.active()); // Error cancel task and pause running REQUIRE(!out.running()); callog.push_back(MARK); callog.push_back(8000); out.setApplySize(4); REQUIRE((out.size()) == 6); REQUIRE(out.setup(handler, 4) == 0); // await flushing (buffer size > 4) out(Event::WRITE); REQUIRE((out.size()) == 2); // Event! REQUIRE((out.write(cnv("012345")) == 6)); out(Event::WRITE); REQUIRE((out.size()) == 4); REQUIRE(out.active()); REQUIRE(out.running()); callog.push_back(MARK); callog.push_back(9000); out.setBufferError(13); // emul. buffer writing error out(Event::WRITE); REQUIRE((out.size()) == 4); REQUIRE(!out.active()); // Error cancel task and pause running REQUIRE(!out.running()); callog.push_back(MARK); callog.push_back(1000); out.setBufferError(0); REQUIRE(out.setup(handler, 0) == 0); // await flushing (buffer size > 0) REQUIRE(out.running()); // new task resume running REQUIRE(out.active()); out.setApplySize(0); // emul/ Connection reset out(Event::WRITE); REQUIRE((out.size()) == 4); REQUIRE(!out.active()); // Error cancel task and pause running REQUIRE(!out.running()); out.cleanup(); REQUIRE((out.size()) == 0); REQUIRE(callog == std::vector<intptr_t>({ // clang-format off RESUME, MARK, 1000, TRANSMITER, 8, 8, TRANSMITER, 8, 4, TRANSMITER, 4, 4, PAUSE, MARK, 2000, RESUME, TRANSMITER, 8, 4, TRANSMITER, 8, 4, HANDLER, Event::BUFFER|Event::WRITE, 8, 0, MARK, 3000, TRANSMITER, 8, 8, PAUSE, HANDLER, Event::BUFFER|Event::WRITE, 0, 0, MARK, 4000, RESUME, TRANSMITER, 5, 5, PAUSE, HANDLER, Event::BUFFER|Event::WRITE, 0, 0, MARK, 5000, RESUME, TRANSMITER, 5, 5, PAUSE, MARK, 6000, RESUME, PAUSE, MARK, 7000, RESUME, PAUSE, HANDLER, Event::ERROR, 6, 0, MARK, 8000, RESUME, TRANSMITER, 6, 4, HANDLER, Event::BUFFER|Event::WRITE, 2, 0, TRANSMITER, 8, 4, HANDLER, Event::BUFFER|Event::WRITE, 4, 0, MARK, 9000, TRANSMITER_ERR, 4, 13, PAUSE, HANDLER, Event::BUFFER|Event::ERROR, 4, 13, MARK, 1000, RESUME, TRANSMITER, 4, 0, PAUSE, HANDLER, Event::BUFFER|Event::ERROR, 4, 0, // clang-format on })); }
true
55a5282db8b86367fc8ada0130d7105bf4148a61
C++
thec0dewriter/AlgoGI2020
/pongrczrebekakitty_2037_147028_feladat4_parcialis-1.cpp
UTF-8
742
2.890625
3
[]
no_license
#include <iostream> using namespace std; int alakit(int szam) { int uj=0; int h=1; while(szam !=0){ uj = (szam %2)*h+ uj; h = h*10; szam = szam /2; } return uj; } void megold( int a, int b, int k) { int szj,db,szam; for(int i= a; i<=b; i++){ szam = alakit(i); db=0; while(szam !=0){ szj = szam % 10; szam = szam /10; if(szj == 1){ db = db +1; } } if(db == k){ cout <<i<<" "; } } } int main() { int a,b,k; cout <<"mennyi a?"; cin >> a; cout << "mennyi b?"; cin >> b; cout << "mennyi k?"; cin >> k; megold(a,b,k); return 0; }
true
6cfeea7c84bb1cf13f8e89afc98eb10c56adc8e6
C++
skilincer/DfsAlgorithmC
/dfsalgorithm.cpp
ISO-8859-9
884
2.90625
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<stdbool.h> int graph[7][7]; bool ziyaret[7]; void matrisoku(){ int i = 0; FILE *fp = fopen("dfs.txt", "r"); while(fscanf(fp, "%d %d %d %d %d %d %d", &graph[i][0], &graph[i][1], &graph[i][2], &graph[i][3], &graph[i][4], &graph[i][5], &graph[i][6] ) != EOF){ i = i + 1 ; } } void DFS(int root, bool ziyaret[]){ int i; ziyaret[root] = true;//ilk aamada rootu ziyaret edildi olarak atadk printf("%d ",root); for(i = 1; i < 8; i++){ if(graph[root][i] == 1 && ziyaret[i] == false ){//matrisler aras balant varsa ve matris ziyaret edilmemise DFS(i, ziyaret); } } } int main(){ matrisoku(); printf("DFS Algoritmasi\n"); DFS(1, ziyaret); getch(); }
true
5b26cab255cfa71030728759557a4b6aaa51aaf8
C++
sshyran/Computational-Agroecology
/viz/model/material.h
UTF-8
332
2.65625
3
[]
no_license
#ifndef __MATERIAL_H__ #define __MATERIAL_H__ class Material { public: Material(float aborption = 0.5, float reflection = 0.5, float transmision = 0.0) :aborption(aborption), reflection(reflection), transmision(transmision) {} ~Material() {}; float aborption; float reflection; float transmision; }; #endif /* __MATERIAL_H__ */
true
96a9fd30e0113fb74efc9e4bfd8fefce2c27c8d8
C++
simonc312/cs184raytrace
/Assignment2/Scene.cpp
UTF-8
11,771
2.859375
3
[]
no_license
#include "Scene.hpp" #include <iostream> using namespace std; #include <fstream> #include <sstream> #include <cstdlib> #include <stack> #include <math.h> #include <time.h> Scene::Scene(std::string file, int progressWait){ bool showProgress = (progressWait > 0); //store variables and set stuff at the end outputName = "output.png"; ifstream in(file.c_str()); if(!in.is_open()){ cout << "Unable to open file" << std::endl; }else{ cout<<"Attempting read of file \""<<file.c_str()<<"\".\n"; //Default values. maxDepth = 5; in.seekg(0, std::ios_base::end); int fileSize = in.tellg(), fileDone; in.seekg(0, std::ios_base::beg); cout<<"Preliminary check: Size: "; float displaySize = fileSize; if(displaySize > 1024.0f){ double whole; displaySize /= 1024.0f; modf(displaySize*100.0f, &whole); if(displaySize > 1024.0f){ displaySize /= 1024.0f; modf(displaySize*100.0f, &whole); if(displaySize > 1024.0f){ displaySize /= 1024.0f; modf(displaySize*100.0f, &whole); if(displaySize > 1024.0f){ displaySize /= 1024.0f; modf(displaySize*100.0f, &whole); cout<<(whole/100.0f)<<"GiB.\n"; }else{ cout<<(whole/100.0f)<<"MiB.\n"; } }else{ cout<<(whole/100.0f)<<"KiB.\n"; } }else{ cout<<(whole/100.0f)<<"B.\n"; } }else{ cout<<displaySize<<"b.\n"; } string line; stack<Transform> transformStack; Transform curTransform; Quality curQuality; Attenuation curAttenuation; time_t lastUpdate, curTime; if(showProgress){ cout<<"Reading completed: 0%"; } lastUpdate = time(NULL); while(in.good()){ vector<std::string> splitline; string buf; getline(in,line); stringstream ss(line); while(ss >> buf){ splitline.push_back(buf); } //Ignore blank lines if(splitline.size() == 0){ continue; } //Ignore comments if(splitline[0][0] == '#'){ continue; } //Valid commands: //size width height // must be first command of file, controls image size else if(!splitline[0].compare("size")){ imgWidth = atoi(splitline[1].c_str()); imgHeight = atoi(splitline[2].c_str()); } //maxdepth depth // max # of bounces for ray (default 5) else if(!splitline[0].compare("maxdepth")){ maxDepth = atoi(splitline[1].c_str()); } //output filename // output file to write image to else if(!splitline[0].compare("output")){ outputName = splitline[1]; } //camera lookfromx lookfromy lookfromz lookatx lookaty lookatz upx upy upz fov // specifies the camera in the standard way, as in homework 2. else if(!splitline[0].compare("camera")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); lookFrom = Vertex3f(x, y, z); x = atof(splitline[4].c_str()); y = atof(splitline[5].c_str()); z = atof(splitline[6].c_str()); lookToward = Vertex3f(x, y, z); x = atof(splitline[7].c_str()); y = atof(splitline[8].c_str()); z = atof(splitline[9].c_str()); up = Vector3f(x, y, z).Normalize(); fov = atof(splitline[10].c_str()); } //sphere x y z radius // Defines a sphere with a given position and radius. else if(!splitline[0].compare("sphere")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); float radius = atof(splitline[4].c_str()); Sphere* obj = new Sphere(x, y, z, radius, curTransform, curQuality); objects.push_back(obj); } //maxverts number // Defines a maximum number of vertices for later triangle specifications. // It must be set before vertices are defined. else if(!splitline[0].compare("maxverts")){ /* IGNORE! */ } //maxvertnorms number // Defines a maximum number of vertices with normals for later specifications. // It must be set before vertices with normals are defined. else if(!splitline[0].compare("maxvertnorms")){ /* IGNORE! */ } //vertex x y z // Defines a vertex at the given location. // The vertex is put into a pile, starting to be numbered at 0. else if(!splitline[0].compare("vertex")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); Vertex3f vertex(x, y, z); vertices.push_back(vertex); } //vertexnormal x y z nx ny nz // Similar to the above, but define a surface normal with each vertex. // The vertex and vertexnormal set of vertices are completely independent // (as are maxverts and maxvertnorms). else if(!splitline[0].compare("vertexnormal")){ VertexNormalPair pair; float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); pair.vertex = Vertex3f(x, y, z); float nx = atof(splitline[4].c_str()); float ny = atof(splitline[5].c_str()); float nz = atof(splitline[6].c_str()); pair.normal = Vector3f(nx, ny, nz); vertexNormalPairs.push_back(pair); } //tri v1 v2 v3 // Create a triangle out of the vertices involved (which have previously been specified with // the vertex command). The vertices are assumed to be specified in counter-clockwise order. Your code // should internally compute a face normal for this triangle. else if(!splitline[0].compare("tri")){ int i0 = atof(splitline[1].c_str()); int i1 = atof(splitline[2].c_str()); int i2 = atof(splitline[3].c_str()); Triangle* obj = new Triangle(vertices[i0], vertices[i1], vertices[i2], curTransform, curQuality); objects.push_back(obj); } //trinormal v1 v2 v3 // Same as above but for vertices specified with normals. // In this case, each vertex has an associated normal, // and when doing shading, you should interpolate the normals // for intermediate points on the triangle. else if(!splitline[0].compare("trinormal")){ int i0 = atof(splitline[1].c_str()); int i1 = atof(splitline[2].c_str()); int i2 = atof(splitline[3].c_str()); VertexNormalPair vn0 = vertexNormalPairs[i0]; VertexNormalPair vn1 = vertexNormalPairs[i1]; VertexNormalPair vn2 = vertexNormalPairs[i2]; Triangle* obj = new Triangle(vn0.vertex, vn1.vertex, vn2.vertex, vn0.normal, vn1.normal, vn2.normal, curTransform, curQuality); objects.push_back(obj); } //translate x y z // A translation 3-vector else if(!splitline[0].compare("translate")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); curTransform = curTransform.translateFirst(x, y, z); } //rotate x y z angle // Rotate by angle (in degrees) about the given axis as in OpenGL. else if(!splitline[0].compare("rotate")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); float angle = atof(splitline[4].c_str()); curTransform = curTransform.rotateFirst(x, y, z, angle); } //scale x y z // Scale by the corresponding amount in each axis (a non-uniform scaling). else if(!splitline[0].compare("scale")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); curTransform = curTransform.scaleFirst(x, y, z); } //pushTransform // Push the current modeling transform on the stack as in OpenGL. // You might want to do pushTransform immediately after setting // the camera to preserve the “identity” transformation. else if(!splitline[0].compare("pushTransform")){ transformStack.push(curTransform); } //popTransform // Pop the current transform from the stack as in OpenGL. // The sequence of popTransform and pushTransform can be used if // desired before every primitive to reset the transformation // (assuming the initial camera transformation is on the stack as // discussed above). else if(!splitline[0].compare("popTransform")){ curTransform = transformStack.top(); transformStack.pop(); } //directional x y z r g b // The direction to the light source, and the color, as in OpenGL. else if(!splitline[0].compare("directional")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); Vector3f direction(-x, -y, -z); direction = curTransform.Get() * direction; float r = atof(splitline[4].c_str()); float g = atof(splitline[5].c_str()); float b = atof(splitline[6].c_str()); Color3f color(r, g, b); DirectionalLight* light = new DirectionalLight(direction, color, curAttenuation); lights.push_back(light); } //point x y z r g b // The location of a point source and the color, as in OpenGL. else if(!splitline[0].compare("point")){ float x = atof(splitline[1].c_str()); float y = atof(splitline[2].c_str()); float z = atof(splitline[3].c_str()); Vertex3f point(x, y, z); point = curTransform.Get() * point; float r = atof(splitline[4].c_str()); float g = atof(splitline[5].c_str()); float b = atof(splitline[6].c_str()); Color3f color(r, g, b); PointLight* light = new PointLight(point, color, curAttenuation); lights.push_back(light); } //attenuation const linear quadratic // Sets the constant, linear and quadratic attenuations // (default 1,0,0) as in OpenGL. else if(!splitline[0].compare("attenuation")){ curAttenuation.constant = atof(splitline[1].c_str()); curAttenuation.linear = atof(splitline[2].c_str()); curAttenuation.quadratic = atof(splitline[3].c_str()); } //ambient r g b // The global ambient color to be added for each object // (default is .2,.2,.2) else if(!splitline[0].compare("ambient")){ float r = atof(splitline[1].c_str()); float g = atof(splitline[2].c_str()); float b = atof(splitline[3].c_str()); curQuality.ambient = Color3f(r, g, b); } //diffuse r g b // specifies the diffuse color of the surface. else if(!splitline[0].compare("diffuse")){ float r = atof(splitline[1].c_str()); float g = atof(splitline[2].c_str()); float b = atof(splitline[3].c_str()); curQuality.diffuse = Color3f(r, g, b); } //specular r g b // specifies the specular color of the surface. else if(!splitline[0].compare("specular")){ float r = atof(splitline[1].c_str()); float g = atof(splitline[2].c_str()); float b = atof(splitline[3].c_str()); curQuality.specular = Color3f(r, g, b); } //shininess s // specifies the shininess of the surface. else if(!splitline[0].compare("shininess")){ curQuality.shininess = atof(splitline[1].c_str()); } //emission r g b // gives the emissive color of the surface. else if(!splitline[0].compare("emission")){ float r = atof(splitline[1].c_str()); float g = atof(splitline[2].c_str()); float b = atof(splitline[3].c_str()); curQuality.emission = Color3f(r, g, b); } else { cerr<<"Unknown command: "<<splitline[0]<<endl; } //Update the progress. curTime = time(NULL); if(showProgress && difftime(curTime, lastUpdate) > progressWait){ fileDone = in.tellg(); double whole; modf(10000.0f*((float)fileDone)/((float)fileSize), &whole); cout<<" ... "<<(whole/100.0f)<<"%\n"; cout.flush(); lastUpdate = curTime; } } } cout<<"Reading finished successfully!\n"; } Scene::~Scene(){ std::list<Object*>::iterator obj; for(obj = objects.begin();obj != objects.end();obj++){ delete *obj; } std::list<Light*>::iterator light; for(light = lights.begin();light != lights.end();light++){ delete *light; } }
true
0c6aafbd3b73849b1f9e477073c866bcc668536a
C++
CyJay96/Lab-cpp
/lab_7/lab_7.7/lab_7.7.cpp
UTF-8
1,294
2.96875
3
[]
no_license
/* Дата сдачи: 04.03.2021 По заданной последовательности различных целых чисел построить соответствующее бинарное дерево поиска T как динамическую структуру данных. Выполнить следующие задания и вывести элементы дерева на экран. Оценить асимптотическую сложность алгоритма. Определить число листьев дерева. 8 20 10 8 12 30 25 34 22 k = 4 11 20 10 8 12 11 30 25 22 34 32 35 k = 5 */ #include "functions.h" int main() { cout << "Enter the number of tree elements:" << endl; cout << "N = "; int n = 0; enter(n); cout << endl; Tree* top = nullptr; cout << "Enter elements of the tree:" << endl; input(top, n); cout << endl; cout << "Elements of the tree displayed on the left:" << endl; outputLeft(top); cout << endl << endl; cout << "Elements of the tree displayed on the right:" << endl; outputRight(top); cout << endl << endl; int k = findLeaves(top); cout << endl << "The number of leaves of the tree: " << k << endl; delTree(top); cout << "Press any key to continue..." << endl; _getch(); return 0; }
true
fecb8417d04a0b2854f55da2d22c64c395309d4a
C++
yogeshvishnole/cliondsalgo
/Recursion/23removeCharacter.cpp
UTF-8
473
3.4375
3
[]
no_license
#include<iostream> using namespace std; void replaceCharacter(char arr[],int elToReplace){ if(arr[0] == '\0') return; if(arr[0] == elToReplace){ for(char* p = arr;*p != '\0';p++){ *p = *(p+1); } replaceCharacter(arr,elToReplace); }else{ replaceCharacter(arr+1,elToReplace); } } int main(int argc,char** argv){ char arr[] = "abcdab"; cout<<arr<<endl; replaceCharacter(arr,'a'); cout<<arr<<endl; }
true
884b5167dfe1d7473505dd310f9651e5f2038135
C++
kpilkk/Interviewbit
/Strings/roman-to-integer.cpp
UTF-8
541
3.421875
3
[]
no_license
// https://www.interviewbit.com/problems/roman-to-integer/ int Solution::romanToInt(string A) { int ans = 0, n = A.size(); unordered_map<char, int> roman = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}}; int temp = roman[A[n - 1]]; ans += temp; for(int i = n - 1; i > 0; --i){ int temp1 = roman[A[i - 1]]; if(temp <= temp1){ temp = temp1; ans += temp1; } else{ ans -= temp1; } } return ans; }
true
aadb6c760e8bdcc59d122188985f1170769fcc2f
C++
etrizzo/PersonalEngineGames
/DFS1/Adventure/Code/Game/Tile.cpp
UTF-8
6,998
2.640625
3
[]
no_license
#include "Tile.hpp" #include "Game/Game.hpp" #include "Game/Map.hpp" #include "Game/DebugRenderSystem.hpp" Tile::~Tile() { } Tile::Tile(int x, int y, TileDefinition* tileDef) { m_coordinates = IntVector2(x,y); m_tileDef = tileDef; m_extraInfo = new TileExtraInfo(); m_extraInfo->m_variant = GetRandomIntLessThan(tileDef->m_spriteCoords.size()); if (m_tileDef->m_isTerrain){ m_extraInfo->m_terrainDef = m_tileDef; } m_extraInfo->SetSpriteCoords(m_tileDef->GetTexCoords(m_extraInfo->m_variant), SPRITE_COSMETIC_BASE); if (m_tileDef->m_overlayCoords != IntVector2(0,0)){ m_extraInfo->SetSpriteCoords(m_tileDef->GetOverlayTexCoords(), SPRITE_OVERLAY); } } Tile::Tile(IntVector2 & coords, TileDefinition* tileDef) { m_coordinates = coords; m_tileDef = tileDef; m_extraInfo = new TileExtraInfo(); if (tileDef == nullptr){ m_extraInfo->m_variant = 0; } else { m_extraInfo->m_variant = GetRandomIntLessThan(tileDef->m_spriteCoords.size()); if (m_tileDef->m_isTerrain){ m_extraInfo->m_terrainDef = m_tileDef; } } m_extraInfo->SetSpriteCoords(m_tileDef->GetTexCoords(m_extraInfo->m_variant), SPRITE_COSMETIC_BASE); if (m_tileDef->m_overlayCoords != IntVector2(0,0)){ m_extraInfo->SetSpriteCoords(m_tileDef->GetOverlayTexCoords(), SPRITE_OVERLAY); } } // returns neighbors of the current tile x: // 0 1 2 // 3 x 4 // 5 6 7 void Tile::AddTag(std::string tag) { m_extraInfo->AddTag(tag); } bool Tile::HasTag(std::string tag) { return m_extraInfo->m_tags.HasTag(tag); } bool Tile::HasTerrainDefinition(TileDefinition * def) const { return m_extraInfo->m_terrainDef == def; } int Tile::GetTerrainLevel() const { //if (m_extraInfo->m_cosmeticBaseDefinition != nullptr){ // return m_extraInfo->m_cosmeticBaseDefinition->m_terrainLevel; //} if (m_extraInfo->m_terrainDef != nullptr){ return m_extraInfo->m_terrainDef->m_terrainLevel; } else { return -1; } } int Tile::GetCosmeticTerrainLevel() const { if (m_extraInfo->m_cosmeticBaseDefinition != nullptr){ return m_extraInfo->m_cosmeticBaseDefinition->m_terrainLevel; } if (m_extraInfo->m_terrainDef != nullptr){ return m_extraInfo->m_terrainDef->m_terrainLevel; } else { return -1; } } eTerrainLayer Tile::GetCosmeticTerrainLayer() const { if (m_extraInfo->m_cosmeticBaseDefinition != nullptr){ return m_extraInfo->m_cosmeticBaseDefinition->m_terrainLayer; } if (m_extraInfo->m_terrainDef != nullptr){ return m_extraInfo->m_terrainDef->m_terrainLayer; } else { ConsolePrintf("Not terrain"); return NOT_TERRAIN; } } eTerrainLayer Tile::GetTerrainLayer() const { //if (m_extraInfo->m_cosmeticBaseDefinition != nullptr){ // return m_extraInfo->m_cosmeticBaseDefinition->m_terrainLayer; //} if (m_extraInfo->m_terrainDef != nullptr){ return m_extraInfo->m_terrainDef->m_terrainLayer; } else { ConsolePrintf("Not terrain"); return NOT_TERRAIN; } } eGroundLayer Tile::GetGroundLayer() const { if (m_extraInfo->m_cosmeticBaseDefinition != nullptr && m_extraInfo->m_cosmeticBaseDefinition != m_tileDef){ return m_extraInfo->m_cosmeticBaseDefinition->m_groundLayer; } //return m_tileDef->m_groundLayer; if (m_extraInfo->m_terrainDef != nullptr){ return m_extraInfo->m_terrainDef->m_groundLayer; } else { ConsolePrintf("Not terrain"); return NOT_GROUND; } } bool Tile::HasBeenSpawnedOn() const { return m_extraInfo->m_spawnedOn; } void Tile::MarkAsSpawned() { m_extraInfo->m_spawnedOn = true; } //for destructible tiles, if i'm #feelinthat void Tile::DamageTile(TileDefinition* typeIfDestroyed, int damage) { damage; typeIfDestroyed; /*if (m_tileDef->m_isDestructible){ AABB2 oldtexCoords = m_tileDef->GetTexCoordsAtHealth(m_health); m_health -=damage; AABB2 newtexCoords = m_tileDef->GetTexCoordsAtHealth(m_health); if (m_health <= 0){ m_tileDef = typeIfDestroyed; } }*/ } AABB2 Tile::GetBounds() const { IntVector2 maxs = m_coordinates + IntVector2(TILE_WIDTH, TILE_WIDTH); return AABB2(m_coordinates.GetVector2(), maxs.GetVector2()); } Vector2 Tile::GetCenter() const { return (m_coordinates.GetVector2() + Vector2(TILE_WIDTH * .5f, TILE_WIDTH * .5f)); } Vector2 Tile::GetApproximateCenter() const { return (GetCenter() + Vector2(GetRandomFloatInRange(TILE_WIDTH * -.001f, TILE_WIDTH *.001f), GetRandomFloatInRange(TILE_WIDTH *-.001f, TILE_WIDTH *.001f))); } TileDefinition* Tile::GetTileDefinition() { return m_tileDef; } int Tile::GetWeight() const { return m_extraInfo->m_weight; } void Tile::SetWeight(int weight) { m_extraInfo->m_weight = weight; } void Tile::RenderTag() { //if (m_extraInfo->m_tags.GetNumTags() > 0){ // //std::string tags = m_extraInfo->m_tags.GetTagsAsString(); // std::string tags = ""; // if (m_extraInfo->m_terrainDef != nullptr){ // tags = m_extraInfo->m_terrainDef->m_name; // } // g_theGame->m_debugRenderSystem->MakeDebugRender3DText(tags, 0.f, Vector3(GetCenter()), .1f); // g_theRenderer->DrawTextInBox2D(tags, GetBounds(), Vector2::HALF, .01f, TEXT_DRAW_WORD_WRAP); //} if (m_extraInfo->m_terrainDef != nullptr){ std::string terrainstuff = ""; terrainstuff += ("Base:\n" + m_extraInfo->m_terrainDef->m_name + "\nCos:\n" ); if (m_extraInfo->m_cosmeticBaseDefinition != nullptr){ terrainstuff += ( m_extraInfo->m_cosmeticBaseDefinition->m_name + " " + std::to_string(m_extraInfo->m_cosmeticBaseDefinition->m_groundLayer)); } terrainstuff+=("\nGLVL:\n" + std::to_string(GetGroundLayer())); terrainstuff+=("\nTLVL:\n" + std::to_string(GetTerrainLevel())); //terrainstuff += "\nDef: " + std::to_string(GetTerrainLevel()); g_theGame->m_debugRenderSystem->MakeDebugRender3DText(terrainstuff, 0.f, Vector3(GetCenter()), .1f); //g_theRenderer->DrawTextInBox2D(terrainstuff, GetBounds(), Vector2::HALF, .01f, TEXT_DRAW_WORD_WRAP); } } void Tile::SetType(TileDefinition* newType) { m_tileDef = newType; m_extraInfo->m_variant = GetRandomIntLessThan(newType->m_spriteCoords.size()); m_extraInfo->m_terrainDef = newType; //if (newType->m_isTerrain){ // m_extraInfo->m_terrainDef = newType; //} else { // m_extraInfo->m_terrainDef = nullptr; //} m_extraInfo->SetSpriteCoords(m_tileDef->GetTexCoords(m_extraInfo->m_variant), SPRITE_COSMETIC_BASE); if (m_tileDef->m_overlayCoords != IntVector2(0,0)){ m_extraInfo->SetSpriteCoords(m_tileDef->GetOverlayTexCoords(), SPRITE_OVERLAY); } } void Tile::AddOverlaySpriteFromTileSheet(AABB2 spriteCoords, eTileSpriteLayer layer) { m_extraInfo->SetSpriteCoords(spriteCoords, layer); } TileExtraInfo::TileExtraInfo() { for(unsigned int i = 0; i < NUM_SPRITE_LAYERS; i++){ m_spriteCoords.push_back(nullptr); } } void TileExtraInfo::SetSpriteCoords(const AABB2 & coords, eTileSpriteLayer layer) { if (m_spriteCoords[layer] != nullptr){ delete m_spriteCoords[layer]; m_spriteCoords[layer] = nullptr; } m_spriteCoords[layer] = new AABB2(coords); } void TileExtraInfo::AddTag(std::string tag) { m_tags.SetTag(tag); } void TileExtraInfo::RemoveTag(std::string tag) { m_tags.RemoveTag(tag); }
true
4414d05154e7a1c0901076a4d62a2d76ddee8707
C++
Ventura-College-CS/assignments-DavReggae
/CSV15_Arrays/array3.cpp
UTF-8
824
3.21875
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int main() { //string mainstr = "chocolate"; //string substr = "col"; char mainstr[10] = "chocolate"; char substr[10] = "col"; int pos, i, j; int flag = 0; // pos = mainstr.find(substr); cout << sizeof(mainstr) << endl; cout << sizeof(substr) << endl; cout << strlen(substr) << endl; cout << strlen(mainstr) << endl; //cout << " found at position " << pos << endl; for(i = 0; i < strlen(mainstr) - strlen(substr) + 1; i++) { for (j=0; j < strlen(substr); j++) { if (substr[j] != mainstr[i+j]) break; } //if( full iteration of inside for loop) if( j== strlen(substr)) cout << " matched at the position " << i << endl; } if( ! flag) cout << " We did not find the substring \n"; }
true
3be5fe4b758b81fd52834ec654b3858947f19d4b
C++
hpuxiaoqiang/coding
/DataStrcture/数据结构书中算法的实现/BasicOperate/SQStack.cpp
GB18030
803
3.359375
3
[]
no_license
/* ˳ջĻ */ #include <iostream> using namespace std; #define OK 1 #define ERROR 0 #define MaxSize 100 typedef int ElemType; typedef struct { ElemType *top; ElemType *base; int StackSize; }SQStack; //ʼ int Init(SQStack &S){ S.base = new ElemType[MaxSize]; if(!S.base) return ERROR; S.top = S.base; S.StackSize = MaxSize; return OK; } //Ԫջ int Push(SQStack &S,ElemType e){ if(S.top - S.base == S.StackSize) return ERROR; *S.top = e; S.top ++; return OK; } //Ԫسջ int Pop(SQStack &S,ElemType &e){ if(S.top == S.base) return ERROR; S.top--; e = *S.top; return OK; } //õ׸Ԫ int GetHead(SQStack &S,ElemType &e){ if(S.base != S.top){ e = *(S.top - 1); return OK; }else{ return ERROR; } } int main() { return 0; }
true
2b6c359e9bb849fc3950b8946b8a767a1880abc6
C++
marromlam/lhcb-software
/Boole/VP/VPDigitisation/src/VPDepositMonitor.cpp
UTF-8
3,225
2.53125
3
[]
no_license
// Gaudi #include "GaudiKernel/SystemOfUnits.h" // Kernel/LHCbKernel #include "Kernel/VPChannelID.h" // Local #include "VPDepositMonitor.h" using namespace Gaudi::Units; DECLARE_ALGORITHM_FACTORY(VPDepositMonitor) //============================================================================= // Standard constructor, initializes variables //============================================================================= VPDepositMonitor::VPDepositMonitor(const std::string& name, ISvcLocator* pSvcLocator) : GaudiTupleAlg(name, pSvcLocator), m_det(nullptr) { declareProperty("Detailed", m_detailed = false); } //============================================================================= /// Initialization //============================================================================= StatusCode VPDepositMonitor::initialize() { StatusCode sc = GaudiTupleAlg::initialize(); if (sc.isFailure()) return sc; m_det = getDetIfExists<DeVP>(DeVPLocation::Default); if (!m_det) { return Error("No detector element at " + DeVPLocation::Default); } setHistoTopDir("VP/"); return StatusCode::SUCCESS; } //============================================================================= // Main execution //============================================================================= StatusCode VPDepositMonitor::execute() { const LHCb::MCHits* hits = getIfExists<LHCb::MCHits>(LHCb::MCHitLocation::VP); if (hits) monitorHits(hits); const LHCb::MCVPDigits* mcdigits = getIfExists<LHCb::MCVPDigits>(LHCb::MCVPDigitLocation::Default); if (mcdigits) monitorDigits(mcdigits); return StatusCode::SUCCESS; } //============================================================================= // Fill histograms for MC hits //============================================================================= void VPDepositMonitor::monitorHits(const LHCb::MCHits* hits) { for (const LHCb::MCHit* hit : *hits) { plot(hit->pathLength() / Gaudi::Units::micrometer, "PathInSensor", "Path in sensor [um]" , 0.0, 300.0, 60); plot(hit->energy() / Gaudi::Units::keV, "EnergyInSensor", "Energy deposited in sensor [keV]" , 0.0, 200.0, 40); } } //============================================================================= // Fill histograms for MC digits //============================================================================= void VPDepositMonitor::monitorDigits(const LHCb::MCVPDigits* mcdigits) { plot(mcdigits->size(), "nDigits", "Number of MCVPDigits / event", 0., 10000., 50); for (const LHCb::MCVPDigit* mcdigit : *mcdigits) { LHCb::VPChannelID channel = mcdigit->channelID(); plot(channel.module(), "DigitsPerModule", "Number of digits / module", -0.5, 51.5, 52); // Loop over the deposits. double charge = 0.; const std::vector<double>& deposits = mcdigit->deposits(); const unsigned int nDeposits = deposits.size(); for (unsigned int i = 0; i < nDeposits; ++i) { charge += deposits[i]; plot(deposits[i], "ChargePerDeposit", "Charge/deposit [e]", 0., 20000., 100); } plot(charge, "ChargePerPixel", "Charge/pixel [e]", 0., 25000.0, 100); } }
true
9eec5593510bb72e9f2b9c5110eff3a17d560586
C++
xrisk/cc2
/Codeforces/anatoly.cpp
UTF-8
923
3.109375
3
[ "Unlicense" ]
permissive
// http://codeforces.com/contest/719/problem/B #include <iostream> #include <algorithm> #include <vector> #include <cstdio> using namespace std; int f1(int len, string s) { int wb = 0, wr = 0; for (int i = 0; i < len; i++) { if (i % 2 == 0 && s[i] == 'b') wb += 1; else if (i % 2 == 1 && s[i] == 'r') wr += 1; } int lesser = min(wb, wr); return lesser + max(wb, wr) - lesser; } int f2(int len, string s) { int wb = 0, wr = 0; for (int i = 0; i < len; i++) { if (i % 2 == 0 && s[i] == 'r') wr += 1; else if (i % 2 == 1 && s[i] == 'b') wb += 1; } int lesser = min(wb, wr); return lesser + max(wb, wr) - lesser; } int main() { #ifdef __APPLE__ freopen("in.in", "r", stdin); #endif int N; cin >> N; string str; cin >> str; cout << min(f1(N, str), f2(N, str)) << "\n"; }
true
23672514b375aecaa65933ed621f29e29fd070da
C++
karolinaWu/leetcode-lintcode
/leetcode/binary_search/154.find_minimum_in_rotated_sorted_array_ii/154.FindMinimuminRotatedSortedArrayII_henrytine.cpp
UTF-8
1,545
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// Source : https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/ // Author : henrytine // Date : 2020-07-22 /***************************************************************************************************** * * Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. * * (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). * * Find the minimum element. * * The array may contain duplicates. * * Example 1: * * Input: [1,3,5] * Output: 1 * * Example 2: * * Input: [2,2,2,0,1] * Output: 0 * * Note: * * This is a follow up problem to Find Minimum in Rotated Sorted Array. * Would allow duplicates affect the run-time complexity? How and why? * ******************************************************************************************************/ class Solution { public: int findMin(vector<int>& nums) { int start = 0, end = nums.size() - 1; while (start < end) { int mid = start + (end - start) / 2; if (nums[mid] == nums[end] && nums[mid] == nums[start]) { start++; end--; } else if (nums[mid] <= nums[end]) { end = mid; } else { start = mid + 1; } } return nums[start]; } }; class Solution { public: int findMin(vector<int>& nums) { for (auto n : nums) if (n < nums[0]) return n; return nums[0]; } };
true
eccd0173933abf88bb03319551aac125f3497b6b
C++
LeFou-k/RTRenderer
/include/rtweekend.h
UTF-8
1,263
2.9375
3
[]
no_license
#ifndef RTWEEKEND_H #define RTWEEKEND_H //set portable utilizable usings, constants, functions #include <cmath> #include <memory> #include <limits> #include <random> //Common Headers //using using std::shared_ptr; using std::make_shared; using std::sqrt; //constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; const double EPSILON = 0.0001; //Utility functions inline double degree_to_radians(const double degree) { return degree * pi / 180.0; } //return a random real number in range [0,1) inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } //return a random double number in range [min, max) inline double random_double(double min, double max) { return min + random_double() * (max - min); } inline int random_int(int min, int max) { return static_cast<int>(random_double(min, max + 1)); } //clamp x in range(min, max) inline double clamp(double x, double min, double max) { if(x < min) return min; if(x > max) return max; return x; } //先定义变量再包括.h头文件 //common headers #include "Ray.h" #include "vec3.h" #endif
true
c540934b227f38b125035351f5ae59298508dd44
C++
Wednesnight/lostengine
/source/lost/fs/Path.cpp
UTF-8
3,314
2.625
3
[ "MIT" ]
permissive
/* Copyright (c) 2011 Tony Kostanjsek, Timo Boll Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "lost/fs/Path.h" #include "lost/common/Logger.h" #if defined WIN32 #include <direct.h> #else #include <sys/stat.h> #endif #include <cerrno> namespace lost { namespace fs { static string dir_separator = "/"; Path::Path() {} Path::Path(const lost::string& sp) : path(sp) { } Path::~Path() { } void Path::operator /= (const Path& other) { path += dir_separator + other.path; } void Path::operator /= (const char* other) { path += dir_separator + other; } void Path::operator = (const char* other) { path = other; } bool Path::operator ==(const char* other) { return path == other; } bool Path::operator !=(const char* other) { return !this->operator==(other); } Path Path::directory() { Path result(path); string::size_type pos = path.rfind(dir_separator); if (pos != string::npos) { result = path.substr(0, pos); } return result; } Path Path::file() { Path result(path); string::size_type pos = path.rfind(dir_separator); if (pos != string::npos) { result = path.substr(++pos); } return result; } lost::string Path::string() const { return path; } lost::string Path::native() const { return path; } Path operator / (const Path& left, const Path& right) { Path result(left.string()); result /= right; return result; } bool exists(const Path& path) { return (access(path.string().c_str(), F_OK) != -1); } bool create_directories(const Path& path) { bool result = true; string dir = path.string(); string::size_type pos = dir.rfind(dir_separator); if (pos != string::npos) { string parent = dir.substr(0, pos); if (!exists(parent)) { result = create_directories(parent); } } if (result) { #if defined WIN32 result = _mkdir(dir.c_str()) != -1 || errno == EEXIST; #else result = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) != -1 || errno == EEXIST; #endif } return result; } } }
true
e0b78a954f5f4d5cca08d8216241a8a85e5dd7f0
C++
uc4w6c/CompetitiveProgramming
/atcoder/past/20200516_167/d/main.cpp
UTF-8
2,130
2.875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; // D - Teleporter // TODO: 失敗しているからどこかのタイミングでもう一度やりたい int main() { int N; long K; cin >> N >> K; vector<int> A(N); for (int i = 0; i < N; i++) { cin >> A.at(i); } vector<int> rated; int nowPoint = 1; for (long i = 1; i <= K; i++) { // cout << "nowPoint:" << nowPoint << endl; // cout << "A.at(nowPoint):" << A.at(nowPoint - 1) << endl; if (rated.empty() == false) { auto itr = find(rated.begin(), rated.end(), nowPoint); if (itr != rated.end()) { /* cout << "rated.size():" << rated.size() << endl; cout << "i:" << i << endl; cout << "rated.size() - i:" << (rated.size() - nowPoint) << endl; cout << ((K - i) % (rated.size() - nowPoint)) << endl; cout << "*itr:" << *itr << endl; cout << *itr + ((K - i) % (rated.size() - nowPoint)) << endl; */ cout << "before" << endl; cout << "rated.at(" << *itr << " + ((" << K << " - " << i << ") % "; cout << "(" << rated.size() << " - " << nowPoint << ")))" << endl; cout << "after" << endl; cout << "rated.at(" << *itr << " + "; cout << "(" << rated.size() << " - " << nowPoint << ")))"; cout << " % "; cout << "((" << K << " - " << i << ")"; cout << endl; // cout << ((rated.size() - nowPoint) % (K - i)) << endl; // cout << rated.at(*itr + ((K - i) % (rated.size() - nowPoint))); if ((K - i) != 0) { cout << rated.at(*itr + ((rated.size() - nowPoint) % (K - i)) - 1) << endl; cout << A.at(rated.at(*itr + ((rated.size() - nowPoint) % (K - i)) - 1) - 1); return 0; } } } rated.push_back(nowPoint); nowPoint = A.at(nowPoint - 1); } cout << nowPoint; }
true
872debfc31e72ccb9216fd18d087dbd00535db87
C++
slayerwalt/LeetCode
/OJ/leet992/leet992.cpp
UTF-8
1,578
3.015625
3
[]
no_license
/* leet992 */ #include <iostream> #include <tuple> #include <vector> #include <queue> #include <stack> #include <string> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <algorithm> #include <numeric> #include <cassert> #include <functional> #include <utility> // #include "../utils/LeetCpp.utils.hpp" using namespace std; class Solution { public: int subarraysWithKDistinct(const vector<int>& A, int K) { int M1[20005]{}, M2[20005]{}; int r1{}, r2{}, c1{}, c2{}, n(A.size()), ans{}; for (const auto& x: A) { // A[lft] = x; 我们希望 #[lft, r1) = K 以及 #[lft, r2) = K+1 // 注意 r1, r2 会比实际大1 while (c1 < K and r1 < n) { if (M1[A[r1]] == 0) c1++; M1[A[r1]]++; r1++; } while (c2 <= K and r2 < n) { if (M2[A[r2]] == 0) c2++; M2[A[r2]]++; r2++; } if (c1 < K) break; // r1 已经出界,仍未找到 ans += r2 - r1; // [r1-1, r2-2] if (c2 == K) ans++; // r2 == n, 无法延长了,此时实际合法区间为 [r1-1, r2-1] M1[x]--; if (M1[x] == 0) c1--; M2[x]--; if (M2[x] == 0) c2--; } return ans; } }; int main(int argc, char const *argv[]) { Solution sol; cout << sol.subarraysWithKDistinct({1,2,1,2,3}, 2) << endl; cout << sol.subarraysWithKDistinct({1,2,1,3,4}, 3) << endl; return 0; }
true
8d6e32a8798db7f0d2f36bd412d4b2de1cf064d4
C++
CorpseParty911/CS225TextAdventure
/TheMap.cpp
UTF-8
5,458
2.84375
3
[]
no_license
#include "RPG Game.h" #include <iostream> #include <fstream> #include <string> using namespace std; Item* nothing = (Item*)new Item("", 0, 0, 0); Enemy* nobody = (Enemy*)new Enemy("", 0, 0, 0.0); Enemy* Room::ENEMY_LIST[10] = { nobody,(Enemy*)new Enemy("Vampire Spawn",15,10,0.5),(Enemy*)new Enemy("Vampire",20,10,0.7),(Enemy*)new Enemy("Troll",45,10,0.65),(Enemy*)new Enemy("Vampire Knight",35,15,0.75),(Enemy*)new Enemy("Grue",90,25,0.6),(Enemy*)new Enemy("Skeleton",30,15,0.65),(Enemy*)new Enemy("Troll Elite",80,30,0.7),(Enemy*)new Enemy("Skeleton Knight",80,20,0.7),(Enemy*)new Enemy("Gaster",200,40,0.8) }; Item* Room::ITEM_LIST[20] = { nothing,(Item*)new Item("Dagger",5,0,0),(Item*)new Item("Shortsword",8,0,0),(Item*)new Item("Longsword",10,0,0),(Item*)new Item("Knife",13,0,0),(Item*)new Item("Glaive",15,0,0),(Item*)new Item("Greatsword",18,0,0),(Item*)new Item("Balmung",25,0,0),(Item*)new Item("Demonsbane",40,0,0),(Item*)new Item("Deathscythe",90,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("",0,0,0),(Item*)new Item("Key",0,0,0),(Item*)new Item("Candelabra",0,0,0) }; Room* emptyRoom = new Room(); Room** theMap; Room::Room(int roomNumber, int* drops, int* encounters, Room** exits, string words, string roomName) { if (drops != NULL) //Only checking one because the default case is all three are NULL. Otherwise, they aren't NULL for (int i = 0; i < 10; i++) { items[i] = ITEM_LIST[drops[i]]; encounter[i] = ENEMY_LIST[encounters[i]]; connections[i] = exits[i]; } name = roomName; text = words; number = roomNumber; } Item* Room::getItem(int index, Room* here) { if (index < 0 || index > 9) //Bounds check return nothing; return here->items[index]; } Enemy* Room::getEncounter(int index, Room* here) { if (index < 0 || index > 9) //Bounds check return nobody; return here->encounter[index]; } void Room::setEncounter(int index, Enemy* newEnemy) { if (index < 0 || index > 9) //Bounds check encounter[index] = newEnemy; } Room** Room::getConnections() { return connections; } void Room::setConnections(int direction, Room* connection) { if (direction < 0 || direction > 9) //Bounds check return; connections[direction] = connection; } string Room::getText() { return text; } string Room::getName() { return name; } int Room::getNumber() { return number; } void Room::gainItem(Item* item) { for (int i = 0; i < 10; i++) //Find an empty spot if (items[i]->getName() == "") { items[i] = item; break; } } Item* Room::loseItem(string itemName) { for (int i = 0; i < 10; i++) if (items[i]->getName() == itemName) { Item* removed = items[i]; items[i] = nothing; return removed; } return nothing; //If it didn't find it } Room* findRoom(int roomIndex, int numRooms) { for (int i = 0; i < numRooms; i++) { if (theMap[i] != emptyRoom) if (theMap[i]->getNumber() == roomIndex) return theMap[i]; } return emptyRoom; //If it didn't find it } Room* createMap(int numRooms) { theMap = new Room*[numRooms]; for (int i = 0; i < numRooms; i++) { theMap[i] = emptyRoom; //Give them all a value for the time being } ifstream File; string text; string text2; string name; string line1; string line2; string line3; int encounters[10]; int itemList[10]; Room* exits[10]; File.open("Map_Data.txt"); if (File.is_open()) { for (int i = 0; i < numRooms; i++) { getline(File, name); getline(File, text); getline(File, text2); getline(File, line1); getline(File, line2); getline(File, line3); for (int i = 0; i < 10; i++) { size_t pos1 = line1.find(' '); //String parsing into the respective arrays string enemyNumber = line1.substr(0, pos1); line1.erase(0, pos1 + 1); encounters[i] = atoi(enemyNumber.c_str()); size_t pos2 = line2.find(' '); string itemNumber = line2.substr(0, pos2); line2.erase(0, pos2 + 1); itemList[i] = atoi(itemNumber.c_str()); size_t pos3 = line3.find(' '); string roomNumber = line3.substr(0, pos3); line3.erase(0, pos3 + 1); exits[i] = findRoom(atoi(roomNumber.c_str()), numRooms); } Room* x = new Room(i + 1, itemList, encounters, exits, text + "\n" + text2, name); for (int i = 0; i < 10; i++) { if (x->getConnections()[i] != emptyRoom) //Make sure movement between the two rooms is possible x->getConnections()[i]->setConnections((i + 5) % 10, x); } theMap[i] = x; if (x->getName() == "Failure" || x->getName() == "") { throw("Invalid Name"); //If any room has either no name or "Failure", throw incomplete data exception } } File.close(); return theMap[0]; } else { throw("Invalid File"); //File didn't open } } int countLines() { int numLines = 0; ifstream File; string line; File.open("Map_Data.txt"); if (File.is_open()) { while (File.peek() != EOF) //Next line isn't the end of the file ie not at the end of the last line { getline(File, line); //Used to cycle through each line numLines++; } File.close(); } else { throw("Invalid File"); //File didn't open } return numLines; }
true
fe713fed4a7db84cb6f149c36f775850e6937b53
C++
camilo1505/Cliente-Servidor
/Matrix/multMatrix.cpp
UTF-8
2,670
3.25
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<malloc.h> #include<time.h> #include<string.h> #include<limits> #include<iostream> using namespace std; const int inf = numeric_limits<int>::max(); void print(float *M, int rows, int cols) { printf("----------MATRIX----------\n"); for(int i=0; i<rows;i++) { for(int j=0; j<cols; j++) { printf("[%f]",M[i*cols+j]); } printf("\n"); } } void toMatrix(float *M, FILE *content, int rows, int cols) { for(int i=0; i<rows;i++) { for(int j=0; j<cols; j++) { fscanf(content,"%f",&M[i*cols+j]); } } fclose(content); } void multiplication(float *m1, float *m2, float *m3, int rowsM1, int colsM1, int rowsM2, int colsM2) { for(int i=0; i<rowsM1; i++) { for(int j=0; j<colsM1; j++) { m3[i*colsM1+j] = 0.0; for(int k=0; k<colsM1; k++) { m3[i*colsM1+j] += m1[i*colsM1+k] * m2[k*colsM1+j]; } } } } void strange(float *m1, float *m2, float *m3, int rowsM1, int colsM1, int rowsM2, int colsM2) { for(int i=0; i<rowsM1; i++) { for(int j=0; j<colsM1; j++) { m3[i*colsM1+j] = 0.0; for(int k=0; k<colsM1; k++) { m3[i*colsM1+j] = std::min(m3[i*colsM1+j], m1[i*colsM1+k] + m2[k*colsM1+j]); } } } } int main(int argc, char** argv) { if(argc != 3) { printf("Error, no se encontraron todos los parametros necesarios."); return 1; } FILE *inputMatrix1; FILE *inputMatrix2; inputMatrix1 = fopen(argv[1],"r"); inputMatrix2 = fopen(argv[2],"r"); float *m1, *m2, *m3; int rowsM1, rowsM2, colsM1, colsM2; fscanf(inputMatrix1,"%d",&rowsM1); fscanf(inputMatrix1,"%d",&colsM1); fscanf(inputMatrix2,"%d",&rowsM2); fscanf(inputMatrix2,"%d",&colsM2); //Memoria el Para Host m1 = (float*) malloc(rowsM1*colsM1*sizeof(float)); m2 = (float*) malloc(rowsM2*colsM2*sizeof(float)); m3 = (float*) malloc(rowsM1*colsM2*sizeof(float)); toMatrix(m1, inputMatrix1, rowsM1, colsM1); toMatrix(m2, inputMatrix2, rowsM2, colsM2); print(m1, rowsM1, colsM1); print(m2, rowsM2, colsM2); if((rowsM1 == colsM2)) { multiplication(m1,m2,m3,rowsM1, colsM1, rowsM2, colsM2); strange(m1,m2,m3,rowsM1, colsM1, rowsM2, colsM2); } else { printf("Error los tamaños de las matrices no son compatibles."); return 1; } print(m3,rowsM1,colsM2); return 0; }
true
2725869a4320f40a97fd473da9fac27b46fac56a
C++
dabaldassi/Remote-Shared-Controller
/src/rsclocal_com/message.hpp
UTF-8
3,130
3.046875
3
[]
no_license
#ifndef MESSAGE_H #define MESSAGE_H #include <sstream> #include <vector> #include <tuple> namespace rsclocalcom { class Message { public: enum Command : unsigned { IF, GETIF, GETLIST, SETLIST, ACK, START, STOP, PAUSE, LOAD_SHORTCUT, SAVE_SHORTCUT, CIRCULAR, PASSWD, NA }; enum AckType { OK, ERROR }; enum AckCode : unsigned { DEFAULT, STARTED, PAUSED, FUTURE, IF_EXIST }; static constexpr int LOAD_DEFAULT = 0; static constexpr int LOAD_RESET = 1; static constexpr char NO_PASSWD[] = "0"; private: Command _cmd; std::vector<std::string> _args; static std::vector<std::tuple<std::string,size_t>> _commands; /** *\fn _to_string *\brief Convert a type to std::string if possible */ template<typename T> std::string _to_string(T&& t) { return std::to_string(std::forward<T>(t));} const std::string& _to_string(const std::string& s) { return s; } const char * _to_string(const char* s) { return s; } public: Message(Command c = NA); /** *\brief Get the message's command *\return The command */ Command get_cmd() const { return _cmd; } /** *\brief Get the message in a stringstream *\param ss The stringstream to get the message *\exception std::runtime_error if the command is NA or if the number of argument doesn't match */ void get(std::stringstream& ss) const; /** *\brief Get the argument at the index i *\param i The argument's index *\return The argument as string */ const std::string& get_arg(size_t i) const { return _args[i]; } /** *\brief Set a message from a stringstream *\remarks This will call the method reset *\param ss The stringstream containin the message to build *\exception std::range_error If argument are missing *\exception std::runtime_error If the command does not exist */ void set(std::stringstream& ss); /** *\brief Reset the message. This will clear all the arguments and set a new command. * The default command is NA *\param c The new command. */ void reset(Command c = NA); /** *\brief Add an argument to the message if possible. *\param t The argument. It will be converted to string only if possible. *\exception std::runtime_error Throw this exception if command if NA *\exception std::range_error Throw this exception if the number of argument is exeeded */ template<typename T, typename... Ts> void add_arg(T&& t, Ts... ts) { add_arg(std::forward<T>(t)); add_arg(std::forward<Ts>(ts)...); } template<typename T> void add_arg(T&& t) { if(_cmd == NA) throw std::runtime_error("Command is N/A"); size_t nb_args = std::get<1>(_commands[_cmd]);; if(_args.size() >= nb_args) throw std::range_error("Too much arguments : expecting " + std::to_string(nb_args)); _args.push_back(_to_string(std::forward<T>(t))); } }; } // rsclocalcom #endif /* MESSAGE_H */
true
ae0b2506b834717bad7117527b7ef317933f40c6
C++
FRENSIE/FRENSIE
/packages/monte_carlo/manager/src/MonteCarlo_ParticleSimulationManager_def.hpp
UTF-8
27,559
2.703125
3
[ "BSD-3-Clause" ]
permissive
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_ParticleSimulationManager_def.hpp //! \author Alex Robinson //! \brief Particle simulation manager template definitions //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_DEF_HPP #define MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_DEF_HPP // Std Lib Includes #include <functional> #include <type_traits> //! Log lost particle details #define LOG_LOST_PARTICLE_DETAILS( particle ) \ FRENSIE_LOG_TAGGED_WARNING( \ "Lost Particle", \ "history " << particle.getHistoryNumber() << \ ", generation " << particle.getGenerationNumber() << \ ", collision number " << particle.getCollisionNumber() ); \ \ FRENSIE_LOG_TAGGED_NOTIFICATION( "Lost Particle State Dump", \ "\n" << particle ) //! Macro for catching a lost particle and breaking a loop #define CATCH_LOST_PARTICLE_AND_BREAK( particle ) \ catch( const std::runtime_error& exception ) \ { \ particle.setAsLost(); \ \ LOG_LOST_PARTICLE_DETAILS( particle ); \ \ FRENSIE_LOG_NESTED_ERROR( exception.what() ); \ \ break; \ } //! Macro for catching a lost particle #define CATCH_LOST_PARTICLE( particle, ... ) \ catch( const std::runtime_error& exception ) \ { \ particle.setAsLost(); \ \ LOG_LOST_PARTICLE_DETAILS( particle ); \ \ FRENSIE_LOG_NESTED_ERROR( exception.what() ); \ \ __VA_ARGS__; \ } //! Macro for catching a lost particle #define CATCH_LOST_PARTICLE_AND_CONTINUE( particle, ... ) \ catch( const std::runtime_error& exception ) \ { \ particle.setAsLost(); \ \ LOG_LOST_PARTICLE_DETAILS( particle ); \ \ FRENSIE_LOG_NESTED_ERROR( exception.what() ); \ \ __VA_ARGS__; \ \ continue; \ } namespace MonteCarlo{ namespace Details{ //! \brief The Ray Safety Helper class template<typename State, typename Enabled=void> struct RaySafetyHelper { //! Return the distance to the next surface hit in the particle's direction static inline double getDistanceToSurfaceHit( State& particle, Geometry::Model::EntityId& surface_hit, const double ) { return particle.navigator().fireRay( surface_hit ).value(); } //! Update the ray safety distance static inline void updateRaySafetyDistance( State&, const double ) { /* ... */ } }; //! \brief The Ray Safety Helper class template<typename State> struct RaySafetyHelper<State,typename std::enable_if<std::is_base_of<MonteCarlo::ChargedParticleState,State>::value>::type> { // Return the distance to the next surface hit in the particle's direction static inline double getDistanceToSurfaceHit( State& particle, Geometry::Model::EntityId& surface_hit, const double remaining_track ) { if ( particle.getRaySafetyDistance() < remaining_track ) return particle.navigator().fireRay( surface_hit ).value(); else return std::numeric_limits<double>::infinity(); } //! Update the ray safety distance static inline void updateRaySafetyDistance( MonteCarlo::ChargedParticleState& particle, const double distance_to_collision_site ) { double new_ray_safety_distance = particle.getRaySafetyDistance() - distance_to_collision_site; // Set the particle's new ray safety distance if( new_ray_safety_distance > 0.0 ) particle.setRaySafetyDistance( new_ray_safety_distance ); // Set ray safety distance to closest boundary in all directions else { particle.setRaySafetyDistance( particle.navigator().getDistanceToClosestBoundary().value() ); } } }; } // end Details namespace // Simulate a resolved particle template<typename State> void ParticleSimulationManager::simulateParticle( ParticleState& unresolved_particle, ParticleBank& bank, const bool source_particle ) { // Make sure that the particle is embedded in the model testPrecondition( unresolved_particle.isEmbeddedInModel( *d_model ) ); this->simulateParticleImpl<State>( unresolved_particle, bank, source_particle, std::bind<void>( &ParticleSimulationManager::simulateParticleTrack<State>, std::ref( *this ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4 ) ); } // Simulate a resolved particle using the "alternative" tracking method template<typename State> void ParticleSimulationManager::simulateParticleAlternative( ParticleState& unresolved_particle, ParticleBank& bank, const bool source_particle ) { // Make sure that the particle is embedded in the model testPrecondition( unresolved_particle.isEmbeddedInModel( *d_model ) ); this->simulateParticleImpl<State>( unresolved_particle, bank, source_particle, std::bind<void>( &ParticleSimulationManager::simulateParticleTrackAlternative<State>, std::ref( *this ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4 ) ); } // Simulate a resolved particle implementation template<typename State, typename SimulateParticleTrackMethod> void ParticleSimulationManager::simulateParticleImpl( ParticleState& unresolved_particle, ParticleBank& bank, const bool source_particle, const SimulateParticleTrackMethod& simulate_particle_track ) { // Make sure that the particle is embedded in the model testPrecondition( unresolved_particle.isEmbeddedInModel( *d_model ) ); // Resolve the particle state State& particle = dynamic_cast<State&>( unresolved_particle ); // Simulate a particle subtrack of random optical path length starting from a // source point if( source_particle ) { // Check if the particle energy is below the cutoff if( particle.getEnergy() < d_properties->getMinParticleEnergy<State>() ) { FRENSIE_LOG_WARNING( particle.getParticleType() << " born below global cutoff energy. Check source " "definition!\n" << particle ); particle.setAsGone(); } // Check if the particle energy is above the max energy if( particle.getEnergy() > d_properties->getMaxParticleEnergy<State>() ) { FRENSIE_LOG_WARNING( particle.getParticleType() << " born above global max energy. Check source " "definition!\n" << particle ); particle.setAsGone(); } else { // Inject first check here d_population_controller->checkParticleWithPopulationController( particle, bank ); simulate_particle_track( particle, bank, d_transport_kernel->sampleOpticalPathLengthToNextCollisionSite(), true ); } } // Simulate a particle subtrack of random optical path length until the // particle is gone while( particle ) { // Check if the particle energy is below the cutoff if( particle.getEnergy() < d_properties->getMinParticleEnergy<State>() ) { particle.setAsGone(); break; } // Check if the particle energy is above the max energy if( particle.getEnergy() > d_properties->getMaxParticleEnergy<State>() ) { particle.setAsGone(); break; } // Roulette the particle if it is below the threshold weight d_weight_roulette->rouletteParticleWeight( particle ); if( particle ) { simulate_particle_track( particle, bank, d_transport_kernel->sampleOpticalPathLengthToNextCollisionSite(), false ); } } } // Simulate an unresolved particle track template<typename State> void ParticleSimulationManager::simulateUnresolvedParticleTrack( ParticleState& unresolved_particle, ParticleBank& bank, const double optical_path, const bool starting_from_source ) { this->simulateParticleTrack( dynamic_cast<State&>( unresolved_particle ), bank, optical_path, starting_from_source ); } // Simulate a resolved particle track // Note: Forced collisions cannot be done with this tracking method. Use the // "alternative" tracking method when forced collisions are requested. template<typename State> void ParticleSimulationManager::simulateParticleTrack( State& particle, ParticleBank& bank, const double optical_path, const bool starting_from_source ) { // Particle tracking information (op = optical_path) double remaining_track_op = optical_path; double op_to_surface_hit; double distance_to_surface_hit; double track_start_point[3] = {particle.getXPosition(), particle.getYPosition(), particle.getZPosition()}; bool subtrack_starting_from_source_point = starting_from_source; bool subtrack_starting_from_cell_boundary = false; // Surface information Geometry::Model::EntityId surface_hit; // Cell information double cell_total_macro_cross_section; // Records if global subtrack ending event has been dispatched bool global_subtrack_ending_event_dispatched = false; // If the particle started from a source point, update the relevant // particle entering cell event observers if( starting_from_source ) { d_event_handler->updateObserversFromParticleEnteringCellEvent( particle, particle.getCell() ); } // Ray trace until the necessary number of optical paths have been traveled while( true ) { // Get the total cross section for the cell if( !d_model->isCellVoid<State>( particle.getCell() ) ) { cell_total_macro_cross_section = d_model->getMacroscopicTotalForwardCrossSectionQuick( particle ); } else cell_total_macro_cross_section = 0.0; double cell_distance_to_collision = remaining_track_op/cell_total_macro_cross_section; // Fire a ray through the cell currently containing the particle try{ distance_to_surface_hit = Details::RaySafetyHelper<State>::getDistanceToSurfaceHit( particle, surface_hit, cell_distance_to_collision ); } CATCH_LOST_PARTICLE_AND_BREAK( particle ); // Convert the distance to the surface to optical path op_to_surface_hit = distance_to_surface_hit*cell_total_macro_cross_section; // The particle passes through this cell to the next if( op_to_surface_hit < remaining_track_op ) { try{ this->advanceParticleToCellBoundary( particle, surface_hit, distance_to_surface_hit ); } CATCH_LOST_PARTICLE_AND_BREAK( particle ); // The particle has exited the geometry if( d_model->isTerminationCell( particle.getCell() ) ) { particle.setAsGone(); break; } // Update the remaining subtrack mfp remaining_track_op -= op_to_surface_hit; // Set the ray safety distance to zero particle.setRaySafetyDistance( 0.0 ); // After the first subtrack the particle can no longer be starting from // a source point subtrack_starting_from_source_point = false; subtrack_starting_from_cell_boundary = true; } // A collision occurs in this cell else { this->advanceParticleToCollisionSite( particle, remaining_track_op, cell_distance_to_collision, track_start_point, global_subtrack_ending_event_dispatched ); // Update the particle's ray safety distance Details::RaySafetyHelper<State>::updateRaySafetyDistance( particle, cell_distance_to_collision ); this->collideWithCellMaterial( particle, bank ); // This track is finished break; } } if( !global_subtrack_ending_event_dispatched ) { d_event_handler->updateObserversFromParticleSubtrackEndingGlobalEvent( particle, track_start_point, particle.getPosition() ); } if( !particle ) d_event_handler->updateObserversFromParticleGoneGlobalEvent( particle ); } // Simulate an unresolved particle track using the "alternative" method template<typename State> void ParticleSimulationManager::simulateUnresolvedParticleTrackAlternative( ParticleState& unresolved_particle, ParticleBank& bank, const double optical_path, const bool starting_from_source ) { this->simulateParticleTrackAlternative( dynamic_cast<State&>( unresolved_particle ), bank, optical_path, starting_from_source ); } // Simulate a resolved particle track using the "alternative" method // Note: This method must be used if forced collisions are used. template<typename State> void ParticleSimulationManager::simulateParticleTrackAlternative( State& particle, ParticleBank& bank, const double initial_optical_path, const bool starting_from_source ) { // Particle tracking information (op = optical_path) double cell_op_to_collision = initial_optical_path; double cell_distance_to_collision; double distance_to_surface_hit; double track_start_point[3] = {particle.getXPosition(), particle.getYPosition(), particle.getZPosition()}; bool subtrack_starting_from_source_point = starting_from_source; // This will only be set to true once the first surface has been crossed - // it will not be set to true initially even if the particle lies on a // surface bool subtrack_starting_from_cell_boundary = false; // Surface information Geometry::Model::EntityId surface_hit; // Cell information double cell_total_macro_cross_section; // Records if global subtrack ending event has been dispatched bool global_subtrack_ending_event_dispatched = false; // If the particle started from a source point, update the relevant // particle entering cell event observers if( starting_from_source ) { d_event_handler->updateObserversFromParticleEnteringCellEvent( particle, particle.getCell() ); } // Ray trace until a collision occurs while( true ) { // Fire a ray through the cell currently containing the particle try{ distance_to_surface_hit = particle.navigator().fireRay( surface_hit ).value(); } CATCH_LOST_PARTICLE_AND_BREAK( particle ); // Get the total cross section for the cell and the distance to collision if( !d_model->isCellVoid<State>( particle.getCell() ) ) { cell_total_macro_cross_section = d_model->getMacroscopicTotalForwardCrossSectionQuick( particle ); // Only consider a forced collision cell if the subtrack is starting from // the source or from a cell boundary if( (subtrack_starting_from_source_point || subtrack_starting_from_cell_boundary) && d_collision_forcer->isForcedCollisionCell<State>(particle.getCell())) { // This event must be dispatched before the particle weight changes d_event_handler->updateObserversFromParticleSubtrackEndingGlobalEvent( particle, track_start_point, particle.getPosition() ); track_start_point[0] = particle.getXPosition(); track_start_point[1] = particle.getYPosition(); track_start_point[2] = particle.getZPosition(); d_collision_forcer->forceCollision( particle.getCell(), cell_total_macro_cross_section*distance_to_surface_hit, std::bind<void>( &ParticleSimulationManager::simulateUnresolvedParticleTrackAlternative<State>, std::ref( *this ), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, false ), particle, bank ); // The current particle becomes the uncollided branch of the track and // must therefore pass through the current cell cell_distance_to_collision = std::numeric_limits<double>::infinity(); } // Normal cell else { cell_distance_to_collision = cell_op_to_collision/cell_total_macro_cross_section; } } // Void cell else { cell_total_macro_cross_section = 0.0; cell_distance_to_collision = std::numeric_limits<double>::infinity(); } // The particle passes through this cell to the next if( distance_to_surface_hit < cell_distance_to_collision ) { try{ this->advanceParticleToCellBoundary( particle, surface_hit, distance_to_surface_hit ); } CATCH_LOST_PARTICLE_AND_BREAK( particle ); // The particle has exited the geometry if( d_model->isTerminationCell( particle.getCell() ) ) { particle.setAsGone(); break; } // Set the ray safety distance to zero particle.setRaySafetyDistance( 0.0 ); // After the first subtrack the particle can no longer be starting from // a source point, but it will be starting from a cell boundary subtrack_starting_from_source_point = false; subtrack_starting_from_cell_boundary = true; // Sample the optical path to collision in the new cell cell_op_to_collision = d_transport_kernel->sampleOpticalPathLengthToNextCollisionSite(); } // A collision occurs in this cell else { this->advanceParticleToCollisionSite( particle, cell_op_to_collision, cell_distance_to_collision, track_start_point, global_subtrack_ending_event_dispatched ); this->collideWithCellMaterial( particle, bank ); // This track is finished break; } } if( !global_subtrack_ending_event_dispatched ) { d_event_handler->updateObserversFromParticleSubtrackEndingGlobalEvent( particle, track_start_point, particle.getPosition() ); } if( !particle ) d_event_handler->updateObserversFromParticleGoneGlobalEvent( particle ); } // Advance a particle to the cell boundary template<typename State> void ParticleSimulationManager::advanceParticleToCellBoundary( State& particle, const Geometry::Model::EntityId surface_to_cross, const double distance_to_surface ) { // Advance the particle to the cell boundary // Note: this will change the particle's cell Geometry::Model::EntityId start_cell = particle.getCell(); double surface_normal[3]; bool reflected = particle.navigator().advanceToCellBoundary( surface_normal ); // Update the observers: particle subtrack ending in cell event d_event_handler->updateObserversFromParticleSubtrackEndingInCellEvent( particle, start_cell, distance_to_surface ); // Update the observers: particle leaving cell event d_event_handler->updateObserversFromParticleLeavingCellEvent( particle, start_cell ); // Update the observers: particle crossing surface event d_event_handler->updateObserversFromParticleCrossingSurfaceEvent( particle, surface_to_cross, surface_normal ); if( reflected ) { d_event_handler->updateObserversFromParticleCrossingSurfaceEvent( particle, surface_to_cross, surface_normal ); } // Update the observers: particle entering cell event d_event_handler->updateObserversFromParticleEnteringCellEvent( particle, particle.getCell() ); } // Advance a particle to a collision site template<typename State> void ParticleSimulationManager::advanceParticleToCollisionSite( State& particle, const double op_to_collision_site, const double distance_to_collision, const double track_start_position[3], bool& global_subtrack_ending_event_dispatched ) { // Advance the particle particle.navigator().advanceBySubstep( *Utility::reinterpretAsQuantity<Geometry::Navigator::Length>( &distance_to_collision ) ); // Update the observers: particle subtrack ending in cell event d_event_handler->updateObserversFromParticleSubtrackEndingInCellEvent( particle, particle.getCell(), distance_to_collision ); // Update the observers: particle subtrack ending global event d_event_handler->updateObserversFromParticleSubtrackEndingGlobalEvent( particle, track_start_position, particle.getPosition() ); global_subtrack_ending_event_dispatched = true; } // Collide with the cell material template<typename State> void ParticleSimulationManager::collideWithCellMaterial( State& particle, ParticleBank& bank ) { ParticleBank local_bank; // Undergo a collision with the material in the cell try{ d_collision_kernel->collideWithCellMaterial( particle, local_bank ); } CATCH_LOST_PARTICLE( particle ); // Apply the population managers to the original particle and to each of its // progeny. Multiple particle mode will result in all different particle types using the same // population manager for now. Needs to be fixed later if desired. if( particle ) { d_population_controller->checkParticleWithPopulationController( particle, bank ); } while( !local_bank.isEmpty() ) { ParticleBank split_particle_bank; if( local_bank.top() ) { d_population_controller->checkParticleWithPopulationController( local_bank.top(), split_particle_bank ); } std::shared_ptr<ParticleState> local_particle; local_bank.pop( local_particle ); // If the particle wasn't terminated, add it to the bank if( local_particle ) { bank.push( local_particle ); bank.splice( split_particle_bank ); } } } } // end MonteCarlo namespace #endif // end MONTE_CARLO_PARTICLE_SIMULATION_MANAGER_DEF_HPP //---------------------------------------------------------------------------// // end MonteCarlo_ParticleSimulationManager_def.hpp //---------------------------------------------------------------------------//
true
81bffe1401214b437aaf351395745dfb0cba1310
C++
gthparch/sst-core
/stats/basestats.h
UTF-8
2,605
2.671875
3
[]
no_license
// Copyright 2009-2015 Sandia Corporation. Under the terms // of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2015, Sandia Corporation // All rights reserved. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #ifndef _H_SST_CORE_BASE_STATISTICS #define _H_SST_CORE_BASE_STATISTICS #include <string> #include <cstdio> namespace SST { namespace Statistics { /** \class BaseStatistics Forms the base class for statistics gathering within the SST core. Statistics are gathered by the core and processed into various (extensible) output forms. Statistics are expected to be named so that they can be located in the simulation output files. */ class BaseStatistic { public: /** Constructor for the BaseStatistics class. In this for the string provided is copied into a buffer within the class (which consumes memory, for statistics with many components callers may want to use the alternative constructor which provides a pointer that is not copied). Default is for the statistic to be created enabled for use \param[statName] The name of the statistic being collected */ BaseStatistic(std::string statName) : enabled(true) { name = (char*) malloc(sizeof(char) * (statName.size() + 1)); sprintf(name, "%s", statName.c_str()); } /** Constructor for the BaseStatistic class. This form of the constructor takes a pointer and does NOT perform a copy of the string (i.e. assumes that the pointer will remain live for the duration of the statistic's use). Default is for the statistic to be created enabled for use \param[statName] A pointer to a name of the statistic being collected, this pointer must remain live for the duration of the statistic's use but can be modifed since it is read on use. */ BaseStatistic(char* statName) : enabled(true) { name = statName; } /** Get the name of the statistic \return The name of the statistic */ const char* getName() { return name; } /** Enable the statistic for collection */ void enable() { enabled = true; } /** Disable the statistic collection */ void disable() { enabled = false; } /** Query whether the statistic is currently enabled \return true if the statistics collection is currently enabled, otherwise false */ bool isEnabled() { return enabled; } protected: char* name; bool enabled; }; } } #endif
true
85665bf8d7fd49912e3e2cba2f5a82161b64d971
C++
Azi-824/iai
/iai/MUSIC.hpp
SHIFT_JIS
3,039
3
3
[]
no_license
//MUSIC.hpp //ypNX /* lj@ EtH_At@C}N` Elj̎ނƂɁA񋓌^ɒlj @F퓬ŎgpSEljꍇ @BT_SE_TYPEɒlj EAddgpāASEBGMlj邱Ƃł */ #pragma once //##################### wb_t@Cǂݍ ####################### #include "DxLib.h" #include <string> #include <vector> //##################### }N`Ft@CpXAO ################### #define MUSIC_DIR_SE R"(.\MY_MUSIC\SE)" //SẼt@C #define MUSIC_DIR_BGM R"(.\MY_MUSIC\BGM)" //BGM̃t@C #define SE_NAME_GAMESTART R"(\gamestart.mp3)" //Q[X[^gSE̖O #define SE_NAME_GAMEOVER R"(\gameover.mp3)" //Q[I[o[SE̖O #define SE_NAME_TEXT_SE R"(\text_se.mp3)" //eLXg\SE̖O #define SE_NAME_SLASH R"(\slash.mp3)" //aʉ̖O #define BGM_NAME_TITLE_BGM R"(\title_bgm.mp3)" //^CgBGM̖O #define BGM_NAME_END_BGM R"(\end_bgm.mp3)" //GhʂBGM̖O //##################### }N`FG[bZ[W ###################### #define MUSIC_ERROR_TITLE "MUSIC_ERROR" //G[^Cg #define MUSIC_ERROR_MSG "ǂݍ߂܂ł" //G[bZ[W //##################### }N` ########################## #define VOLUME_MAX 255 //ʂ̍ől //##################### 񋓌^ ######################### enum SE_TYPE { SE_TYPE_GAMESTART, //Q[X^[g SE_TYPE_RESULT, //ʕ\ SE_TYPE_TEXT, //eLXg\ SE_TYPE_SLASH //a鉹 }; enum BGM_TYPE { BGM_TYPE_TITLE, //^CgBGM BGM_TYPE_END //GhBGM }; //##################### NX` ############################ class MUSIC { private: std::string FilePath; //t@CpX std::string FileName; //O std::vector<int> Handle; //nh int PlayType; //̍Đ@ bool IsLoad; //ǂݍ߂ std::vector<bool> IsPlayed; //Đς݂ public: MUSIC(const char *, const char *); //RXgN^ ~MUSIC(); //fXgN^ bool GetIsLoad(); //ǂݍ߂擾 bool GetIsPlay(int); //ĐĂ邩擾 void ChengePlayType(int); //̍Đ@ύX void ChengeVolume(double,int); //ʂύX void Play(int); //Đ void PlayOne(int); //Đ(1񂾂) void PlayReset(int); //Đς݂ǂZbg(w肳ꂽ̂) void PlayReset(); //Đς݂ǂZbg(S) void Stop(); //~߂(S) void Stop(int); //~߂(w肳ꂽ̂) bool Add(const char*, const char*); //lj };
true
d502bef2a87f7d72cf7ce1ac5c53bfb355ec194f
C++
matias1379/ArduinoVibrador
/CodigosEjemplos/JSON/arrayJson/arrayJson.ino
UTF-8
958
2.953125
3
[]
no_license
#include <ArduinoJson.hpp> #include <ArduinoJson.h> void SerializeArray() { String json; StaticJsonDocument<300> doc; doc.add("B"); doc.add(45); doc.add(2.1728); doc.add(true); serializeJson(doc, json); Serial.println(json); } void DeserializeArray() { String json = "[\"B\",45,2.1728,true]"; StaticJsonDocument<300> doc; DeserializationError error = deserializeJson(doc, json); if (error) { return; } String item0 = doc[0]; int item1 = doc[1]; float item2 = doc[2]; bool item3 = doc[3]; Serial.println(item0); Serial.println(item1); Serial.println(item2); Serial.println(item3); } void setup() { Serial.begin(115200); Serial.println("===== Array Example ====="); Serial.println("-- Serialize --"); SerializeArray(); Serial.println(); Serial.println("-- Deserialize --"); DeserializeArray(); Serial.println(); } void loop() { }
true
3c4e6dfcddba11488305c0f411fbc30ebc4d0579
C++
bksaiki/MathSolver
/lib/expr/arithmetic.h
UTF-8
1,805
2.9375
3
[]
no_license
#ifndef _MATHSOLVER_ARITHMETIC_EXPR_H_ #define _MATHSOLVER_ARITHMETIC_EXPR_H_ #include "../common/base.h" #include "../expr/expr.h" namespace MathSolver { // Returns true if the node only contains the following: // numbers, constants, variables, // operators: +, -, *, /, % (mod), !, ^ // functions: exp, log, sin, cos, tan // Assumes the expression is valid. bool isArithmeticNode(ExprNode* node); // Returns true if every node in the expression is arithmetic: inline bool isArithmetic(ExprNode* expr) { return containsAll(expr, isArithmeticNode); } // Returns true if the expression contains inexact (Float) subexpressions. inline bool isInexact(ExprNode* expr) { return containsAll(expr, [](ExprNode* node) { return node->type() != ExprNode::FLOAT; }); } // Returns true if the expression is undefined inline bool isUndef(ExprNode* expr) { return expr->type() == ExprNode::CONSTANT && ((ConstNode*)expr)->name() == "undef"; } // Finds the common term between two monomial expressions. std::list<ExprNode*> commonTerm(ExprNode* expr1, ExprNode* expr2); // Finds the coefficient of an expression given a base term. std::list<ExprNode*> coeffTerm(ExprNode* expr, ExprNode* term); // Removes a list of term from an expression void removeTerm(ExprNode* expr, const std::list<ExprNode*>& terms); // Assumes the expression is in the form x^n or x and returns a copy of x, ExprNode* extractPowBase(ExprNode* op); // Assumes the expression is in the form x^n or x and returns a copy of n or 1, respectively. ExprNode* extractPowExp(ExprNode* op); // Assumes the expression is in the form x^n or x and returns x directly. ExprNode* peekPowBase(ExprNode* op); // Assumes the expression is in the form x^n or x and returns n or 1 directly. ExprNode* peekPowExp(ExprNode* op); } #endif
true
acee7943fc3f58740d43c3160e7f2f36b0baf04e
C++
NPIPHI/sdf-generator
/src/gfx/texture.cpp
UTF-8
1,633
2.921875
3
[]
no_license
// // Created by 16182 on 7/20/2020. // #include "texture.hpp" #include "../io/io.hpp" GLuint get_BMP(const std::string &file_name) { auto buffer = getFileRaw(file_name); unsigned char * header = buffer.data(); unsigned char * data; unsigned int dataPos; unsigned int imageSize; int width, height; // Actual RGB data // Open the file if ( header[0]!='B' || header[1]!='M' ){ printf("Not a correct BMP file\n"); return 0; } // Read the information about the image dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); if (imageSize==0) imageSize=width*height*4; if (dataPos==0) dataPos=54; data = buffer.data() + dataPos; // ARGB->RGBA for(int i = 0; i < imageSize; i+=4){ unsigned char a = data[i]; unsigned char b = data[i+1]; unsigned char g = data[i+2]; unsigned char r = data[i+3]; data[i] = r; data[i+1] = g; data[i+2] = b; data[i+3] = a; } return loadTexture(data, width, height, GL_LINEAR); } GLuint loadTexture(const void *data, int width, int height, GLenum filtering) { GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filtering); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filtering); glGenerateMipmap(GL_TEXTURE_2D); return tex; }
true
f5d543911c88997a35ac02688baa0fff70b7e296
C++
btcup/sb-admin
/exams/2559/02204111/2/midterm/2_2_712_5920503513.cpp
UTF-8
251
2.8125
3
[ "MIT" ]
permissive
//5920503513 #include<iostream> #include<cmath> using namespace std; int main() { int a,x,i; cout<<"Enter an integer : "; cin>>a; for(x=0,i=0;x>=1;i++) { x=a/10; } cout<<"Number of digit is "<<i<<endl; system("pause"); return 0; }
true
696455acb6610e5044169b3ecbf9218b529bdd02
C++
xmansyis/CSCI-21-Spring-2014
/Projects/p4/BSTNode.h
UTF-8
2,631
3.859375
4
[]
no_license
/* *Project 4, BSTNode.h * *CHEE YEE XIONG *Date created: 4-29-14 *Last date modified: 5-16-14 */ #pragma once #include <cstdlib> #include <string> #include <iostream> using namespace std; template <typename T> class BSTNode{ public: /* *overloaded constructor, leftChild = NULL, rightChild = NULL, data = newData. *@param template T is the new data. */ BSTNode(T newData){ leftChild = NULL; rightChild = NULL; data = newData; } /* *destructor. */ virtual ~BSTNode() {/*nothing to be done*/} /* *function setData(T newData), set data = newData. *@param template T is the new data. */ void setData(T newData){ data = newData; } /* *function setLeftChild(BSTNode * newLeftChild), set leftChild = newLeftChild. *@param BSTNode* is the new leftChild. */ void setLeftChild(BSTNode *newLeftChild){ leftChild = newLeftChild; } /* *function setRightChild(BSTNode * newRightChild), set rightChild = newRightChild. *@param BSTNode* is the new rightChild. */ void setRightChild(BSTNode *newRightChild){ rightChild = newRightChild; } /* *function getLeftChild() const, return leftChild. *@return BSTNode* leftChild. */ BSTNode* getLeftChild() const{ return leftChild; } /* *function getRightChild() const, return rightChild. *@return BSTNode* rightChild. */ BSTNode* getRightChild() const{ return rightChild; } /* *function getData() const, return the data. *@return template T is the data to be return. */ T getData() const{ return data; } /* *function getData(), return the data. *@return &template T is the data to be return. */ T& getData(){ return data; } /* *function getLeftChild(), return leftChild. *@return BSTNode*& leftChild. */ BSTNode*& getLeftChild(){ return leftChild; } /* *function getRightChild(), return rightChild. *@return BSTNode*& rightChild. */ BSTNode*& getRightChild(){ return rightChild; } private: //data members. BSTNode *leftChild; BSTNode *rightChild; T data; };
true
033de8e63c1768df6ff652e6687c0f95f29b32a3
C++
jeffamstutz/rfManta
/Core/Math/ipow.h
UTF-8
709
2.515625
3
[ "MIT" ]
permissive
#ifndef Manta_Core_ipow_h #define Manta_Core_ipow_h #include <MantaSSE.h> #include <Core/Math/SSEDefs.h> namespace Manta { inline double ipow(double x, int p) { double result=1; while(p){ if(p&1) result*=x; x*=x; p>>=1; } return result; } inline float ipow(float x, int p) { float result=1; while(p){ if(p&1) result*=x; x*=x; p>>=1; } return result; } #ifdef MANTA_SSE inline __m128 ipow(__m128 x, int p) { __m128 result = _mm_set1_ps(1.f); while (p) { if (p&1) result = _mm_mul_ps(result, x); x = _mm_mul_ps(x, x); p >>= 1; } return result; } #endif } #endif
true
aa12a30940a3d5127b3e9412e994d760c5bf276f
C++
pipilove/cpp_workspace
/firstprogram/StoneMerge/StoneMerge/StoneMerge.cpp
GB18030
790
3.328125
3
[]
no_license
/** ԲʯӺϲ */ #include <iostream> using namespace std; int minFuction(); int main(){ int n,i,j,k; cout<<"ʯӶ "; cin>>n; int *stone=new int[n]; cout<<"ʯӵĸ "; for(i=0;i<n;i++) cin>>stone[i]; int **m=new int*[n]; for(i=0;i<n;i++) m[i]=new int[n]; //m[i][j]ʾӴӵijʯӺϲƶ for(i=0;i<n;i++) for(j=0;j<n;j++){ if(i==j)m[i][j]=0;//ϣƶƶΪ0 else m[i][j]=-1;//ʼ }; for(i=0,j=1;i<n;i++,j++)//ϣֱ m[i][j]=stone[i]+stone[j]; for(k=3;k<n;k++) for(i=0;i<n;i++) for(j=i+1;j<n;j++) m[i][j] int minFuction(); return 0; } int minFuction();
true
0ade3167d8fba2476f5c924b456d8d8b9dbb7476
C++
jomei/graph_algorithms
/02/acyclicity.cpp
UTF-8
867
3.375
3
[]
no_license
#include <iostream> #include <vector> using std::vector; using std::pair; int step( vector<pair<bool, vector<int>>> &adj, int n) { // std::cout<< "step into " << n + << "\n"; if(adj[n].first) {return 1;} adj[n].first = true; for(int i = 0; i < adj[n].second.size(); ++i) { int r = step(adj, adj[n].second[i]); if(r == 1) { return 1;} } adj[n].first = false; return 0; } int acyclic( vector<pair<bool, vector<int>>> &adj) { for(int i = 0; i < adj.size(); ++i) { // if(adj[i].first) {continue;} int r = step(adj, i); if(r == 1) {return 1;} } return 0; } int main() { size_t n, m; std::cin >> n >> m; vector<pair<bool, vector<int>>> adj(n); for (size_t i = 0; i < m; i++) { int x, y; std::cin >> x >> y; adj[x - 1].first = false; adj[x - 1].second.push_back(y - 1); } std::cout << acyclic(adj); }
true
81d38a52fb4ae08d9fc54a331fd88d50443eb0d1
C++
YefersonPerez/proyecto-1er-Parcial
/Codificando.cpp
UTF-8
826
2.90625
3
[]
no_license
#include "Codificando.h" Codificando::Codificando() { } void Codificando::RecibirParametro() { //b= Esto es una prueba para el parcial de programacion I de la Unet. string Inicio="PRUEBA.txt"; string Final="ENTEROS.txt"; ifstream Codigo; ofstream Palabra; char X; int var=1; int var2=1; int numero; Codigo.open(Inicio.c_str(), ios::in); Palabra.open(Final.c_str(), ios::out); cout<<endl<<"De Prueba.txt (Letras)... Pasara a Enteros.txt (Numeros)"<<endl; while(var==1) { numero=0; for(int i=0;(i<4)&&(var2==1);i++) { Codigo>>X; if(Codigo.eof()==0) { if(i!=0) { numero>>8; } numero=numero|(X<<24); } else { var=0; var2=0; numero>>=8*(4-i); } } if(numero!=0) { Palabra<<numero<<endl; } } cout<<endl<<"Revisa el Enteros.txt"<<endl; }
true
1165f1de32e3959842e02ff864138de771b8bb0a
C++
sjm767/Algobay
/RollingString.cpp
UTF-8
1,280
3.03125
3
[]
no_license
//#include<iostream> //#include<string> //#include<algorithm> //#include<vector> //#include<sstream> // //using namespace std; //string rollingString(string s, vector<string>operations); //int main() //{ // // vector<string> operations; // operations.push_back("0 0 L"); // operations.push_back("2 2 L"); // operations.push_back("0 2 R"); // // // cout << rollingString("abc", operations) << endl; // // //int num = atoi(a[0].c_str()); // // //char aaa = 'a'; // // // //string bbb = "abc"; // // //bbb[1] = (char)(bbb[1] + 1); // // return 0; //} // // //string rollingString(string s, vector<string>operations) //{ // vector<string> aa; // // for (int i = 0; i < operations.size(); i++) // { // std::istringstream ss(operations[i]); // string token; // // while (std::getline(ss, token, ' ')) { // aa.push_back(token); // } // // int start, end, direction; // // start = atoi(aa[0].c_str()); // end = atoi(aa[1].c_str()); // direction = aa[2] == "L" ? -1 : 1; // // for (int j = start; j <= end; j++) // { // if (s[j] == 'a' && direction == -1) // { // s[j] = 'z'; // } // else if (s[j] == 'z' && direction == 1) // { // s[j] = 'a'; // } // else { // s[j]=(char)(s[j] + direction); // } // } // // aa.clear(); // } // // return s; //}
true
01bfc769a9ce6efa06d37d0a794f38222af00d03
C++
BackTo2012/homework
/Data_Structure/sequence/sequence.cpp
UTF-8
3,959
3.203125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> using namespace std; const int maxn = 20000; int s[maxn + 10]; int t[maxn + 10]; clock_t runtime, op, ed; void init() { for (int i = 1; i <= maxn ; i++) { s[i] = rand(); t[i] = s[i]; } } // Here is Bubble sort void BubbleSort(int arr[], int size) { for (int i = 1; i <= size ; i++) { for (int j = i + 1; j <= size; j++) { if (arr[j] < arr[i]) { swap(arr[i], arr[j]); } } } } // Here is Insert sort void InsertSort(int arr[], int size) { int low, high, mid; for (int i = 2; i < size; i++) { arr[0] = arr[i]; low = 1; high = i - 1; while (low <= high) { mid = (low + high) / 2; if (arr[0] < arr[mid]) high = mid - 1; else low = mid + 1; } for (int j = i - 1; j >= high+1; j--) arr[j+1] = arr[j]; arr[high+1] = arr[0]; } } // Here is Merge sort void Merge(int arr[], int L, int M, int R) { int LEFT_SIZE = M - L; int RIGHT_SIZE = R - M + 1; int left[LEFT_SIZE]; int right[RIGHT_SIZE]; int i, j, k; // fill in the left sub array for (i = L; i < M; i++) { left[i-L] = arr[i]; } // fill in the right sub array for (i = M; i <= R; i++) { right[i-M] = arr[i]; } // merge into the original array i = 0; j = 0; k = L; while (i < LEFT_SIZE && j < RIGHT_SIZE) { if (left[i] < right[j]) { arr[k] = left[i]; i++; k++; } else { arr[k] = right[j]; j++; k++; } } while (i < LEFT_SIZE) { arr[k] = left[i]; i++; k++; } while (i < RIGHT_SIZE) { arr[k] = right[j]; j++; k++; } } void MergeSort(int arr[], int L, int R) { if (L == R) { return; } else { int M = (L + R) / 2; MergeSort(arr, L, M); MergeSort(arr, M+1, R); Merge(arr, L, M+1, R); } } // Here is Quick sort void QuickSort(int arr[], int start, int end) { if (start >= end) { return; } int mid = arr[end]; int left = start; int right = end; while (left < right) { while (arr[left] < mid && left < right) { left++; } while (arr[right] >= mid && left < right) { right--; } swap(arr[left], arr[right]); } if (arr[left] >= arr[end]) { swap(arr[left], arr[end]); } else { left++; } QuickSort(arr, start, left - 1); QuickSort(arr, left + 1, end); } // Here is Shell sort void ShellSort(int arr[], int size) { int h = 1; while (h < size / 2) { h = 2 * h + 1; } while (h >= 1) { for (int i = h + 1; i < size; i++) { for (int j = i; j >= h && arr[j] < arr[j - h]; j -= h) { swap(arr[j], arr[j - h]); } } h = h / 2; } } // print the array to a new file void Print(const char *f) { FILE *fp; fp = fopen(f, "w"); cout << "\n" << f << ": " << difftime(ed, op) << " ms" << endl; for (int i = 1; i <= maxn; i++) { fprintf(fp, "%d ", s[i]); } fprintf(fp, "\n"); } int main() { srand((unsigned)time(NULL)); //set time as random number seed init(); Print("origin.txt"); // use clock to timing op = clock(); BubbleSort(s, maxn); ed = clock(); Print("BubbleSort.txt"); op = clock(); InsertSort(s, maxn); ed = clock(); Print("InsertSort.txt"); op = clock(); MergeSort(s, 1, maxn); ed = clock(); Print("MergeSort.txt"); op = clock(); QuickSort(s, 1, maxn); ed = clock(); Print("QuickSort.txt"); op = clock(); ShellSort(s, maxn); ed = clock(); Print("ShellSort.txt"); return 0; }
true
f2a8bb804c2422eeaa536b76858df797a3e46e35
C++
nonanonno/CarND-Extended-Kalman-Filter-Project
/src/kalman_filter.cpp
UTF-8
1,545
2.890625
3
[ "MIT" ]
permissive
#include "kalman_filter.h" #include "tools.h" #include <cmath> #include <iostream> using Eigen::MatrixXd; using Eigen::VectorXd; // Please note that the Eigen library does not initialize // VectorXd or MatrixXd objects with zeros upon creation. void KalmanFilter::Initialize(const Eigen::VectorXd &x, const Eigen::MatrixXd &P) { x_ = x; P_ = P; F_ = MatrixXd::Identity(4, 4); I = MatrixXd::Identity(4, 4); } void KalmanFilter::Predict(float dt) { F_(0, 2) = dt; F_(1, 3) = dt; x_ = F_ * x_; P_ = F_ * P_ * F_.transpose() + Q_; } void KalmanFilter::Update(const VectorXd &z) { VectorXd y = z - H_ * x_; MatrixXd S = H_ * P_ * H_.transpose() + R_; MatrixXd K = P_ * H_.transpose() * S.inverse(); x_ = x_ + K * y; P_ = (I - K * H_) * P_; } namespace { VectorXd h(const MatrixXd &x) { VectorXd v(3); v(0) = sqrt(x(0) * x(0) + x(1) * x(1)); v(1) = atan2(x(1), x(0)); v(2) = (x(0) * x(2) + x(1) * x(3)) / v(0); return v; } } // namespace void KalmanFilter::UpdateEKF(const VectorXd &z) { auto hx = h(x_); std::cout << "z = " << z(0) << ", " << z(1) << ", " << z(2) << std::endl; std::cout << "hx = " << hx(0) << ", " << hx(1) << ", " << hx(2) << std::endl; VectorXd y = z - hx; if (y(1) > M_PI) { y(1) -= 2 * M_PI; } if (y(1) < -M_PI) { y(1) += 2 * M_PI; } std::cout << "y = " << y(0) << ", " << y(1) << ", " << y(2) << std::endl; MatrixXd S = H_ * P_ * H_.transpose() + R_; MatrixXd K = P_ * H_.transpose() * S.inverse(); x_ = x_ + K * y; P_ = (I - K * H_) * P_; }
true
1524d1a57f6f6174654aec7a059a7c933361a804
C++
xfw5/path-finder
/DepthStencilTarget.cpp
UTF-8
1,508
2.671875
3
[]
no_license
#include "DepthStencilTarget.h" #include "base\ccMacros.h" DepthStencilTarget::DepthStencilTarget() :_id("") , _packed(false) , _depthBuffer(0) , _stencilBuffer(0) , _width(0) , _height(0) { } DepthStencilTarget::~DepthStencilTarget() { if (_depthBuffer) { glDeleteRenderbuffers(1, &_depthBuffer); CHECK_GL_ERROR_DEBUG(); } if (_stencilBuffer) { glDeleteRenderbuffers(1, &_stencilBuffer); CHECK_GL_ERROR_DEBUG(); } } DepthStencilTarget* DepthStencilTarget::create(const char* id, DSType type, unsigned int width, unsigned int height) { auto* dst = new DepthStencilTarget(); if (dst && dst->init(id, type, width, height)) { dst->autorelease(); return dst; } CC_SAFE_DELETE(dst); return nullptr; } bool DepthStencilTarget::init(const char* id, DSType type, unsigned int width, unsigned int height) { GLint oldRBO; glGetIntegerv(GL_RENDERBUFFER_BINDING, &oldRBO); glGenRenderbuffers(1, &_depthBuffer); CHECK_GL_ERROR_DEBUG(); glBindRenderbuffer(GL_RENDERBUFFER, _depthBuffer); CHECK_GL_ERROR_DEBUG(); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); CHECK_GL_ERROR_DEBUG(); glBindRenderbuffer(GL_RENDERBUFFER, oldRBO); CHECK_GL_ERROR_DEBUG(); _id = id; _width = width; _height = height; _packed = true; return true; } GLuint DepthStencilTarget::getDepthBufferHandle() { return _depthBuffer; } GLuint DepthStencilTarget::getStencilBufferHandle() { return _stencilBuffer; } bool DepthStencilTarget::isPacked() { return _packed; }
true
ac67d604d65f8c54ffd4f72c7041fb571b301254
C++
arashnh11/Tetrahedra_pack
/Script/tet_script.h
UTF-8
1,430
2.890625
3
[ "MIT" ]
permissive
#include <vector> #include <math.h> using namespace std; int write_basis(){ vector<vector<double> > Base(3, vector<double>(3,0)); for (int i = 0; i <= Base.size() - 1; i++){ Base[i][i] = 1; } for (int j = 0; j <= Base.size() - 1; j++){ for (int i = 0; i <= Base[1].size() - 1; i++){ printf("%8.4f ", Base[j][i]); } printf("\n"); } printf("\n"); return 0; } int write_tet(vector<vector<double> > &Tet){ for (int j = 0; j <= Tet.size() - 1; j++){ for (int i = 0; i <= Tet[1].size() - 1; i++){ printf("%f ", Tet[j][i]); } if (j < Tet.size() - 1) printf(", "); } printf("\n"); return 0; } int write_pack(vector<vector<vector<double> > > &Pack){ FILE *f = fopen("Output.txt","w"); for (int k = 0; k <= Pack.size() - 1; k++){ for (int j = 0; j <= Pack[1].size() - 1; j++){ for (int i = 0; i <= Pack[1][1].size() - 1; i++){ printf("%8.4f ", Pack[k][j][i]); fprintf(f, "%8.4f ", Pack[k][j][i]); } // if (j < Pack[1].size() - 1) // printf(", "); } printf("\n"); fprintf(f, "\n"); } printf("\n"); fprintf(f, "\n"); fclose(f); return 0; } int write_tet_face(vector<vector<vector<double> > >Face){ for (int k = 0; k <= Face.size() - 1; k++){ for (int j = 0; j <= Face[1].size() - 1; j++){ for (int i = 0; i <= Face[1][1].size() - 1; i++){ printf("%f ", Face[k][j][i]); } if (j < Face[1].size() - 1) printf(","); } printf("\n"); } return 0; }
true
c207ddacb582b6e8d24e1e3375373eb268fad9ba
C++
GregVanK/PibbliePums
/Game/PibbliePums/PibbliePums/SoundNode.cpp
UTF-8
439
2.515625
3
[]
no_license
/* *@author: Greg VanKampen *@file: SoundsNode.cpp *@description: A class which contains sounds and its location */ #include "SoundNode.h" #include "SoundPlayer.h" GEX::SoundNode::SoundNode(SoundPlayer & player) :SceneNode(), _sounds(player) { } void GEX::SoundNode::playSound(SoundEffectID sound, sf::Vector2f position) { _sounds.play(sound, position); } unsigned int GEX::SoundNode::getCategory() const { return Category::SoundEffect; }
true
dede21d208324ba063b1e83c717b6f37beafa976
C++
jbuzzell/cacophony
/lib/Interval.h
UTF-8
1,148
3.171875
3
[ "MIT" ]
permissive
#ifndef INTERVAL_H #define INTERVAL_H #include "Note.h" /* ------------------------------------------------------------------------------------------------ - INTERVAL: a class containing dissonance information for two given notes and methods for - calculating dissonance - - members: - - numerator: the numerator of the just interval - - denominator: the denominator of the just interval - - dissonance: the dissonance of the just interval, calculated by adding num + den - - methods: - - getDissonance(): get dissonance of Interval object - - Interval::getDissonance(): get dissonance of the interval between two Notes - - setDissonance(): setter for member dissonance - - setNumeratorDenominator(): setter for numerator and denominator ------------------------------------------------------------------------------------------------ */ class Interval { public: Interval(Note one = 0, Note two = 0); int numerator; int denominator; int dissonance; int getDissonance(); static int getDissonance(Note one, Note two); private: void setDissonance(); void setNumeratorDenominator(Note one, Note two); }; #endif // !INTERVAL_H
true
036599a055192cf3df82854c4889ebeb9d2256c6
C++
Moumou38/FlappGL_Monia
/include/Cube.hpp
UTF-8
5,691
3.015625
3
[]
no_license
#pragma once #include <vector> #include <GL/glew.h> #include <Vertex.hpp> class Cube { private: unsigned int m_verticesCount; GLuint m_VAO; std::vector<Vertex> m_vertices; Cube(const Cube& cube); GLuint m_VBO[2]; Cube& operator=(const Cube& cube); public: Cube(){ } void initVertices(){ // Bottom face m_vertices.emplace_back(Vertex(-0.5f, -0.5f, 0.5f, 0.f, -1.f, 0.f, 0.f, 0.f)); m_vertices.emplace_back(Vertex(-0.5f, -0.5f, -0.5f, 0.f, -1.f, 0.f, 0.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, -0.5f, 0.f, -1.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, -0.5f, 0.f, -1.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, 0.5f, 0.f, -1.f, 0.f, 1.f, 0.f)); // Upper face m_vertices.emplace_back(Vertex(-0.5f, 0.5f, -0.5f, 0.f, 1.f, 0.f, 0.f, 0.f)); m_vertices.emplace_back(Vertex(-0.5f, 0.5f, 0.5f, 0.f, 1.f, 0.f, 0.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, 0.5f, 0.5f, 0.f, 1.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, 0.5f, 0.5f, 0.f, 1.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, 0.5f, -0.5f, 0.f, 1.f, 0.f, 1.f, 0.f)); // Left face m_vertices.emplace_back(Vertex(-0.5f, 0.5f, -0.5f, -1.f, 0.f, 0.f, 0.f, 0.f)); m_vertices.emplace_back(Vertex(-0.5f, -0.5f, -0.5f, -1.f, 0.f, 0.f, 0.f, 1.f)); m_vertices.emplace_back(Vertex(-0.5f, -0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(-0.5f, -0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(-0.5f, 0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 0.f)); // Right face m_vertices.emplace_back(Vertex(0.5f, 0.5f, 0.5f, 1.f, 0.f, 0.f, 0.f, 0.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, 0.5f, 1.f, 0.f, 0.f, 0.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, -0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 1.f)); m_vertices.emplace_back(Vertex(0.5f, 0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 0.f)); // Front face m_vertices.push_back(Vertex(-0.5f, 0.5f, 0.5f, 0.f, 0.f, 1.f, 0.f, 0.f)); m_vertices.push_back(Vertex(-0.5f, -0.5f, 0.5f, 0.f, 0.f, 1.f, 0.f, 1.f)); m_vertices.push_back(Vertex(0.5f, -0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 1.f)); m_vertices.push_back(Vertex(0.5f, -0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 1.f)); m_vertices.push_back(Vertex(0.5f, 0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 0.f)); // Back face m_vertices.push_back(Vertex(0.5f, 0.5f, -0.5f, 0.f, 0.f, -1.f, 0.f, 0.f)); m_vertices.push_back(Vertex(0.5f, -0.5f, -0.5f, 0.f, 0.f, -1.f, 0.f, 1.f)); m_vertices.push_back(Vertex(-0.5f, -0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 1.f)); m_vertices.push_back(Vertex(-0.5f, -0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 1.f)); m_vertices.push_back(Vertex(-0.5f, 0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 0.f)); } void init(){ /* // Load geometry int cube_triangleCount = 12; int cube_triangleList[] = {0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7, 8, 9, 10, 10, 9, 11, 12, 13, 14, 14, 13, 15, 16, 17, 18, 19, 17, 20, 21, 22, 23, 24, 25, 26, }; float cube_uvs[] = {0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, }; float cube_vertices[] = {-0.5, -0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, -0.5, -0.5, 0.5, -0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5 }; float cube_normals[] = {0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, }; */ initVertices(); unsigned int index[] = { 0, 1, 2, 3, 4, 0, 5, 6, 7, 8, 9, 5, 10, 11, 12, 13, 14, 10, 15, 16, 17, 18, 19, 15, 20, 21, 22, 23, 24, 20, 25, 26, 27, 28, 29, 25 }; m_verticesCount = sizeof(index)/sizeof(unsigned int); glGenBuffers(2, m_VBO); glGenVertexArrays(1, &m_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_VBO[0]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(index), index, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, m_VBO[1]); glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex)*m_vertices.size(), &m_vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, position)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, normal_coords)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)offsetof(Vertex, tex_coords)); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void render() const{ glBindVertexArray(m_VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_VBO[0]); glDrawElements(GL_TRIANGLES, m_verticesCount, GL_UNSIGNED_INT, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindVertexArray(0); } ~Cube(){ glDeleteBuffers(2, m_VBO); glDeleteVertexArrays(1, &m_VAO); } };
true
66d0ff60bf8545865a95063fdbad930cf6087d55
C++
hamzaig/cplusplus
/Calculator.cpp
UTF-8
181
3.078125
3
[]
no_license
#include <iostream> using namespace std; int main() { int x,y,z,sum; cout<<"Enter First Second And Third Number\n"; cin>>x>>y>>z; sum=x+y+z; cout<<"Your Answer Is: "<<sum; }
true
60982a621e997c16ce90fd388a941b675bf379c7
C++
Jvanrhijn/hopscotch
/lib/game/tile.h
UTF-8
966
2.75
3
[]
no_license
// // Created by Guthorak on 10/22/18. // #ifndef __PIE_SRC_TILE_H #define __PIE_SRC_TILE_H #include <utility> #include <vector> #include <memory> #include "optional.h" #include "renderer/drawable.h" namespace pie { //! Class representing a single Tile on the game board class Tile { public: Tile(size_t row, size_t column); Tile() = default; //! Returns true if the tile has a value bool IsSet() const; // getters const std::pair<size_t, size_t> &coordinates() const; const Optional<size_t> &value() const; const std::vector<std::shared_ptr<Tile>> &reachables() const; // setters void set_value(size_t value); void set_coordinates(size_t, size_t); //! Adds tile to list of reachable tiles from this void add_reachable(std::shared_ptr<Tile> tile); private: Optional<size_t> value_; std::vector<std::shared_ptr<Tile>> reachables_; std::pair<size_t, size_t> coordinates_; }; } //namespace pie #endif //__PIE_SRC_TILE_H
true
b314ee9a27afa85e21f0a0bac07c75b25b93b73f
C++
WeakBoss/hello-world
/Clock.cpp
GB18030
2,129
3
3
[]
no_license
#include <iostream> #include <windows.h> #include <time.h> #include <conio.h> using namespace std; class Clock { public: Clock(int h, int m, int s); Clock(); ~Clock() {}; void tick(); void show(); void adjust(); void alarm(); void system(); void rang(); private: time_t timep; time_t timea; bool is_alarm; bool is_rang; int rang_time; }; Clock::Clock(int h, int m, int s) { time(&timep); struct tm*p = localtime(&timep); p->tm_hour = h; p->tm_min = m; p->tm_sec = s; timep = mktime(p); timep++; is_alarm = false; is_rang=false; rang_time= 60; } Clock::Clock() { time(&timep); timep++; is_alarm =is_rang= false; rang_time = 60; } void Clock::tick() { timep++; } void Clock::show() { cout << ctime(&timep)<<endl; } void Clock::system() { if (_kbhit() != 0) { cout << "ѡ" << endl << "1 ʱ 2 " << endl; int key; cin >> key; switch (key) { case 1: adjust(); break; case 2: alarm(); break; } } if (is_alarm) { struct tm*p = localtime(&timea); cout << "alarm:" << p->tm_hour << ":" << p->tm_min << ":" << p->tm_sec <<"\t"; } else { cout << "no alarm \t" ; } if (is_rang) { cout << "ranging\t" <<"letf "<<rang_time<<" seconds"<< endl; } else { cout << "no rang" << endl; } if (timep == timea) { is_rang = true; } if (rang_time == 0) { is_alarm = is_rang = false; rang_time = 60; } } void Clock::adjust() { cout << " ʱ " << endl; int h, m, s; cin >> h >> m >> s; struct tm*p = localtime(&timep); p->tm_hour = h; p->tm_min = m; p->tm_sec = s; timep = mktime(p); } void Clock::alarm() { cout << " ʱ " << endl; int h, m, s; cin >> h >> m >> s; time(&timea); struct tm*p = localtime(&timea); p->tm_hour = h; p->tm_min = m; p->tm_sec = s; timea = mktime(p); is_alarm = true; timep += 5; } void Clock::rang() { if (is_rang) { cout << '\a'; rang_time--; } } int main() { Clock ck; while (true) { ck.show(); cout << "ʱ 밴" << endl; ck.tick(); ck.system(); ck.rang(); Sleep(890); system("cls"); } }
true
255e2e5a5c20d9796390887cc4d35bcd893a0299
C++
basimkhajwal/ProgrammingChallenges
/Code Forces/0982/b.cpp
UTF-8
864
2.546875
3
[]
no_license
#include <cstdio> #include <algorithm> #include <set> using namespace std; #define MAXN 210000 int N; pair<int,int> W[MAXN]; set<pair<int, int> > empty, ones; int main() { scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &W[i].first); W[i].second = i+1; } empty = set<pair<int,int>>(W, W+N); for (int i = 0; i < 2*N; i++) { char c; scanf(" %c", &c); if (c == '0') { pair<int,int> a = *empty.begin(); printf("%d", a.second); ones.insert(a); empty.erase(empty.begin()); } else { pair<int,int> a = *ones.rbegin(); printf("%d", a.second); ones.erase(--ones.end()); } if (i < 2*N-1) printf(" "); else printf("\n"); } return 0; };
true
fb409908603f81445edeea9807fb7f3570169e86
C++
GuanqunGe/Cpp-Primer_Exercise
/Chapter_15/ex_15_37/Query_base.h
UTF-8
687
2.703125
3
[]
no_license
#ifndef QUERY_BASE #define QUERY_BASE #include "TextQuery.h" #include "QueryResult.h" #include <string> class Query_base{ // don't know why we need a friend class Query // --> so that we can call the virtual rep() function and destructor of Query_base class through Query. // but why isn't Query also friend of the derived class?? friend class Query; friend class OrQuery; friend class NotQuery; friend class AndQuery; friend class BinaryQuery; protected: using line_no = TextQuery::line_no; virtual ~Query_base() = default; private: virtual QueryResult eval(const TextQuery &) const = 0; virtual std::string rep() const = 0; }; #endif
true
36d58f869a1ff97dd5840f25c195b31c63baaff7
C++
SergeyLebedkin/VulkanPlayground
/build/msvs2017/apps/vulkan_glfw_app/vulkan_loaders.cpp
UTF-8
1,566
2.828125
3
[ "MIT" ]
permissive
#include "vulkan_loaders.hpp" #include <algorithm> #include <string> #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #pragma warning(push) #pragma warning(disable: 4996) #include <stb_image.h> #include <stb_image_write.h> #pragma warning(pop) // createImageProcedural void createImageProcedural( VulkanDevice& device, uint32_t width, uint32_t height, VulkanImage& image) { // create data for image struct pixel_u8 { uint8_t r, g, b, a; }; pixel_u8 color0{ 255, 128, 000, 255 }; pixel_u8 color1{ 255, 255, 255, 255 }; pixel_u8* texData = new pixel_u8[width * height]; // create image instance vulkanImageCreate(device, VK_FORMAT_R8G8B8A8_UNORM, width, height, 1, &image); // fill image buffer for (uint32_t i = 0; i < height; i++) { for (uint32_t j = 0; j < width; j++) { if (((i / 32) % 2) == 0) texData[i*width + j] = color0; else texData[i*width + j] = color1; } } vulkanImageWrite(device, image, 0, texData); vulkanImageBuildMipmaps(device, image); delete[] texData; } // loadImageFromFile void loadImageFromFile( VulkanDevice& device, VulkanImage& image, std::string fileName) { // load image data from file int width = 0, height = 0, channels = 0; stbi_uc* texData = stbi_load(fileName.data(), &width, &height, &channels, 4); // create and setup vulkan image vulkanImageCreate(device, VK_FORMAT_R8G8B8A8_UNORM, width, height, 1, &image); vulkanImageWrite(device, image, 0, texData); vulkanImageBuildMipmaps(device, image); // free image data stbi_image_free(texData); }
true
68bf12fcef4b08ee749592cc5985e517cf5e243e
C++
pastly/yaps-cli
/Database.h
UTF-8
1,018
3.078125
3
[]
no_license
#ifndef DATABASE_H #define DATABASE_H #include "Tree.h" #include "Entry.h" #include "FileIO.h" #include <string> class Database { private: //std::string m_name; std::string m_path; std::string m_password; // may not be needed, not sure Tree<Entry> m_entries; public: void setName(std::string name) {m_entries.getRoot().setTitle(name);} void setPath(std::string path) {m_path = path;} void setPassword(std::string password) {m_password = password;} std::string getName() {return m_entries.getRoot().getTitle();} std::string getPath() {return m_path;} Tree<Entry> &getEntries() {return m_entries;} //std::string getPassword() {return m_password;} uint64_t addEntry(Entry entry, uint64_t parent); void removeEntry(uint64_t id); std::string print(Tree<Entry>* subTree = nullptr); // if left default (nullptr), entire db will be printed void saveToFile(std::string fileName); void readFromFile(std::string fileName); Database(); }; #endif // DATABASE_H
true
ba0ccb0b40a27d9cb22699ae687127a0a96e9233
C++
benbraide/ewin
/ewin/ewin/drawing/com_native.h
UTF-8
1,898
3.0625
3
[ "MIT" ]
permissive
#pragma once #ifndef EWIN_COM_NATIVE_H #define EWIN_COM_NATIVE_H #include "../common/boolean_property.h" #include "../common/object_property.h" namespace ewin::drawing{ template <class native_type> class com_native{ public: typedef native_type native_type; struct create_info{}; com_native() : native_(nullptr){ native.initialize_(nullptr, [this](void *prop, void *arg, common::property_access access){ *static_cast<native_type **>(arg) = native_; }); created.initialize_(nullptr, [this](void *prop, void *arg, common::property_access access){ if (access == common::property_access::write) create_(*static_cast<bool *>(arg), nullptr); else if (access == common::property_access::read) *static_cast<bool *>(arg) = (native_ != nullptr); }); } virtual ~com_native(){ if (native_ != nullptr){ native_->Release(); native_ = nullptr; } } com_native(const com_native &) = delete; com_native &operator =(const com_native &) = delete; common::read_only_object_value_property<native_type, com_native> native; common::boolean_value_property<com_native> created; protected: virtual void create_(bool create, const create_info *info){ if (!create && native_ != nullptr){ native_->Release(); native_ = nullptr; } } native_type *native_; }; template <class native_type> class shared_com_native : public com_native<native_type>{ public: explicit shared_com_native(native_type *value){ native_ = value; } shared_com_native(const shared_com_native &other){ if ((native_ = other.native_) != nullptr) native_->AddRef(); } shared_com_native &operator =(const shared_com_native &other){ if (native_ != nullptr)//Release previous native_->Release(); if ((native_ = other.native_) != nullptr) native_->AddRef(); return *this; } }; } #endif /* !EWIN_COM_NATIVE_H */
true
d1082e74c7b49d6a299a1a781296554681054094
C++
mukuld/cpp
/alphabet.cpp
UTF-8
182
3.109375
3
[]
no_license
#include <stdio.h> int main(void) { //Loop to print the alphabets in capitals for (char i = 30; i < 127; i++) printf("%c ", i); char endline = '\n'; printf("%c", endline); }
true
682fc97f48139e5d6a1ed2e50b410b30d65dcb14
C++
BGMer7/LeetCode
/33. Search in Rotated Sorted Array/search.cpp
UTF-8
2,064
3.75
4
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; class Solution { public: int search(vector<int> &nums, int target) { // nums = { 4,1,2,3 }; int size = nums.size(); if (size == 0) return -1; if (size == 1 && nums[0] != target) return -1; else if (size == 1 && nums[0] == target) return 0; int i = 0; while (nums[i] < nums[i + 1] && i < size - 2) i++; int res = -1; if (nums[i + 1] == target) { res = i + 1; } else { res = binarySearch(nums, i + 2, size - 1, target); if (res == -1) { res = binarySearch(nums, 0, i, target); } } return res; } private: int binarySearch(vector<int> nums, int left, int right, int target) { while (left <= right) { int middle = left + (right - left) / 2; if (nums[middle] == target) return middle; else if (nums[middle] < target) left = middle + 1; else if (nums[middle] > target) right = middle - 1; } return -1; } }; class SolutionNew { private: int binarySearch(vector<int> &nums, int target, int start, int end) { int left = start, right = end - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } public: int search(vector<int> &nums, int target) { int left = 0, right = nums.size() - 1; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] < nums[right]) right = mid; else if (nums[mid] > nums[right]) left = mid + 1; else --right; } cout << left << endl; int leftRes = binarySearch(nums, target, 0, left); int rightRes = binarySearch(nums, target, left, nums.size()); cout << leftRes << " " << rightRes << endl; if (leftRes == -1 && rightRes == -1) return -1; else if (leftRes == -1) return rightRes; else return leftRes; return -1; } }; int main() { Solution s; vector<int> nums{1, 3}; int res = s.search(nums, 0); cout << res << endl; }
true
6d73210cc523cde436de6ec60ac88687ebc43dfb
C++
TWA2Jerry/PCS
/Problems/Moocast.cpp
UTF-8
1,057
2.734375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(void){ int num_cows; scanf("%d", &num_cows); vector <tuple<int, int, int>> cows_vector; queue <int> q; bool visited[num_cows]; for(int i = 0; i<num_cows; i++){ int x,y,p; scanf("%d %d %d", &x, &y, &p); cows_vector.push_back({x,y,p}); visited[i] = false; } int max_num = 0; for(int i = 0; i<num_cows; i++){ q.push(i); visited[i] = true; int current_max = 1; while(!q.empty()){ int a = q.front(); q.pop(); int x1 = get<0>(cows_vector[a]); int y1 = get<1>(cows_vector[a]); int power = get<2>(cows_vector[a]); for(int j = 0; j<num_cows; j++){ if(visited[j]) continue; int x2 = get<0>(cows_vector[j]); int y2 = get<1>(cows_vector[j]); if(pow(power, 2) >= pow(x2-x1, 2)+pow(y2-y1, 2)){ current_max++; visited[j] = true; q.push(j); } } } if (current_max > max_num) max_num = current_max; for(int j = 0; j<num_cows; j++){ visited[j] = false; } } printf("%d\n", max_num); return 0; }
true
a3cae87a4b470aed7dc33d9423f5120a25dcb4c0
C++
ankushgarg1998/Competitive_Coding
/contests/codechef-contests/LTIME54/second.cpp
UTF-8
1,286
3
3
[]
no_license
#include <iostream> #include<cmath> #include<vector> using namespace std; int main() { int t; long int X, Y, M, i; cin>>t; while(t--) { cin>>M>>X>>Y; if(X == 0) { cout<< (M^(M-1)) <<"\n"; continue; } vector<long int> A(M); for(i=1; i<=M; i++) A[i-1] = i; while(M > 2) { for(auto a:A) cout<<a<<" "; cout<<"\n"; vector<long int> eve; vector<long int> odd; for(i=0; i<M; i+=2) eve.push_back(A[i]); for(i=1; i<M; i+=2) odd.push_back(A[i]); eve.erase(eve.begin() + ((M/2)*X/Y)); odd.erase(odd.begin() + ((M/2)*X/Y)); for(auto e:eve) cout<<e<<" "; cout<<"Eve\n"; for(auto o:odd) cout<<o<<" "; cout<<"Odd\n"; A.clear(); M -= 2; A.reserve(M); A.insert(A.end(), eve.begin(), eve.end() ); A.insert(A.end(), odd.begin(), odd.end() ); // eve.clear(); // odd.clear(); } cout<< (A[0]^A[1]) <<"\n"; } return 0; }
true
0f4d488aaadda869197d77fabf03cc9ee8647849
C++
microsoft/onnxruntime-openenclave
/samples/c_cxx/imagenet/local_filesystem_win.cc
UTF-8
2,396
2.703125
3
[ "MIT" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "local_filesystem.h" #include <assert.h> #include <mutex> static std::mutex m; void ReadFileAsString(const ORTCHAR_T* fname, void*& p, size_t& len) { if (!fname) { throw std::runtime_error("ReadFileAsString: 'fname' cannot be NULL"); } HANDLE hFile = CreateFileW(fname, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { int err = GetLastError(); std::ostringstream oss; oss << "open file " << fname << " fail, errcode =" << err; throw std::runtime_error(oss.str().c_str()); } std::unique_ptr<void, decltype(&CloseHandle)> handler_holder(hFile, CloseHandle); LARGE_INTEGER filesize; if (!GetFileSizeEx(hFile, &filesize)) { int err = GetLastError(); std::ostringstream oss; oss << "GetFileSizeEx file " << fname << " fail, errcode =" << err; throw std::runtime_error(oss.str().c_str()); } if (static_cast<ULONGLONG>(filesize.QuadPart) > std::numeric_limits<size_t>::max()) { throw std::runtime_error("ReadFileAsString: File is too large"); } len = static_cast<size_t>(filesize.QuadPart); // check the file file for avoiding allocating a zero length buffer if (len == 0) { // empty file p = nullptr; len = 0; return; } std::unique_ptr<char[]> buffer(reinterpret_cast<char*>(malloc(len))); char* wptr = reinterpret_cast<char*>(buffer.get()); size_t length_remain = len; DWORD bytes_read = 0; for (; length_remain > 0; wptr += bytes_read, length_remain -= bytes_read) { // read at most 1GB each time DWORD bytes_to_read; if (length_remain > (1 << 30)) { bytes_to_read = 1 << 30; } else { bytes_to_read = static_cast<DWORD>(length_remain); } if (ReadFile(hFile, wptr, bytes_to_read, &bytes_read, nullptr) != TRUE) { int err = GetLastError(); p = nullptr; len = 0; std::ostringstream oss; oss << "ReadFile " << fname << " fail, errcode =" << err; throw std::runtime_error(oss.str().c_str()); } if (bytes_read != bytes_to_read) { p = nullptr; len = 0; std::ostringstream oss; oss << "ReadFile " << fname << " fail: unexpected end"; throw std::runtime_error(oss.str().c_str()); } } p = buffer.release(); return; }
true
eba7d514fdb4402c9a3f7aca066e186bf165daa9
C++
lmd-luxoft/labwork-MaximWeingarten
/qt-03-containers-and-qstring/main.cpp
UTF-8
2,047
3.53125
4
[]
no_license
#include <QCoreApplication> #include <QDebug> #include <QStack> int main(int argc, char *argv[]) { QList<QString> names; names << "Mary" << "Ann" << "Charlynn" << "Marylynn" << "Margaret" << "Kate" << "Rose" << "Gwendolyn"; // TODO: using Java-style iterators print the longest name from the list QListIterator<QString> i(names); QString longest = ""; while (i.hasNext()) { auto nxt = i.next(); if (nxt.size()>longest.size()) { longest = nxt; } } // use QString::arg to output message with this name QString message = "The longest name is %1."; qDebug()<<message.arg(longest); // TODO: using STL-style iterators print the shortest name from the list QString shortest = names.at(0); for (auto it = names.begin()+1;it!=names.end();it++) { if (it->size()<shortest.size()) { shortest = *it; } } // use QString::prepend and append to output message with this name shortest.prepend("The shortest string is "); shortest.append("."); qDebug()<<shortest; // TODO: using foreach and QStringList show all names with "lynn" suffix QString separator = ""; QList<QString> lynnList; for (auto &s: names) { if (s.endsWith("lynn")) { lynnList << s; } } qDebug()<<lynnList.join(", "); // and print it separated by ',' as one string // print all names in reverse order // TODO: 1. Using QStack qDebug()<<"reverse with stack"; QStack<QString> stack; for (auto &s: names) { stack.push(s); } while (!stack.empty()) { qDebug()<<stack.pop(); } // TODO: 2. Using other QList qDebug()<<"reverse with list"; QList rnames(names.rbegin(), names.rend()); qDebug()<<rnames.join(", "); // TODO: 3. Without other containers qDebug()<<"reverse with riterator"; for(auto it = names.rbegin(); it!= names.rend(); it++) { qDebug()<<*it; } }
true
31d138e22cb6869b844f1da1946574aa59730a72
C++
rahulr56/OpenMP
/OpenMP_examples/OpenMP_Course/intergal.cpp
UTF-8
298
2.875
3
[]
no_license
#include <iostream> static long num_steps =100000; double step; int main() { int i; double x,pi,sum=0.0; step = 1.0/(double)num_steps; for (i=0; i<num_steps;i++) { x=(i+0.5)*step; sum += 4.0/(1.0+x*x); } pi = step * sum; std::cout<<pi<<std::endl; }
true
7ba4a3526c8f187f0fb9e3b9dc5fabfdf8e1e8af
C++
MRdoulestar/userAVL
/dog4u.h
UTF-8
2,313
2.78125
3
[ "MIT" ]
permissive
//@author //Xingxin YU #include<iostream> #include<string.h> #include<cstring> #include<vector> #include<unistd.h> #include<cstring> #include<sys/socket.h> #include<netinet/in.h> #include<arpa/inet.h> #include<stdio.h> #include<stdlib.h> #define USER_FILE "user.txt" //工具类 class Utils { public: static std::vector<std::string> split(std::string, char dot); //字符串分割 static size_t hash(std::string str); //字符串哈希成数字 }; //AVL节点类 class AVLnode { private: size_t key; //节点id std::string username; //节点中存储的用户名 std::string password; //节点中用户对应的密码 public: int bf; //节点平衡因子 AVLnode *left; //左子节点 AVLnode *right; //右子节点 AVLnode *parent;//父节点 AVLnode(size_t key, std::string username, std::string password, AVLnode *left=NULL, AVLnode *right=NULL, AVLnode *parent=NULL): key(key), username(username), password(password), left(left), right(right), parent(parent){} AVLnode(){} size_t getKey(); void setKey(size_t key); std::string getUsername(); void setUsername(std::string username); std::string getPassword(); void setPassword(std::string password); }; //AVL树类,包括对该树的所有操作 class AVL { private: AVLnode *root; //根节点 //对AVL树的插入和删除 void AVLinsert(AVLnode* node); void AVLremove(std::string username); //旋转操作 void leftRotate(AVLnode* NBnode); void rightRotate(AVLnode* NBnode); void lrRotate(AVLnode* NBnode); void rlRotate(AVLnode* NBnode); public: int height; //树的高度 unsigned long num; //节点个数 std::vector<AVLnode> vec; //所有用户名数据 //std::vector<std::string> vec_p; //所有密码数据 //AVL树的遍历 void traversal(AVLnode* T); //用户查找 std::string findUser(size_t key); AVLnode* getRoot(); AVL(); //构造函数 ~AVL(); //析构函数 //对用户的增删改查 void search(std::string username); void insert(std::string username, std::string password); void remove(std::string username); }; //程序初始化类 class Init { private: int socket_fd, accept_fd; sockaddr_in myserver; sockaddr_in remote_addr; public: AVL usertree; Init(int port); int recv_msg(); int mysend(int *socket, char* buffer, int len); bool login(int socket); };
true
ffaf6871fdcea4988be0b113104a5c65a4e7ac9d
C++
jfhamlin/perry
/Romulus/Source/Resource/SphereGeometryProvider.cpp
UTF-8
6,101
2.734375
3
[]
no_license
#include "Math/Constants.h" #include "Math/Vector.h" #include "Math/Bounds/BoundingVolumes.h" #include "Resource/SphereGeometryProvider.h" #include "Render/SimpleGeometryChunk.h" #include <boost/scoped_array.hpp> #include <cmath> namespace romulus { using math::Pi; using math::Vector2; using math::Vector3; IMPLEMENT_RTTI(ProceduralSphereArguments); void SphereGeometryProvider::UnloadResource(ResourceHandleBase::id_t id) { ArgumentsMap::iterator argsIt = m_arguments.find(id); if (argsIt != m_arguments.end()) { SphereMap::iterator sphereIt = m_spheres.find(argsIt->second); ASSERT(sphereIt != m_spheres.end()); m_arguments.erase(argsIt); m_spheres.erase(sphereIt); } } int SphereGeometryProvider::HandleType() const { return render::GeometryHandle::HandleType(); } void* SphereGeometryProvider::GetResource(ResourceHandleBase::id_t id) { ArgumentsMap::const_iterator argsIt = m_arguments.find(id); if (argsIt != m_arguments.end()) { SphereMap::const_iterator sphereIt = m_spheres.find(argsIt->second); ASSERT(sphereIt != m_spheres.end()); return static_cast<void*>( static_cast<render::GeometryChunk*>(sphereIt->second.get())); } return 0; } bool SphereGeometryProvider::GenerateResource( const ProceduralResourceArguments& arguments, ResourceHandleBase::id_t& id) { if (IsExactType<ProceduralSphereArguments>(arguments)) { const ProceduralSphereArguments& sphereArgs = static_cast<const ProceduralSphereArguments&>(arguments); if (sphereArgs.LongitudinalSegments < 3 || sphereArgs.LatitudinalSegments < 2) return false; std::pair<uint_t, uint_t> argKey = std::make_pair(sphereArgs.LongitudinalSegments, sphereArgs.LatitudinalSegments); IDMap::const_iterator idIt = m_ids.find(argKey); if (idIt == m_ids.end()) id = CreateNewSphere(argKey); else id = idIt->second; return true; } return false; } ResourceHandleBase::id_t SphereGeometryProvider::CreateNewSphere( const std::pair<uint_t, uint_t>& lonLatSegments) { const real_t radius = 1.f; boost::shared_ptr<render::SimpleGeometryChunk sphere( new render::SimpleGeometryChunk); ResourceHandleBase::id_t id = m_nextResourceID++; // There are (#latitudinal segments)-1 vertices for each longitudinal line, // plus the singular pole vertices. // There are (#longitudinal segments) longitudinal lines. // This constant does not include the pole vertices. const uint_t numVerticesPerLongitudeLine = lonLatSegments.second - 1; // Make "North" pole, which has index 0. sphere->AddVertex(radius * Vector3(0, 1, 0), Vector3(0, 1, 0), Vector2(.5f, 1)); const uint_t northIndex = 0; // Make "South" pole, which has index 1. sphere->AddVertex(radius * Vector3(0, -1, 0), Vector3(0, -1, 0), Vector2(.5f, 0)); const uint_t southIndex = 1; // We call longitude theta, ranging from 0 to 2*pi radians. We call // latitude phi, ranging from -pi/2 to pi/2 radians. // x = cos(theta) * cos(phi) // y = sin(phi) // z = - sin(theta) * cos(phi) // Since we only create unit spheres, the normal is equal to the vertex. // For texture coordinates, U increases with theta, V with phi. const real_t deltaU = 1.f / static_cast<real_t>(lonLatSegments.first); const real_t deltaV = 1.f / static_cast<real_t>(lonLatSegments.second); real_t u = 0.f; real_t v = deltaV; const real_t deltaTheta = 2.f * Pi * deltaU; const real_t deltaPhi = Pi * deltaV; real_t theta = 0.f; real_t phi = - .5f * Pi + deltaPhi; // Omit the south pole vertex. uint_t i, j; // Create the first longitudinal row of vertices, where theta=0. for (i = 0; i < numVerticesPerLongitudeLine; ++i, phi += deltaPhi, v += deltaV) { const real_t cp = cos(phi); const real_t sp = sin(phi); Vector3 vertex(cp, sp, 0); sphere->AddVertex(radius * vertex, vertex, Vector2(u, v)); } for (i = 1, u = deltaU, theta = deltaTheta; i < lonLatSegments.first + 1; ++i, u += deltaU, theta += deltaTheta) { const real_t ct = cos(theta); const real_t st = sin(theta); for (j = 0, phi = - .5f * Pi + deltaPhi, v = deltaV; j < numVerticesPerLongitudeLine; ++j, phi += deltaPhi, v += deltaV) { const real_t cp = cos(phi); const real_t sp = sin(phi); Vector3 vertex(ct * cp, sp, - st * cp); sphere->AddVertex(radius * vertex, vertex, Vector2(u, v)); } const uint_t firstCurrentLonIndex = 2 + i * numVerticesPerLongitudeLine; const uint_t firstLastLonIndex = firstCurrentLonIndex - numVerticesPerLongitudeLine; // Fill in the faces between these vertices and the last set. // Start with the tri incident on the south pole. sphere->AddFace(southIndex, firstCurrentLonIndex, firstLastLonIndex); // Fill in the quads. for (j = 1; j < numVerticesPerLongitudeLine; ++j) sphere->AddFace(firstCurrentLonIndex + j, firstLastLonIndex + j, firstLastLonIndex + j - 1, firstCurrentLonIndex + j - 1); // End with the tri incident on the north pole. sphere->AddFace(northIndex, firstLastLonIndex + numVerticesPerLongitudeLine - 1, firstCurrentLonIndex + numVerticesPerLongitudeLine - 1); } sphere->ComputeTangents(); sphere->SetBoundingVolume(math::BoundingSphere(Vector3(0.f), radius)); m_arguments.insert(make_pair(id, lonLatSegments)); m_ids.insert(make_pair(lonLatSegments, id)); m_spheres.insert(make_pair(lonLatSegments, sphere)); return id; } } // namespace romulus
true
eb2a9a7fe3ec0d69f8de80356791a10f5d556004
C++
mzry1992/workspace
/OJ/sgu/500_gen.cpp
UTF-8
2,230
2.859375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; const double eps = 1e-8; struct Point { double x,y; Point(){} Point(double _x,double _y) { x = _x; y = _y; } Point operator -(const Point& b)const { return Point(x-b.x,y-b.y); } double operator *(const Point& b)const { return x*b.y-y*b.x; } double operator &(const Point& b)const { return x*b.x+y*b.y; } }; struct Line { Point s,e; Line(){} Line(Point _s,Point _e) { s = _s; e = _e; } }; double Norm(Point p) { return sqrt(p&p); } Point getPoint(int r,Line l) { while (true) { Point p = Point(rand()%(2*r+1)-r,rand()%(2*r+1)-r); if (Norm(p) >= 0.9*r) continue; if ((p-l.s)*(l.e-l.s) > 0) continue; return p; } } bool conPoint(Point p[],int n) { for (int i = 1;i < n;i++) if (p[i].x != p[0].x || p[i].y != p[0].y) return false; return true; } bool conLine(Point p[],int n) { for (int i = 2;i < n;i++) if ((p[i]-p[0])*(p[1]-p[0]) != 0) return false; return true; } bool GScmp(Point a,Point b) { if (fabs(a.x-b.x) < eps) return a.y < b.y-eps; return a.x < b.x-eps; } void GS(Point p[],int n,Point res[],int &resn) { resn = 0; int top = 0; sort(p,p+n,GScmp); if (conPoint(p,n)) { res[resn++] = p[0]; return; } if (conLine(p,n)) { res[resn++] = p[0]; res[resn++] = p[n-1]; return; } for (int i = 0;i < n;) if (resn < 2 || (res[resn-1]-res[resn-2])*(p[i]-res[resn-1]) > 0) res[resn++] = p[i++]; else --resn; top = resn-1; for (int i = n-2;i >= 0;) if (resn < top+2 || (res[resn-1]-res[resn-2])*(p[i]-res[resn-1]) > 0) res[resn++] = p[i--]; else --resn; resn--; } Point tmp[100000],op[100000]; void getPoly(int r,Line l) { int n = rand()%50000+1; for (int i = 0;i < n;i++) tmp[i] = getPoint(r,l); int tn = n; GS(tmp,tn,op,n); printf("%d\n",n); for (int i = 0;i < n;i++) printf("%.0f %.0f\n",op[i].x,op[i].y); } int main() { srand(time(0)); for (int cas = 1;cas <= 1;cas++) { int r = 1000000000; printf("%d\n",r); Point vp = getPoint(r,Line(Point(1,1),Point(0,1))); getPoly(r,Line(Point(0,0),vp)); getPoly(r,Line(vp,Point(0,0))); } printf("0 0\n"); return 0; }
true