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
88267a32303036020d92bad43621585734d039e0
C++
hrishikeshgoyal/leetcode_programs
/binaryTreePaths/binaryTreePaths.cpp
UTF-8
1,710
3.421875
3
[]
no_license
class Solution { public: vector<string> TreePaths; void DFS(TreeNode* node, string answer) { answer += "->" + to_string(node->val); if(node->left == NULL && node->right == NULL) TreePaths.push_back(answer); else { if(node->left != NULL) DFS(node->left, answer); if(node->right != NULL) DFS(node->right, answer); } } vector<string> binaryTreePaths(TreeNode* root) { if(root != NULL) { DFS(root, ""); for(int i = 0; i < TreePaths.size(); i++) TreePaths[i].erase(TreePaths[i].begin(), TreePaths[i].begin() + 2); } return TreePaths; } }; class Solution { public: void binaryTreePathsHelper(TreeNode* root, vector<int> solution, vector<string>& result ) { if (!root) return; solution.push_back(root->val); //meet the leaf node, shape a path into the result if (root->left==NULL && root->right==NULL){ if(solution.size()>0){ stringstream ss; for(int i=0; i<solution.size(); i++){ ss << solution[i] << (i<solution.size()-1 ? "->":""); } result.push_back(ss.str()); } return; } binaryTreePathsHelper(root->left, solution, result); binaryTreePathsHelper(root->right, solution, result); } vector<string> binaryTreePaths(TreeNode* root) { vector<string> result; vector<int> solution; binaryTreePathsHelper(root, solution, result); return result; } };
true
93fa4ef6acc116ab6a0a2c58a88964947a07b742
C++
rzwm/oglpg8
/src/2.Subroutines/Subroutines.cpp
UTF-8
2,298
2.84375
3
[]
no_license
/////////////////////////////////////////////// // 简介: // 根据 2.6 着色器子程序 一节,练习使用着色器 // 子程序。在顶点着色器中实现两个子程序-红色 // 和蓝色,在软件端选择要使用的子程序以改变三 // 角形的颜色。 // /////////////////////////////////////////////// #include "GL/glew.h" #include "GL/freeglut.h" #include <iostream> #include "LoadShaders.h" GLuint VAO; GLuint VBO; GLuint g_program; void display() { glClear(GL_COLOR_BUFFER_BIT); if (0 != g_program) { glUseProgram(g_program); // 书中的“注意”有说明:调用glUseProgram()时会重新设置所有子程序uniform的值, // 所以这里每次都要重新设置。 { GLint location = glGetSubroutineUniformLocation(g_program, GL_VERTEX_SHADER, "selected_func_color"); if (location != -1) { // 把“Blue”改为“Red”试试! GLuint index = glGetSubroutineIndex(g_program, GL_VERTEX_SHADER, "Blue"); if (index != GL_INVALID_INDEX) { glUniformSubroutinesuiv(GL_VERTEX_SHADER, 1, &index); } } } glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); } glutSwapBuffers(); } void init() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); GLfloat vertices[] = { -0.5f, -1.0f, 0.5f, -1.0f, 0.0f, 1.0f }; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); ShaderInfo shaders[] = { { GL_VERTEX_SHADER, "Subroutines.vs" }, { GL_FRAGMENT_SHADER, "Subroutines.fs" }, { GL_NONE, "" } }; g_program = loadShaders(shaders); if (0 != g_program) { glUseProgram(g_program); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (const void*)0); glEnableVertexAttribArray(0); } } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA); glutInitWindowSize(512, 512); glutInitWindowPosition(100, 100); glutInitContextVersion(4, 3); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow(argv[0]); if (glewInit() != GLEW_OK) { std::cerr << "Unable to initialize GLEW ... exiting" << std::endl; exit(EXIT_FAILURE); } glutDisplayFunc(display); init(); glutMainLoop(); return 0; }
true
5be046b5b00683b50d5856ac79715e8e6da6c50c
C++
Hyiker/CampusNavigation
/src/model/physical/building.cc
UTF-8
1,232
2.796875
3
[]
no_license
#include "model/physical/building.h" #include "error/errors.hpp" #include "model/physical/path.h" using namespace std; Building::Building(string name) : PhysicalModel{name} { } void Building::init(Id id, vector<string>& params) { this->set_id(id); // TODO if (params.size() < 8) { // TODO: throw error here return; } this->set_name(params[2]); this->coordinate.push_back(stod(params[3])); this->coordinate.push_back(stod(params[4])); this->width = stod(params[5]); this->height = stod(params[6]); this->shape = params[7]; } Id Building::connect_to(std::shared_ptr<PhysicalModel> pm) { if (auto path = std::static_pointer_cast<PhysicalPath>(pm)) { this->connections.insert(path->get_id()); return path->get_id(); } else { throw InvalidTypeException(std::string("连接的目标必须是Path")); } } unordered_set<Id>& Building::get_connections() { return this->connections; } double Building::get_width() { return this->width; } double Building::get_height() { return this->height; } std::vector<double> Building::get_coordinate() { return this->coordinate; } std::string Building::get_shape() { return this->shape; }
true
21694bde713800d5e2f178e24d2b96e1a1bbbc59
C++
Lutzion/ESP8266_Artnet_DMX_DC
/lib/MultiResetDetector/src/MultiResetDetector.h
UTF-8
1,933
2.609375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
#ifndef MultiResetDetector_H__ #define MultiResetDetector_H__ #include <Arduino.h> #include <user_interface.h> #include <EEPROM.h> struct _rtcData { uint16_t data ; uint16_t crc ; } ; class MultiResetDetector { uint32_t timeoutMs; bool waitingForMultiReset; bool isLastResetReasonValuable; EEPROMClass eeprom; public: //MultiResetDetector(uint32_t timeoutMs, uint32_t eepromSector = 0); MultiResetDetector(uint32_t timeoutMs, uint32_t eepromSector = 0, void (*fptr)() = NULL); ~MultiResetDetector(); /** * Resets with the reason different to provide are ignored. */ MultiResetDetector& setValuableResetReasons(std::initializer_list<rst_reason> reasons); /** * Starts blocking detection. Returns how many times microcontroller was reseted. */ uint8_t execute(); /** * Detscts the cause of device reset and increase the counter. Should be * called on the first line of setup method and only once. */ uint8_t detectResetCount(); /** * Blocks until monitoring time interval is up. */ void finishMonitoring(); /** * Ensures that reset counter set to zero. Returns whether monitoring time * interval is up. Could be used inside a loop instead of blocking * finishMonitoring if timeoutMs is too big. */ bool handle(); /** * Starts detection and waits timeoutMs. Returns how many times reset button * was clicked. */ //static uint8_t execute(uint32_t timeoutMs, uint32_t eepromSector = 0); static uint8_t execute(uint32_t timeoutMs, uint32_t eepromSector = 0, void (*fptr)() = NULL); inline void setValidResetCallback(void (*fptr)()) { validResetCallback = fptr; } private: #ifdef MRD_ESP8266_RTC //uint32_t MULTIRESET_COUNTER; _rtcData rtcData ; uint32_t rtcAddress; #endif uint8_t readResetCount(); void writeResetCount(uint8_t resetCount); void (*validResetCallback)(); }; #endif // MultiResetDetector_H__
true
a4b3ba8b491126c7685402988c9eb9432e6ff8d4
C++
jihoonog/sudoku-solver
/SudokuGrid.cc
UTF-8
3,013
3.34375
3
[]
no_license
/* Author: Jihoon Og Date: 3/15/18 This class implements a Sudoku puzzle grid All valid coordinates are 1-9 (row and column) */ #include <algorithm> #include <cctype> #include "SudokuGrid.h" SudokuGrid::SudokuGrid(){ for(int i = 0; i < SIZE; ++i){ for(int j = 0; j < SIZE; ++j){ grid[i][j] = EMPTY; } } } bool SudokuGrid::empty(int row, int col) const { return grid[row-1][col-1] == EMPTY; } bool SudokuGrid::isValid(int row, int col, int val) const { // check row for(int j = 0; j < SIZE; ++j){ if(j != col-1 && val == grid[row-1][j]){ return false; } } // check col for(int i = 0; i < SIZE; ++i){ if(i != row-1 && val == grid[i][col-1]){ return false; } } int boxr = (row-1) / 3 * 3; int boxc = (col-1) / 3 * 3; for(int i = boxr; i < boxr+SIZE/3; ++i){ for(int j = boxc; j < boxc+SIZE/3; ++j){ if((i != row-1 || j != col-1) && val == grid[i][j]) { return false; } } } return true; } bool SudokuGrid::isValid() const{ bool used[SIZE+1]; // check each row to check for duplicates for(int i = 0; i < SIZE; ++i){ std::fill(used+1, used+SIZE+1, false); for(int j = 0; j < SIZE; ++j){ if(grid[i][j] != EMPTY && used[grid[i][j]]){ return false; } used[grid[i][j]] = true; } } // check each col to check for duplicates for(int j = 0; j < SIZE; ++j){ std::fill(used+1, used+SIZE+1, false); for(int i = 0; i < SIZE; ++i){ if(grid[i][j] != EMPTY && used[grid[i][j]]){ return false; } used[grid[i][j]] = true; } } // checking each block for(int bi = 0; bi < SIZE; bi += SIZE/3){ for(int bj = 0; bj < SIZE; bj += SIZE/3){ std::fill(used+1, used+SIZE+1, false); for(int i = 0; i < SIZE/3; ++i){ for(int j = 0; j < SIZE/3; ++j){ if(grid[bi+i][bj+j] != EMPTY && used[grid[bi+i][bj+j]]){ return false; } used[grid[bi+i][bj+j]] = true; } } } } return true; } void SudokuGrid::put(int row, int col, int val){ grid[row-1][col-1] = val; } void SudokuGrid::clear(int row, int col){ grid[row-1][col-1] = EMPTY; } void SudokuGrid::clear(){ for(int i = 0; i < SIZE; ++i){ for(int j = 0; j < SIZE; ++j){ grid[i][j] = EMPTY; } } } std::istream& operator>>(std::istream& is, SudokuGrid& sgrid){ char c; for(int i = 0; i < SudokuGrid::SIZE; ++i){ for(int j = 0; j < SudokuGrid::SIZE; ++j){ is>>c; sgrid.grid[i][j] = (std::isdigit(c)) ? c - '0' : SudokuGrid::EMPTY; } } return is; } std::ostream& operator<<(std::ostream& os, SudokuGrid& sgrid){ for(int i = 0; i < SudokuGrid::SIZE; ++i){ if(i > 0 && i % (SudokuGrid::SIZE/3) == 0){ os <<"---+---+---\n"; } for(int j = 0; j < SudokuGrid::SIZE; ++j){ if(j > 0 && j % (SudokuGrid::SIZE/3) == 0){ os<<"|"; } os << static_cast<char>(sgrid.grid[i][j]+'0'); } os<<"\n"; } return os; }
true
dd6251aeac981d1cfc30a5fb79795abf50c991ea
C++
nikv98/p101
/c++/array/arr.cpp
UTF-8
1,073
3.890625
4
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <string> #include <algorithm> using namespace std; int size = 7; int arr[7]; /* Lets return the value at the specified index */ int get(int index){ if(index >= 0 && index < size){ return arr[index]; }else{ return NULL; } } /* Lets set the value of an index with the value we pass in as parameters */ bool set(int index, int value){ if(index >= 0 && index < size){ arr[index] = value; return true; }else{ return false; } } /* lets calculate the sum of the contents of the array */ int getTotal(){ int total; for(int index = 0; index < size; index++){ total += get(index); } return total; } /* Lets print out the contents of our array */ void print(){ for(int index = 0; index < size; index++){ cout << get(index) << endl; } } /* Lets use our functions */ int main(){ srand(time(NULL)); for(int n = 0; n < size; n++){ set(n, rand()%100 + 1); //lets add a random number between 1-100 inclusive } print(); cout << "total: " << getTotal() << endl; cout << endl; }
true
868f972f0188d858f9791f33cad505978324d3ef
C++
Quinton19/Homework_6
/Arm.cpp
UTF-8
399
2.9375
3
[]
no_license
#include "Arm.h" Arm::Arm(string n, int pn, double w, double c, string d, double pc) : Robot_Part(n, pn, w, c, d, Component_type::Arm) { power_consumed = pc; } double Arm::get_power_consumed() { return power_consumed; } string Arm::to_string() { string result; result = Robot_Part::to_string() + "Power consumed: " + Str_conversion::to_string(get_power_consumed()) + " W\n"; return result; }
true
db2974a18a998b58eda2e8db25ae31b28a0f51ec
C++
WhiZTiM/coliru
/Archive2/b1/d3c84f84b1f269/main.cpp
UTF-8
621
3.3125
3
[]
no_license
#include <iostream> #include <string> #include <typeinfo> class ClassA { public: ClassA(); int a; void doSomethingA(); }; class ClassB { public: ClassB(A * A_instance_ptr) { A_ptr = A_instance_ptr; } void doSomethingB() { b = A_ptr->a; } private: A *A_ptr; int b; }; int main(int argc, char **argv) { A A_instance; A_instance.a = 10; A_instance.doSomething(); A* A_ptr; A_ptr = &A_instance; B B_instance(A_ptr); // commenting this line, the code compiles fine return 0; }
true
fc448361cd6b403f42acc027cfece743f9190de4
C++
ulkumeteriz/Ray-Tracer-for-CPU
/image/jpeg.cpp
UTF-8
3,350
3.109375
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <stdexcept> #include <jpeglib.h> #include "../jpeg.h" void read_jpeg_header(const char *filename, int& width, int& height) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE *infile; /* create jpeg decompress object */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); /* set input file name */ if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_src(&cinfo, infile); /* read header */ jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); width = cinfo.output_width; height = cinfo.output_height; fclose(infile); } void read_jpeg(const char *filename, unsigned char *image, int width, int height) { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; FILE *infile; JSAMPROW row_pointer; /* pointer to a row */ int j, k; /* create jpeg decompress object */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); /* set input file name */ if ((infile = fopen(filename, "rb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_src(&cinfo, infile); /* read header */ jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if (width != cinfo.output_width || height != cinfo.output_height) { throw std::runtime_error("Error: Actual JPEG resolution does not match the provided one."); } row_pointer = (JSAMPROW) malloc(sizeof(JSAMPLE)*(width)*3); while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, &row_pointer, 1); for(j=0; j < width; j++) { for(k=0; k < 3; k++) { image[(cinfo.output_scanline - 1) * width * 3 + j * 3 + k] = (unsigned char) row_pointer[3*j + k]; } } } jpeg_finish_decompress(&cinfo); fclose(infile); free(row_pointer); jpeg_destroy_decompress(&cinfo); } void write_jpeg(char *filename, unsigned char *image, int width, int height) { struct jpeg_compress_struct cinfo; struct jpeg_error_mgr jerr; FILE *outfile; JSAMPROW row_pointer = (JSAMPROW) malloc(sizeof(JSAMPLE)*width*3); /* pointer to a row */ int j, k; /* create jpeg compress object */ cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); /* set output file name */ if ((outfile = fopen(filename, "wb")) == NULL) { fprintf(stderr, "can't open %s\n", filename); exit(1); } jpeg_stdio_dest(&cinfo, outfile); /* set parameters */ cinfo.image_width = width; cinfo.image_height = height; cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, 100, TRUE); jpeg_start_compress(&cinfo, TRUE); while (cinfo.next_scanline < cinfo.image_height) { /* this loop converts each element to JSAMPLE */ for(j=0; j < width; j++) { for(k=0; k < 3; k++) { row_pointer[3*j + k] = (JSAMPLE) image[cinfo.next_scanline * width * 3 + j * 3 + k]; } } jpeg_write_scanlines(&cinfo, &row_pointer, 1); } jpeg_finish_compress(&cinfo); fclose(outfile); free(row_pointer); jpeg_destroy_compress(&cinfo); }
true
fdc3a3fc98512ef567c4e1054bc889f1c16fe19c
C++
carriez0705/leetcode
/017-LetterCombinationsofaPhoneNumber.cpp
UTF-8
772
2.96875
3
[]
no_license
class Solution { vector<string> vec; vector<string> re; public: void dfs(int n, string &digits, string &result){ if(n==digits.size()){ re.push_back(result); return; } int c = digits[n]-'0'; for(int i = 0; i<vec[c].size();i++){ result.push_back(vec[c][i]); dfs(n+1,digits,result); result.pop_back(); } } vector<string> letterCombinations(string digits) { if(digits.empty()) return re; string str[] = {" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; for(int i = 0;i<10;i++){ vec.push_back(str[i]); } string result = ""; dfs(0,digits,result); return re; } };
true
068aeafaefcbb98e8f2eebf59071adb931237556
C++
mborzyszkowski/LinearEquationSystems
/matrix.h
UTF-8
1,331
2.65625
3
[ "MIT" ]
permissive
#ifndef MATRIX_H #define MATRIX_H #include "objectManager.h" class Matrix : public ObjectManager { int sizeCols; int sizeRows; public: /*NxN*/ Matrix(int size, bool marked = true); /*MxN*/ Matrix(int rows, int cols, bool marked = true); virtual ~Matrix(); int getSizeCols() const; int getSizeRows() const; virtual double getElementXY(int x, int y) const; virtual void setElementXY(int x, int y, double value); virtual void print() const; virtual double normalize(); virtual Matrix* matrixD(); virtual Matrix* matrixU(); virtual Matrix* matrixL(); virtual Matrix* reverseD(); virtual void doolittle_fLU(Matrix** L, Matrix** U); virtual Matrix* forwardSubstitution(Matrix* eqations, Matrix* values); virtual Matrix* backSubstitution(Matrix* eqations, Matrix* values); friend Matrix& operator+(const Matrix& left, const Matrix& right); friend Matrix& operator-(const Matrix& left, const Matrix& right); friend Matrix& operator*(const Matrix& left, const Matrix& right); friend Matrix& operator-(const Matrix& matrix); virtual Matrix* add(const Matrix& left, const Matrix& right) const; virtual Matrix* sub(const Matrix& left, const Matrix& right) const; virtual Matrix* mul(const Matrix& left, const Matrix& right) const; virtual Matrix* inversion(const Matrix& matrix) const; }; #endif // !MATRIX_H
true
d43341a7cbd69e5f1971a85bf51ca2ebf99057e1
C++
seanahmad/Joshi_Cpp_all-the-examples-and-code
/Chap_1___A_simple_Monte_Carlo_model/Ex_1/SimpleMCMain1.cpp
UTF-8
2,830
3.421875
3
[]
no_license
// SimpleMCMain1.cpp // // Basic procedural implementation of a pricer for a vanilla call and put options. // enum class Contract is an additional parameter to SimpleMonteCarlo1 to discriminate between calls and puts. //require ../Code/Random1.cpp #include "Random1.h" #include <iostream> #include <cmath> enum class OptionType { call, put }; //function doing the MC simulation double SimpleMonteCarlo1(double Expiry, double Strike, double Spot, double Vol, double r, unsigned long NumberOfPath, OptionType TheOptionsType) { double variance{ Vol * Vol * Expiry }; double rootVariance{ std::sqrt(variance) }; double itoCorrection{ -0.5 * variance }; double movedSpot{ Spot * std::exp(r * Expiry + itoCorrection) }; //compute first to reduce call exp() double thisSpot; double thisPayoff{}; double runningSum{ 0 }; for (unsigned long i = 0; i < NumberOfPath; i++) { double thisGaussian{ GetOneGaussianByBoxMuller() }; thisSpot = movedSpot * std::exp(rootVariance * thisGaussian); switch (TheOptionsType) { case OptionType::call: thisPayoff = thisSpot - Strike; break; case OptionType::put: thisPayoff = Strike - thisSpot; break; default: throw "Unknown option type found..."; } thisPayoff = thisPayoff > 0 ? thisPayoff : 0; runningSum += thisPayoff; } double mean{ runningSum / NumberOfPath }; mean *= std::exp(-r * Expiry); return mean; } int main() { OptionType optionType; double Expiry; double Strike; double Spot; double Vol; double r; unsigned long NumberOfPath; //read in parameters int optionTypeSelector; do { std::cout << "\nKind of contract? (press 0 for 'calls', 1 for 'puts')\n"; std::cin >> optionTypeSelector; } while ((optionTypeSelector != 0) & (optionTypeSelector != 1)); switch (optionTypeSelector) { case 0: optionType = OptionType::call; break; case 1: optionType = OptionType::put; break; default: throw "Unknown option type found..."; } std::cout << "\nEnter expiry\n"; std::cin >> Expiry; std::cout << "\nEnter Strike\n"; std::cin >> Strike; std::cout << "\nEnter spot\n"; std::cin >> Spot; std::cout << "\nEnter vol\n"; std::cin >> Vol; std::cout << "\nEnter r\n"; std::cin >> r; std::cout << "\n Number of paths\n"; std::cin >> NumberOfPath; double result{ SimpleMonteCarlo1(Expiry, Strike, Spot, Vol, r, NumberOfPath, static_cast<OptionType>(optionType)) }; std::cout << "the price is " << result << "\n"; return 0; }
true
06d248b0cdf536a84e443a326fec476b132f90a6
C++
TaliShiva/Samples
/basic_element/test/DiskPortTest/DiskPortTests.cpp
UTF-8
5,962
2.6875
3
[]
no_license
#include <thread> #include <fstream> #include <gtest/gtest.h> #include <boost/align/aligned_allocator.hpp> #include "../../include/disk_performer/DiskPort.hpp" /** * @brief Read data from file * @param file_path * @param start_pos * @param read_size * @throw std::runtime_error when file less than expected * @return */ std::string getFileContent(const std::string &file_path, unsigned long long start_pos, size_t read_size) { std::ifstream t(file_path); t.seekg(0, std::ios::end); size_t file_total_size = t.tellg(); if (file_total_size < start_pos + read_size) { throw std::runtime_error("The file contains less data than expected"); } std::string buffer(read_size, ' '); t.seekg(start_pos); t.read(&buffer[0], read_size); t.close(); return buffer; } /** * @brief Construct SolidData * @param offset * @param length * @param fill * @param data_atom_count * @return */ std::shared_ptr<SolidData> getSolidData(unsigned long long offset, size_t length, unsigned char fill = '0', size_t data_atom_count = 1) { std::vector<std::shared_ptr<DataAtom>> data_atoms_vector; for (unsigned long i = 0; i < data_atom_count; i++) { unsigned int raid_id = 42; unsigned int raid_disk_number = 42; unsigned long long disk_offset = offset; size_t disk_length = length; PhysicalRegion physical_region(raid_id, raid_disk_number, disk_offset, disk_length); auto raw_data_write_ptr = std::make_shared<RawDataWrite>(payload_data_vector(length, fill)); unsigned long long int raw_data_offset = 0; auto data_atom = std::make_shared<DataAtom>(raw_data_offset, physical_region, raw_data_write_ptr); data_atoms_vector.push_back(data_atom); } return std::make_shared<SolidData>(std::move(data_atoms_vector)); } /** * Write and verify recorded data */ TEST(DiskPortTests, correctOneWrite) { const std::string file_path = "/tmp/tt-en1wie0iYohc2eogha3e"; const unsigned sector_size = 512; const unsigned sector_count = 1; constexpr unsigned one_write_size = sector_size * sector_count; const unsigned char fill = 'K'; const callback_id_type callback_id = 5; const unsigned buffer_count = 1; std::ofstream createfile(file_path); createfile << "" << std::endl; createfile.close(); auto disk_port = new DiskPort(file_path); disk_port->asyncWrite(getSolidData(0, one_write_size, fill, buffer_count), callback_id); sleep(1); sync(); delete disk_port; std::string content = getFileContent(file_path, 0, one_write_size); auto ret = content.find_first_not_of(fill); std::remove(file_path.c_str()); EXPECT_EQ(std::string::npos, ret); } /** * Write and check answer code */ TEST(DiskPortTests, correctOneWriteAndAnswer) { const std::string file_path = "/tmp/tt-aevoo7oe0Chauc5ieghu"; const unsigned sector_size = 512; const unsigned sector_count = 1; constexpr unsigned one_write_size = sector_size * sector_count; const unsigned char fill = 'Z'; const callback_id_type callback_id = 5; const unsigned buffer_count = 1; std::ofstream createfile(file_path); createfile << "" << std::endl; createfile.close(); auto disk_port = new DiskPort(file_path); disk_port->asyncWrite(getSolidData(0, one_write_size, fill, buffer_count), callback_id); auto result = disk_port->waitAndGetAnswer(false); delete disk_port; std::remove(file_path.c_str()); EXPECT_EQ(one_write_size, result.second); EXPECT_EQ(callback_id, result.first); } /** * Write from multiple buffers and verify recorded data */ TEST(DiskPortTests, correctOneWriteFromMultipleBuffer) { const std::string file_path = "/tmp/tt-phohw4be3sheeGhaib0e"; const unsigned sector_size = 512; const unsigned sector_count = 1; constexpr unsigned one_write_size = sector_size * sector_count; const unsigned char fill = 'U'; const callback_id_type callback_id = 5; const unsigned buffer_count = 4; constexpr unsigned summ_write_bytes = one_write_size * buffer_count; std::ofstream createfile(file_path); createfile << "" << std::endl; createfile.close(); auto disk_port = new DiskPort(file_path); disk_port->asyncWrite(getSolidData(0, one_write_size, fill, buffer_count), callback_id); sleep(1); sync(); delete disk_port; std::string content = getFileContent(file_path, 0, summ_write_bytes); auto ret = content.find_first_not_of(fill); std::remove(file_path.c_str()); EXPECT_EQ(std::string::npos, ret); } /** * Write from multiple buffers and check answer code */ TEST(DiskPortTests, correctOneWriteFromMultipleBufferAndAnswer) { const std::string file_path = "/tmp/tt-Oochi9IlahxeiVeg9eQu"; const unsigned sector_size = 512; const unsigned sector_count = 1; constexpr unsigned one_write_size = sector_size * sector_count; const unsigned char fill = 'U'; const callback_id_type callback_id = 5; const unsigned buffer_count = 4; constexpr unsigned summ_write_bytes = one_write_size * buffer_count; std::ofstream createfile(file_path); createfile << "" << std::endl; createfile.close(); auto disk_port = new DiskPort(file_path); disk_port->asyncWrite(getSolidData(0, one_write_size, fill, buffer_count), callback_id); auto result = disk_port->waitAndGetAnswer(false); delete disk_port; EXPECT_EQ(summ_write_bytes, result.second); std::remove(file_path.c_str()); } /** * Check while open non exist device */ TEST(DiskPortTests, correctExceptionWhenOpenNonExistDevice) { const std::string file_path = "/tmp/tt-Ig2ahngeey4AiteeNgai"; std::remove(file_path.c_str()); try { DiskPort disk_port(file_path); FAIL(); } catch (std::system_error &e) { EXPECT_EQ(e.code().value() , static_cast<int>(std::errc::no_such_file_or_directory)); } }
true
19d1d10b0e8fa861bbc7a10e0c0e1085871afce1
C++
dittoo8/algorithm_cpp
/BOJ/11657.cpp
UTF-8
1,062
2.546875
3
[]
no_license
#include <iostream> #include <vector> #define INF 987654321 #define MAX 502 using namespace std; struct edge { int u,v,c; }; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n,m; cin >> n >> m; long long dist[MAX]; fill(&dist[0], &dist[n]+1,INF); dist[1]= 0; vector<edge> edges; edges.resize(m); int u,v,c; for(int i=0;i<m;i++){ cin >> u >> v >> c; edges[i].u = u, edges[i].v = v, edges[i].c = c; } for(int i=0;i<n-1;i++){ for(int j=0;j<m;j++){ if(dist[edges[j].u] == INF) continue; if(dist[edges[j].v] > dist[edges[j].u] + edges[j].c) dist[edges[j].v] = dist[edges[j].u] + edges[j].c; } } for(int i=0;i<m;i++){ if(dist[edges[i].u] == INF) continue; if(dist[edges[i].v] > dist[edges[i].u] + edges[i].c){ cout << -1 << '\n'; return 0; } } for(int i=2;i<=n;i++){ if(dist[i]==INF) cout<< -1 << '\n'; else cout << dist[i] << '\n'; } return 0; }
true
01a339ea9a1eb083092bc690dac3dda0919e79d1
C++
TejasPatil80178/InterviewBit
/Binary Search/RotatedSortedArraySearch.cpp
UTF-8
609
3.125
3
[]
no_license
int bSearch(vector<int> a,int b,int s,int e) { while(s<=e) { //cout<<s<<" "<<e<<endl; int mid = (s+e)/2; if(a[mid]==b) { return mid; } else if(a[mid] > b) { e = mid-1; } else{ s = mid+1; } } return -1; } int Solution::search(const vector<int> &a, int b) { int s = min_element(a.begin(),a.end()) - a.begin(); int n = a.size(); int e = n-1; if(a[s]<=b && a[e]>=b) { return bSearch(a,b,s,e); } else{ return bSearch(a,b,0,s-1); } }
true
04ac432a4fc63c6c9726d61f7ec0e82c44d9b55c
C++
michalkuraz/infiltr-paper
/data/pasade-test/logo.cpp
UTF-8
8,158
2.6875
3
[]
no_license
// // File: logo.c // // Description: Class for logging output // // Author: Matej Leps // #include <stdlib.h> #include <string.h> #include <sys/resource.h> #include "logo.h" const long KeywordLength=64 ; struct logo_keyword { logo_keyword ( void ) ; ~logo_keyword ( void ) ; char *word ; long binary ; long mode ; bool init ; } ; logo_keyword::logo_keyword ( void ) { binary=0 ; mode=0 ; word=new char[KeywordLength] ; init=false ; } logo_keyword::~logo_keyword ( void ) { if ( word ) { delete [] word ; } } // -------------------------------------- C_LOGO -------------------------------------------------- logo::logo ( void ) { f=NULL ; printlevel=0 ; savelevel=0 ; files=0 ; levels=0 ; names=NULL ; filenames=NULL ; } logo::~logo ( void ) { for ( long i=0 ; i<files ; i++ ) { if ( filenames[i].init ) fclose ( f[i] ) ; } if ( f ) delete [] f ; if ( names ) delete [] names ; if ( filenames ) delete [] filenames ; } void logo::set_levels ( long olevels ) { levels=olevels ; names=new logo_keyword[levels] ; } void logo::set_level_name ( long olevel, char *olevel_name ) { strcpy( names[olevel].word,olevel_name ) ; names[olevel].binary=give_binary( olevel+1 ) ; } void logo::set_files ( long ofiles ) { files=ofiles ; filenames=new logo_keyword[files] ; f=new PFILE[files] ; } void logo::set_file_name ( long ofile, char *ofile_name, long omode ) { strcpy( filenames[ofile].word,ofile_name ) ; filenames[ofile].mode=omode ; } void logo::load_files ( void ) { if ( savelevel > 0 ) { for ( long i=0 ; i<files ; i++ ) { switch ( filenames[i].mode ) { case mode_always_ask: safe_load( i ) ; break ; case mode_append: append_load( i ) ; break ; case mode_rewrite: rewrite_load( i ) ; break ; default: fprintf ( stderr, "\n\n unknown open_file mode in function" ) ; fprintf ( stderr, "\n logo::load_files (file %s, line %d).\n",__FILE__,__LINE__ ) ; exit ( 1 ) ; } } } } void logo::safe_load ( long ofile ) { int c ; if (( f[ofile]=fopen ( filenames[ofile].word,"rt" ) ) != NULL ) { printf ( "File %s exists, rewrite, append, exit? [R/A/E]:", filenames[ofile].word ) ; c=getchar() ; while (getchar() != '\n') ; if ( fclose( f[ofile] ) == EOF ) { f[ofile]=NULL ; fprintf ( stderr,"\n\n Error during closing file %s", filenames[ofile].word ) ; fprintf ( stderr,"\n in function logo::safe_load (%s, line %d).\n",__FILE__,__LINE__); exit ( 1 ) ; } if ( !( c=='r' || c=='R' || c=='a' || c=='A')) { f[ofile]=NULL ; fprintf ( stderr,"\nUser exit.\n" ) ; exit( 0 ) ; } else if ( c=='a' || c=='A' ) { f[ofile]=fopen ( filenames[ofile].word,"at" ) ; if ( f[ofile]==NULL ) { fprintf ( stderr,"\n\n Error during opening file %s", filenames[ofile].word ) ; fprintf ( stderr,"\n in function logo::safe_load (%s, line %d).\n",__FILE__,__LINE__); exit ( 1 ) ; } return ; } } f[ofile]=fopen ( filenames[ofile].word,"wt" ) ; if ( f[ofile]==NULL ) { fprintf ( stderr,"\n\n Error during opening file %s", filenames[ofile].word ) ; fprintf ( stderr,"\n in function logo::safe_load (%s, line %d).\n",__FILE__,__LINE__); exit ( 1 ) ; } filenames[ofile].init=true ; } void logo::rewrite_load ( long ofile ) { f[ofile]=fopen ( filenames[ofile].word,"wt" ) ; if ( f[ofile]==NULL ) { fprintf ( stderr,"\n\n Error during opening file %s", filenames[ofile].word ) ; fprintf ( stderr,"\n in function logo::rewrite_load (%s, line %d).\n",__FILE__,__LINE__); exit ( 1 ) ; } filenames[ofile].init=true ; } void logo::append_load ( long ofile ) { f[ofile]=fopen ( filenames[ofile].word,"at" ) ; if ( f[ofile]==NULL ) { fprintf ( stderr,"\n\n Error during opening file %s", filenames[ofile].word ) ; fprintf ( stderr,"\n in function logo::append_load (%s, line %d).\n",__FILE__,__LINE__); exit ( 1 ) ; } filenames[ofile].init=true ; } void logo::start_time ( void ) { start=clock() ; } void logo::print_time ( long olevel, char *olabel, long otag, long osize ) { if ( names[olevel].binary & printlevel ) { end=clock() ; the_time=(double)(end-start)/((double)osize*CLOCKS_PER_SEC) ; print ( olevel, olabel ) ; print ( olevel, " %f s \n", the_time ); if ( otag==tag_stop_time ) start=clock() ; } } void logo::save_time ( long olevel, long ofile, char *olabel, long otag, long osize ) { if ( filenames[ofile].init && ( names[olevel].binary & savelevel )) { end=clock() ; the_time=(double)(end-start)/((double)osize*CLOCKS_PER_SEC) ; save ( olevel, ofile, olabel ) ; save ( olevel, ofile, " %f s \n", the_time ) ; fflush( f[ofile] ) ; if ( otag==tag_stop_time ) start=clock() ; } } void logo::print_sys_time ( long olevel ) { if ( names[olevel].binary & printlevel ) { struct rusage usage ; getrusage( RUSAGE_SELF, &usage ) ; print( olevel, "CPU usage: User = %ld.%06ld, System = %ld.%06ld\n", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec, usage.ru_stime.tv_sec, usage.ru_stime.tv_usec ) ; } } void logo::print ( long olevel, char *format, ... ) { if ( names[olevel].binary & printlevel ) { va_list argumenty ; va_start ( argumenty, format ) ; vprintf ( format, argumenty ) ; va_end ( argumenty ) ; } } void logo::save ( long olevel, long ofile, char *format, ... ) { if ( filenames[ofile].init && ( names[olevel].binary & savelevel )) { va_list argumenty ; va_start ( argumenty, format ) ; vfprintf ( f[ofile], format, argumenty ) ; va_end ( argumenty ) ; } } void logo::print_help ( void ) { long i ; printf( "\nLevels:\n" ) ; for ( i=0 ; i<levels ; i++ ) { printf ( " %32s %10ld \n", names[i].word, names[i].binary ) ; } printf( "\nFiles:\n" ) ; for ( i=0 ; i<files ; i++ ) { printf ( " %32s \n", filenames[i].word ) ; } } // // commands for command line // by O. Hrstka, sometimes in 2001 // long scan_cmd_line_direct ( long oargc , char *oargv[] , char omark , long &ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i]+2,"%ld",&ovalue ) ; return 1 ; } } return 0 ; } long scan_cmd_line_direct ( long oargc , char *oargv[] , char omark , double &ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i]+2,"%lf",&ovalue ) ; return 1 ; } } return 0 ; } long scan_cmd_line_direct ( long oargc , char *oargv[] , char omark , char *ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i]+2,"%s",ovalue ) ; return 1 ; } } return 0 ; } long scan_cmd_line ( long oargc , char *oargv[] , char omark , long &ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i+1],"%ld",&ovalue ) ; return 1 ; } } return 0 ; } long scan_cmd_line ( long oargc , char *oargv[] , char omark , double &ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i+1],"%lf",&ovalue ) ; return 1 ; } } return 0 ; } long scan_cmd_line ( long oargc , char *oargv[] , char omark , char *ovalue ) { long i ; for ( i=1 ; i<oargc ; i++ ) { if (( oargv[i][0]=='-' ) && ( oargv[i][1]==omark )) { sscanf( oargv[i+1],"%s",ovalue ) ; return 1 ; } } return 0 ; }
true
f3e2a8a2f9582f0317a90e66e3d47eb6006d8e93
C++
salakichi/Billiards
/Billiards/Scene.cpp
SHIFT_JIS
4,047
2.796875
3
[]
no_license
#include "stdafx.h" #include "Scene.h" Scene::Scene(ResourceManager &r, glm::uvec2 &size) : resource(r), windowSize(size) { // ̃V[ nextScene = NONE; } Scene::~Scene() { } void Scene::Next(GAME_STATUS next) { nextScene = next; } void Scene::DrawSmallCircle(float radius, int x, int y) { glEnable(GL_POINT_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(radius*2.0f); glBegin(GL_POINTS); glVertex2f((float)x, (float)y); glEnd(); glDisable(GL_BLEND); glDisable(GL_POINT_SMOOTH); } void Scene::DrawLargeCircle(float radius, int x, int y) { for (float th1 = 0.0f; th1 <= 360.0f; th1 = th1 + 2.0f) { float th2 = th1 + 10.0f; float th1_rad = th1 * 0.0174533f; float th2_rad = th2 * 0.0174533f; float x1 = radius * cos(th1_rad); float y1 = radius * sin(th1_rad); float x2 = radius * cos(th2_rad); float y2 = radius * sin(th2_rad); glBegin(GL_TRIANGLES); glVertex2f((float)x, (float)y); glVertex2f(x1 + x, y1 + y); glVertex2f(x2 + x, y2 + y); glEnd(); } } void Scene::glutRenderText(void* bitmapfont, char*text) { for (int i = 0; i<(int)strlen(text); i++) glutBitmapCharacter(bitmapfont, (int)text[i]); } int Scene::drawText(char *text, string fontName, glm::uvec2 pos, glm::vec2 move) { unsigned int textLength; //Ŏ󂯎eLXg̒ WCHAR * unicodeText; //textUNICODEɕϊi[ glRasterPos2i(pos.x, pos.y); //{̕ƂĈ悤ݒ setlocale(LC_CTYPE, "jpn"); //text̕擾 textLength = (unsigned int)_mbstrlen(text); if (textLength == -1) return -1; //text̃̕Cḧ̗쐬 unicodeText = new WCHAR[textLength + 1]; if (unicodeText == NULL) { return -2; } //擾WCgIDUNICODEɕϊ if (MultiByteToWideChar(CP_ACP, 0, text, -1, unicodeText, (sizeof(WCHAR) * textLength) + 1) == 0) return -3; // \ RFont(fontName)->Render(unicodeText); delete[] unicodeText; return 1; } // ‚ int Scene::drawText(char *text, string fontName, glm::uvec2 pos, glm::vec2 move, glm::vec4 mainColor, glm::vec4 edgeColor, int edgeSize) { // ` glColor4f(mainColor.r, mainColor.g, mainColor.b, mainColor.a); drawText(text, fontName, move, pos); // if (edgeSize > 0) { glColor4f(edgeColor.r, edgeColor.g, edgeColor.b, edgeColor.a); for (int i = -edgeSize + 1; i<edgeSize; i++) { drawText(text, fontName, move, glm::vec2(pos.x + i, pos.y + (edgeSize - i))); drawText(text, fontName, move, glm::vec2(pos.x + i, pos.y - (edgeSize - i))); } drawText(text, fontName, move, glm::vec2(pos.x + edgeSize, pos.y)); drawText(text, fontName, move, glm::vec2(pos.x - edgeSize, pos.y)); } return 1; } void Scene::DrawSquareWithEdge(glm::uvec2 startPos, glm::uvec2 endPos, glm::vec4 mainColor, glm::vec4 edgeColor, float edgeSize) { glColor4f(mainColor.r, mainColor.g, mainColor.b, mainColor.a); glBegin(GL_QUADS); glVertex2i(startPos.x, startPos.y); glVertex2i(endPos.x, startPos.y); glVertex2i(endPos.x, endPos.y); glVertex2i(startPos.x, endPos.y); glEnd(); if (edgeSize > 0.f) { glColor4f(edgeColor.r, edgeColor.g, edgeColor.b, edgeColor.a); glLineWidth(edgeSize); glBegin(GL_LINE_LOOP); glVertex2i(startPos.x, startPos.y); glVertex2i(endPos.x, startPos.y); glVertex2i(endPos.x, endPos.y); glVertex2i(startPos.x, endPos.y); glEnd(); } } void Scene::DrawSquareWithGradation(glm::uvec2 startPos, glm::uvec2 endPos, glm::vec4 startColor, glm::vec4 endColor) { glBegin(GL_QUADS); glColor4f(startColor.r, startColor.g, startColor.b, startColor.a); glVertex2i(startPos.x, startPos.y); glColor4f(startColor.r, startColor.g, startColor.b, startColor.a); glVertex2i(endPos.x, startPos.y); glColor4f(endColor.r, endColor.g, endColor.b, endColor.a); glVertex2i(endPos.x, endPos.y); glColor4f(endColor.r, endColor.g, endColor.b, endColor.a); glVertex2i(startPos.x, endPos.y); glEnd(); }
true
0b74cd57687c45690cdbd5203de144b7a2b196e8
C++
BUIDUCTAI2105/hackerrank_algorithms
/Baitap-thaykhang/138.cpp
WINDOWS-1258
1,206
3.046875
3
[]
no_license
// Tm vi tr cua gi tri chan dau tin trong mang 1 chieu cc so nguyn. Neu mang khng c gi tri chan th se tri ve -1 //B1: viet ham nhap va xuat mang 1 chieu a[i] // nhap vao n neu n <= 0 hoac n > MAX ( MAX 100 ) thi bi loi va nhap lai // //B2: viet ham timvitrichandau // duyet cc phn tu tu dau mang toi cuoi mang, neu co phan tu no chia het cho 2 (a[i] % 2 == 0) thi in ra vi tri do (return i) // nguoc lai neu khng c gi tri chan nao thi tra v gi tri -1 #include<stdio.h> #define MAX 100 void nhap (int a[], int &n) { do { printf("\nNhap so phan tu: "); scanf("%d", &n); if(n <= 0 || n > MAX) { printf("\nloi roi kiem tra lai !"); } }while(n <= 0 || n > MAX); for(int i = 0; i < n; i++) { printf("\nNhap a[%d]: ", i); scanf("%d", &a[i]); } } void xuat(int a[], int n) { for(int i = 0; i < n; i++) { printf("%4d", a[i]); } } int timvitrichandau(int a[], int n) { for(int i = 0; i < n; i++) { if(a[i] % 2 == 0) { return i; } } return -1; } int main() { int n; int a[MAX]; nhap(a, n); xuat(a, n); int vitrichandau = timvitrichandau(a, n); printf("\nVi tri chan dau la %d", vitrichandau); getchar(); return 0; }
true
3a9d9ca022ebe9661a8b6e219df2e3fac1ded802
C++
stressedtyagi/ds-lab-sem1-nitw
/LAB - 6/14_JUNE_207919_P1.cpp
UTF-8
4,840
4.03125
4
[]
no_license
/* Design a program to implement the following sorting algorithms on integer data. Bubble Sort [Optional] Selection Sort [Optional] Insertion Sort Merge Sort Quick Sort The program should have a menu with options to generate an array of random numbers, call the various sorting algorithms on the array, and print the array. [The student should practice to write sorting algorithms on other data types including structures and class objects; and other possible ways they can be implemented/used] */ #include <iostream> #include <math.h> using namespace std; void print(int a[], int n) { for(int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } void copy(int a[], int b[], int n) { for(int i = 0; i < n; i++) { b[i] = a[i]; } } void bubbleSort(int[],int); void selectionSort(int[],int); void insertionSort(int[],int); void merge(int*,int,int,int); void mergeSort(int*,int,int); void quickSort(int*,int,int); int partition(int*,int,int); int main() { int n; cout << "Enter number of elements in array : "; cin >> n; int a[n]; srand((unsigned)time(0)); for(int i = 0; i < n; i++) { a[i] = (rand()%(n+1)); } cout << "Inital Array : "; print(a,n); cout << "--------------------------------------------------------------" << endl; int b[n]; copy(a,b,n); bubbleSort(b,n); cout << "1. Array after bubble sort : "; print(b,n); cout << "--------------------------------------------------------------" << endl; cout << "--------------------------------------------------------------" << endl; copy(a,b,n); selectionSort(b,n); cout << "2. Array after selection sort : "; print(b,n); cout << "--------------------------------------------------------------" << endl; cout << "--------------------------------------------------------------" << endl; copy(a,b,n); insertionSort(b,n); cout << "3. Array after insertion sort : "; print(b,n); cout << "--------------------------------------------------------------" << endl; cout << "--------------------------------------------------------------" << endl; copy(a,b,n); mergeSort(b,0,n-1); cout << "4. Array after merge sort : "; print(b,n); cout << "--------------------------------------------------------------" << endl; cout << "--------------------------------------------------------------" << endl; copy(a,b,n); quickSort(b,0,n-1); cout << "5. Array after quick sort : "; print(b,n); cout << "--------------------------------------------------------------" << endl; return 0; } void bubbleSort(int a[], int n) { bool checkFlag{true}; for(int i = 0; i < n-1 && checkFlag; i++) { checkFlag = false; for(int j = 0; j < n-i-1; j++) { if(a[j] > a[j+1]) { swap(a[j],a[j+1]); checkFlag = true; } } } } void selectionSort(int a[], int n) { for(int i = 0;i < n-1; i++) { int min = i; for(int j = i+1;j < n; j++) { if(a[j] < a[min]) { min = j; } } swap(a[i],a[min]); } } void insertionSort(int a[], int n) { for(int i = 0; i < n; i++) { int pivot = a[i]; int j = i - 1; for( ; j >= 0; j--) { if(a[j] > pivot) { a[j+1] = a[j]; }else { break; } } a[j+1] = pivot; } } void mergeSort(int *a, int start,int end) { if(start < end) { int mid = start + (end - start)/2; // same as (start+end)/2 ... used this to avoid integer overflow mergeSort(a,0,mid); mergeSort(a,mid+1,end); merge(a,start,mid,end); } } void merge(int *a, int start,int mid,int end) { int *res = new int[end-start+1]; int n = mid; int m = end; int k{0}; int i{start}, j{mid+1}; while(i <= n && j <= m) { if(a[i] < a[j]) res[k++] = a[i++]; else if (a[i] > a[j]) res[k++] = a[j++]; else { res[k++] = a[i++]; res[k++] = a[j++]; } } while(i <= n) res[k++] = a[i++]; while(j <= m) res[k++] = a[j++]; i = 0; for(int l = start; i < k; l++) { a[l] = res[i]; i++; } } void quickSort(int *a, int l, int h) { if(l < h) { int par = partition(a,l,h); quickSort(a,l,par); quickSort(a,par+1,h); } } int partition(int *a, int l, int h) { int pivot{a[l]}; int i{l-1}, j{h+1}; while(true) { do { i++; } while (a[i] < pivot); do { j--; } while (a[j] > pivot); if(i >= j) return j; swap(a[i],a[j]); } }
true
8dc00310ac3a0f618077e4d886883b99bc974193
C++
JungAh12/BOJ
/1629.cpp
UTF-8
911
3.671875
4
[]
no_license
/* 처음에 행렬제곱이랑 똑같다고 생각해서 matrix multiply → scalar multiply로 바꿨는데 바로 return할 수 있는 조건들을 따지다 보니 굳이 matrix 경우처럼 식이 길어질 필요가 없었음. - 곱하고자 하는 수가 홀수이면 A가 한번 더 곱해진다는 것을 주의해서 풀어야했음. */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <cstdio> using namespace std; long long int recul(long long int A, long long int B, long long int C) { if (A == C) return 0; if (B == 0) return 1; if (B == 1) return A % C; long long int D = recul(A, B / 2, C); if (B % 2 == 1) //홀수면 return (((D * D) % C) * A) % C; //마지막에 A하나 더 곱해야함. else return (D*D)%C; } int main() { long long int A, B, C; scanf("%lld %lld %lld", &A,&B,&C); long long int D; D = recul(A, B, C); cout << D; return 0; }
true
8128bc21de0d4e752f3d7b295d87ecd79b4a8c7f
C++
iamvickynguyen/Kattis-Solutions
/permutedarithmeticsequence.cpp
UTF-8
650
3.203125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef long long int ll; bool is_arit(vector<ll> &v, int m) { ll diff = v[1] - v[0]; for (int i = 2; i < m; i++) { if (v[i] - v[i - 1] != diff) { return false; } } return true; } int main() { int n, m; ll x; cin >> n; while (n--) { vector<ll> v; cin >> m; for (int i = 0; i < m; i++) { cin >> x; v.push_back(x); } if (is_arit(v, m)) cout << "arithmetic" << endl; else { sort(v.begin(), v.end()); if (is_arit(v, m)) cout << "permuted arithmetic" << endl; else cout << "non-arithmetic" << endl; } } return 0; }
true
6b537d106ea3c83516f084d950eec807c7846e7f
C++
aaronschraner/CST211
/assignment5/Exception.h
UTF-8
1,282
3.328125
3
[]
no_license
/********************************************************************** * Author: Aaron Schraner * Date created: September 30, 2015 * Last modified: October 11, 2015 (added comments) * Filename: Exception.cpp * Purpose: Generic exception class with error message * Constructors: * Exception(): default constructor * sets message to "Undefined exception" * * Exception(const char* msg) * sets message to msg * * Exception(const Exception& e) * copy constructor * copies message from e to self * Destructor: * ~Exception() * deletes message * * Operators: * operator<< (ostream& os, const Exception& e) * send the message to the output stream * ************************************************************************/ #ifndef EXCEPTION_H #define EXCEPTION_H #include <iostream> using std::ostream; class Exception { private: //the error message char* message; public: //constructors Exception(); Exception(const char* msg); Exception(const Exception& e); //destructor ~Exception(); //operators and methods const Exception& operator=(const Exception& e); const char* getMessage() const { return message; } void setMessage(const char* msg); friend ostream& operator<<(ostream& os, const Exception &e); }; #endif
true
0c6891f4cd7c46aee3d055b74ffd1bfff985b3f3
C++
zhengyujie306/mySmartPtr
/include/mySharedPtr.h
UTF-8
1,084
3.703125
4
[]
no_license
#ifndef MYSHAREDPTR_H #define MYSHAREDPTR_H #include <iostream> using std::cout; using std::endl; template <typename T> class mySharedPtr { public: //constructor mySharedPtr():ptr(new T()), count(new int(1)) {} explicit mySharedPtr(T *src) : ptr(src), count(new int(1)) {} explicit mySharedPtr(T value) : ptr(new T(value)), count(new int(1)) {} //copy constructor mySharedPtr(const mySharedPtr& rhs) : ptr(rhs.ptr), count(rhs.count) { ++(*count); } mySharedPtr& operator=(const mySharedPtr& rhs) { ++(*(rhs.count)); if(--(*count) == 0) { delete ptr; delete count; } ptr = rhs.ptr; count = rhs.count; return *this; } ~mySharedPtr() { if(--(*count) == 0) { delete ptr; delete count; cout << "deleted" << endl; } else { cout << "some pointer still refer to raw pointer" << endl; } } T* get() const { return ptr; } int use_count() const { return *count; } T operator*() { return *ptr; } T* operator->() { return ptr; } protected: private: T *ptr; //raw pointer int *count; //reference count }; #endif // MYSHAREDPTR_H
true
ddec57a3f21a31aa4b77b4a4613e57d45583de7a
C++
mehulthakral/logic_detector
/backend/CDataset/countPrimes/countPrimes_8.cpp
UTF-8
472
2.765625
3
[]
no_license
class Solution { public:int countPrimes(int n) { if(n<=1) return 0; vector<bool> isPrime(n,true); // we will mark 0 and 1 as false manually isPrime[0]=isPrime[1]=false; for(int i=2;i*i<n;++i) { if(isPrime[i]) { for(int j=i*i;j<n;j+=i) { isPrime[j]=false; } } } return count(isPrime.begin(),isPrime.end(),true); } };
true
a2ff26950caf75ef8a9ffbf44a2ba76b91f1aef7
C++
rajeev921/Algorithms
/LeetCode/All_Problem/Graphs/200.cpp
UTF-8
2,811
3.046875
3
[]
no_license
class Solution { public: private: vector<pair<int, int>> dir {{0, 1}, {0, -1}, {-1, 0}, {1, 0} }; public: // Faster BFS int Bfs(int row, int col, vector<vector<char>>& grid, vector<vector<bool>>& visited) { queue<pair<int,int>> q; q.push(make_pair(row, col)); visited[row][col] = true; while(!q.empty()) { int sz = q.size(); for(int i = 0; i < sz; ++i) { pair<int, int> p = q.front(); int row = p.first; int col = p.second; q.pop(); if(row+1 != grid.size() && visited[row+1][col] == false && grid[row+1][col] == '1') { q.push(make_pair(row+1, col)); visited[row+1][col] = true; } if(col+1 != grid[0].size() && visited[row][col+1] == false && grid[row][col+1] == '1') { q.push(make_pair(row, col+1)); visited[row][col+1] = true; } if(col != 0 && col-1 >= 0 && visited[row][col-1] == false && grid[row][col-1] == '1') { q.push(make_pair(row, col-1)); visited[row][col-1] = true; } if(row!= 0 && row-1 >= 0 && visited[row-1][col] == false && grid[row-1][col] == '1') { q.push(make_pair(row-1, col)); visited[row-1][col] = true; } } } return 1; } public: // Slower than the above solution int bfs(int row, int col, vector<vector<char>>& grid, vector<vector<bool>>& visited) { queue<pair<int,int>> q; q.push({row, col}); visited[row][col] = true; while(!q.empty()) { int sz = q.size(); for(int i = 0; i < sz; ++i) { auto current_point = q.front(); q.pop(); for(int j = 0 ; j < dir.size(); ++j) { int nextX = current_point.first + dir[j].first; int nextY = current_point.second + dir[j].second; if(nextX < 0 || nextX==grid.size() || nextY < 0 || nextY==grid[0].size() || grid[nextX][nextY]=='0' || visited[nextX][nextY]==true) { continue; } q.push({nextX, nextY}); visited[nextX][nextY]=true; } } } return 1; } int numIslands(vector<vector<char>>& grid) { if(grid.size() < 1) { return 0; } int xdim = grid.size(); int ydim = grid[0].size(); vector<vector<bool>> visited(xdim, vector<bool>(ydim, false)); int count{}; for(int i = 0; i < xdim; ++i) { for(int j = 0; j < ydim; ++j) { if(visited[i][j] || grid[i][j] == '0'){ continue; } else { count += bfs(i, j, grid, visited); } } } return count; } };
true
120bee78d61ba2901974842e864657ebe6b1f0f7
C++
scratchboom/CoolGrids
/MPI-wrapped.cpp
UTF-8
2,626
2.96875
3
[]
no_license
#include "GridsCommon.hpp" using namespace std; template<typename T> class MpiGrid3D: Grid3D<T> { private: Grid3D<T> fullGridBounds; Grid3D<T> subGridBounds; int partsX, partsY, partsZ; public: MpiGrid3D() { Grid3D<T>(); partsX = partsY = partsZ = 1; } void setParts(int partsX, int partsY, int partsZ) { this->partsX = partsX; this->partsY = partsY; this->partsZ = partsZ; } void build() { std::cout << "MpiGrid3D::build" << std::endl; buildBounds(); if (nodesCountX % partsX == 0) { std::cout << nodesCountX << " = " << (nodesCountX / partsX) << "*" << partsX << std::endl; } else { DBGVAL(nodesCountX % partsX); DBGVAL(nodesCountX / partsX); DBGVAL(nodesCountX / partsX +1); } } }; double minFunc1(int Nx,int Ny,int Nz,int nx,int ny,int nz){ return sqr((double) nx / ny - (double) Nx / Ny) + sqr((double) ny / nx - (double) Ny / Nx) + sqr((double) nx / nz - (double) Nx / Nz) + sqr((double) nz / nx - (double) Nz / Nx) + sqr((double) ny / nz - (double) Ny / Nz) + sqr((double) nz / ny - (double) Nz / Ny); } double minFunc2(int Nx,int Ny,int Nz,int nx,int ny,int nz){ return (nx-1)*Ny*Nz + (ny-1)*Nz*Nx + (nz-1)*Nx*Ny; } void calcDims(int Nx, int Ny, int Nz, int n, int& nx, int& ny, int& nz) { double bestI = 1E50; int nxBest = 0; int nyBest = 0; int nzBest = 0; for (int nx = 1; nx <= n; nx++) for (int ny = 1; ny <= n; ny++) { int nz = (n / nx) / ny; if (nx * ny * nz != n) continue; double I = minFunc2(Nx,Ny,Nz,nx,ny,nz); if (I < bestI) { bestI = I; nxBest = nx; nyBest = ny; nzBest = nz; } } if (bestI < 1E50) { nx = nxBest; ny = nyBest; nz = nzBest; cout << "dimns calculated" << endl; cout << "nx: " << nxBest << endl; cout << "ny: " << nyBest << endl; cout << "nz: " << nzBest << endl; cout << "min proportion: " << minFunc1(Nx,Ny,Nz,nx,ny,nz) << endl; cout << "min area: " << minFunc2(Nx,Ny,Nz,nx,ny,nz) << endl; } else { cout << "dims calculation failed" << endl; throw "dims calculation failed"; } } int main(int argc, char* argv[]) { cout << "hello there" << endl; int Nx = 100; int Ny = 100; int Nz = 200; int n = 1000; int nx,ny,nz; calcDims(Nx,Ny,Nz,n,nx,ny,nz); for(int i=0;i<argc;i++)cout << argv[i] << endl; MpiEnvironment env(argc, argv); MpiCommunicator world; if(world.isMainProcess())cout << "numtasks: " << world.getSize() << endl; cout << "task id: " << world.getRank() << endl; if(world.isMainProcess()){ MpiGrid3D<double> g; g.setIndexRangeX(0,2); g.build(); } return 0; }
true
ebee58c7355bc4b9394fab9e1d554b3b961793f5
C++
alortimor/c-_tests
/tcp_server/client/AsyncTCPClient.h
UTF-8
6,484
3
3
[]
no_license
#ifndef ASYNCTCPCLIENT_H #define ASYNCTCPCLIENT_H #include <boost/asio.hpp> #include <thread> #include <mutex> #include <memory> #include <iostream> using namespace boost; // Function pointer type that points to the callback // function which is called when a request is complete. typedef void(*Callback) (int request_id, const std::string& response, const system::error_code& ec); // Structure represents a context of a single request. struct Session { Session(asio::io_service& ios, const std::string& ip_addr, short port, const std::string& request, int id, Callback callback) : m_sock(ios), m_ep(asio::ip::address::from_string(ip_addr), port), m_request(request), m_id(id), m_callback(callback), m_was_cancelled(false) { } asio::ip::tcp::socket m_sock; // Socket used for communication asio::ip::tcp::endpoint m_ep; // Remote endpoint. std::string m_request; // Request string. // streambuf where the response will be stored. asio::streambuf m_response_buf; std::string m_response; // Response represented as a string. // Contains the description of an error if one occurs during // the request life cycle. system::error_code m_ec; unsigned int m_id; // Unique ID assigned to the request. // Pointer to the function to be called when the request // completes. Callback m_callback; bool m_was_cancelled; std::mutex m_cancel_guard; }; class AsyncTCPClient : public boost::noncopyable { public: AsyncTCPClient() { m_work.reset(new boost::asio::io_service::work(m_ios)); m_thread.reset(new std::thread([this](){ m_ios.run(); })); } void process_request(int duration_sec, const std::string& ip_addr, short port, Callback callback, int request_id, const std::string& sql_statement) { std::string request = sql_statement + std::string("\n"); std::shared_ptr<Session> session = std::shared_ptr<Session>(new Session(m_ios, ip_addr, port, request, request_id, callback)); session->m_sock.open(session->m_ep.protocol()); // Add new session to the list of active sessions so // that we can access it if the user decides to cancel // the corresponding request before it completes. // Because active sessions list can be accessed from // multiple threads, we guard it with a mutex to avoid // data corruption. std::unique_lock<std::mutex> lock(m_active_sessions_guard); m_active_sessions[request_id] = session; lock.unlock(); session->m_sock.async_connect(session->m_ep, [this, session](const system::error_code& ec) { if (ec != 0) { session->m_ec = ec; request_done(session); return; } std::unique_lock<std::mutex> cancel_lock(session->m_cancel_guard); if (session->m_was_cancelled) { request_done(session); return; } asio::async_write(session->m_sock, asio::buffer(session->m_request), [this, session](const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec != 0) { session->m_ec = ec; request_done(session); return; } std::unique_lock<std::mutex> cancel_lock(session->m_cancel_guard); if (session->m_was_cancelled) { request_done(session); return; } asio::async_read_until(session->m_sock, session->m_response_buf, '\n', [this, session](const boost::system::error_code& ec, std::size_t bytes_transferred) { if (ec != 0) { session->m_ec = ec; } else { std::istream strm(&session->m_response_buf); std::getline(strm, session->m_response); } request_done(session); } ); } ); } ); }; // Cancels the request. void cancel_request(int request_id) { std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(request_id); if (it != m_active_sessions.end()) { std::unique_lock<std::mutex> cancel_lock(it->second->m_cancel_guard); it->second->m_was_cancelled = true; it->second->m_sock.cancel(); } } void close() { // allows i/o thread to exits event loop when there are no more pending asynchronous operations. m_work.reset(NULL); // Wait for the I/O thread to exit. m_thread->join(); } private: void request_done(std::shared_ptr<Session> session) { // Shutting down the connection. This method may // fail in case socket is not connected. We don’t care // about the error code if this function fails. boost::system::error_code ignored_ec; session->m_sock.shutdown( asio::ip::tcp::socket::shutdown_both, ignored_ec); // Remove session form the map of active sessions. std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(session->m_id); if (it != m_active_sessions.end()) m_active_sessions.erase(it); lock.unlock(); boost::system::error_code ec; if (session->m_ec == 0 && session->m_was_cancelled) ec = asio::error::operation_aborted; else ec = session->m_ec; // Call the callback provided by the user. session->m_callback(session->m_id, session->m_response, ec); }; private: asio::io_service m_ios; std::map<int, std::shared_ptr<Session>> m_active_sessions; std::mutex m_active_sessions_guard; std::unique_ptr<boost::asio::io_service::work> m_work; std::unique_ptr<std::thread> m_thread; }; #endif // ASYNCTCPCLIENT_H
true
a55a594c84de3b98743c3eaba4cada05345f7422
C++
busebd12/InterviewPreparation
/LeetCode/C++/General/Medium/TheMazeII/solution.cpp
UTF-8
3,628
3.46875
3
[ "MIT" ]
permissive
#include <array> #include <deque> #include <limits> #include <utility> #include <vector> using namespace std; /* Solution: breadth-first search. Time complexity: O(rows * columns) Space complexity: O(rows * columns) */ class Solution { private: array<pair<int, int>, 4> directions={{{0, -1}, {-1, 0}, {0, 1}, {1, 0}}}; int rows=0; int columns=0; public: int shortestDistance(vector<vector<int>> & maze, vector<int> & start, vector<int> & destination) { int result=-1; this->rows=maze.size(); this->columns=maze[0].size(); const int INF=numeric_limits<int>::max(); vector<vector<int>> distances(rows, vector<int>(columns, INF)); distances[start[0]][start[1]]=0; bfs(maze, distances, start); if(distances[destination[0]][destination[1]]!=INF) { result=distances[destination[0]][destination[1]]; } return result; } void bfs(vector<vector<int>> & maze, vector<vector<int>> & distances, vector<int> & start) { deque<tuple<int, int, int>> queue; queue.emplace_back(start[0], start[1], 0); while(!queue.empty()) { int qSize=queue.size(); for(int count=0;count<qSize;count++) { auto [currentRow, currentColumn, currentEmptySpacesTravelled]=queue.front(); queue.pop_front(); for(auto & [rowOffset, columnOffset] : directions) { int nextRow=currentRow; int nextColumn=currentColumn; int emptySpacesTravelled=getEmptySpacesTravelled(maze, nextRow, nextColumn, rowOffset, columnOffset); int newDistance=currentEmptySpacesTravelled + emptySpacesTravelled; if(newDistance < distances[nextRow][nextColumn]) { distances[nextRow][nextColumn]=newDistance; queue.emplace_back(nextRow, nextColumn, newDistance); } } } } } int getEmptySpacesTravelled(vector<vector<int>> & maze, int & row, int & column, int rowOffset, int columnOffset) { int emptySpacesTravelled=0; while(isValid(maze, row + rowOffset, column + columnOffset)==true) { emptySpacesTravelled+=1; row+=rowOffset; column+=columnOffset; } return emptySpacesTravelled; } bool isValid(vector<vector<int>> & maze, int row, int column) { bool invalidRow=(row < 0 or row >= rows); bool invalidColumn=(column < 0 or column >= columns); if(invalidRow==true or invalidColumn==true) { return false; } if(maze[row][column]==1) { return false; } return true; } };
true
e38d0f015695aba92dddd4e6df0cfb4730ba34c1
C++
m-d-asenov/SoftUni-Programming-Basics-with-Java-and-CPP
/exam_2020_march/CatWalking.cpp
UTF-8
488
3.21875
3
[]
no_license
#include <iostream> using namespace std; int main() { int minPerWalk; cin >> minPerWalk; int walks; cin >> walks; int calories; cin >> calories; int burntCal = minPerWalk * walks * 5; if(burntCal >= calories * 0.5) cout << "Yes, the walk for your cat is enough. Burned calories per day: " << burntCal << "." << endl; else cout << "No, the walk for your cat is not enough. Burned calories per day: " << burntCal << "." << endl; return 0; }
true
a32f5a75ce7cc0f7279df11f805f38844e968ee6
C++
vv1133/mintdb
/src/extend/hash/main.cpp
UTF-8
11,298
2.625
3
[]
no_license
#include <map> #include <iostream> #include <vector> #include <string.h> #include <stdio.h> using namespace std; #define get16bits(d) (*((const unsigned short *) (d))) unsigned int ossHash ( const char *data, int len ) { unsigned int hash = len, tmp ; int rem ; if ( len <= 0 || data == 0 ) return 0 ; rem = len&3 ; len >>= 2 ; for (; len > 0 ; --len ) { hash += get16bits (data) ; tmp = (get16bits (data+2) << 11) ^ hash; hash = (hash<<16)^tmp ; data += 2*sizeof(unsigned short) ; hash += hash>>11 ; } switch ( rem ) { case 3: hash += get16bits (data) ; hash ^= hash<<16 ; hash ^= ((char)data[sizeof (unsigned short)])<<18 ; hash += hash>>11 ; break ; case 2: hash += get16bits(data) ; hash ^= hash <<11 ; hash += hash >>17 ; break ; case 1: hash += (char)*data ; hash ^= hash<<10 ; hash += hash>>1 ; } hash ^= hash<<3 ; hash += hash>>5 ; hash ^= hash<<4 ; hash += hash>>17 ; hash ^= hash<<25 ; hash += hash>>6 ; return hash ; } typedef struct _Element { int id; const char *data; }Element; #define BUCKET_MAX_ELEMENT(num) ((num) * 2) class BucketManager { class Bucket { public: multimap<unsigned int, Element *> _bucketMap; ~Bucket() { for ( multimap<unsigned int, Element*>::iterator it = _bucketMap.begin(); it != _bucketMap.end(); ++it ) { delete (*it).second; } } int createIndex ( unsigned int hashNum, Element *ele ) ; int findIndex ( unsigned int hashNum, Element *ele ) ; int removeIndex ( unsigned int hashNum, Element *ele ) ; void print() ; }; private : int _size; int _index; int _elenum; vector<Bucket *>_bucket ; int rebuildBucket (int num); public : BucketManager () { _size = 4;//2^(_index-1) - 2^_index-1 _index = 3; _elenum = 0; } ~BucketManager () { Bucket *pBucket = NULL ; for ( int i = 0; i < _size; ++i ) { pBucket = _bucket[i] ; if ( pBucket ) delete pBucket ; } } int initialize () ; int addBucket () ; int rebuildAll () ; int createIndex ( Element *ele ) ; int findIndex ( Element *ele ) ; int removeIndex ( Element *ele ) ; void print() ; }; int BucketManager::createIndex ( Element *ele ) { unsigned int random; unsigned int hashnum; unsigned int mask, maskhash; int rc; unsigned int size; hashnum = ossHash((const char*)&ele->id, sizeof(ele->id)); mask = (1<<_index) - 1; size = 1 << (_index - 1); maskhash = hashnum & mask; if (maskhash < _size) random = maskhash; else random = maskhash - size; rc = _bucket[random]->createIndex ( hashnum, ele ) ; if (rc == 0) _elenum++; if (BUCKET_MAX_ELEMENT(_size) <= _elenum) { if ((1<<_index) - 1 == _size) { printf("before rebuildAll:\n"); print(); printf("++++++++++++++++++++++++++++\n"); if (rebuildAll() != 0) return -1; } else { printf("before addBucket:\n"); print(); printf("++++++++++++++++++++++++++++\n"); if (addBucket() != 0) return -1; } } return rc ; } int BucketManager::findIndex ( Element *ele ) { unsigned int random; unsigned int hashnum; unsigned int mask, maskhash; int rc; unsigned int size; hashnum = ossHash((const char*)&ele->id, sizeof(ele->id)); mask = (1<<_index) - 1; size = 1 << (_index - 1); maskhash = hashnum & mask; if (maskhash < _size) random = maskhash; else random = maskhash - size; rc = _bucket[random]->findIndex ( hashnum, ele ) ; return rc ; } int BucketManager::removeIndex ( Element *ele ) { unsigned int random; unsigned int hashnum; unsigned int mask, maskhash; int rc; unsigned int size; hashnum = ossHash((const char*)&ele->id, sizeof(ele->id)); mask = (1<<_index) - 1; size = 1 << (_index - 1); maskhash = hashnum & mask; if (maskhash < _size) random = maskhash; else random = maskhash - size; rc = _bucket[random]->removeIndex ( hashnum, ele ) ; return rc ; } int BucketManager::initialize () { int rc = 0 ; Bucket *temp = NULL ; for ( int i = 0; i < _size; ++i ) { temp = new (std::nothrow) Bucket () ; if ( !temp ) { rc = -1 ; goto error ; } _bucket.push_back ( temp ) ; temp = NULL ; } done: return rc ; error : goto done ; } int BucketManager::rebuildBucket (int num) { unsigned int mask; unsigned int hashnum; Element *ele; unsigned int random; int rc; for (multimap<unsigned int, Element*>::iterator it = _bucket[num]->_bucketMap.begin(); it != _bucket[num]->_bucketMap.end(); ++it) { hashnum = (*it).first; ele = (*it).second; mask = (1<<_index) - 1; random = hashnum & mask; if (random != _size - 1) continue; rc = _bucket[random]->createIndex ( hashnum, ele ) ; if (rc != 0) goto error; rc = _bucket[num]->removeIndex ( hashnum, ele ) ; if (rc != 0) { _bucket[random]->removeIndex ( hashnum, ele ) ; goto error; } } done: return rc ; error : goto done ; } int BucketManager::addBucket () { unsigned int num; int rc = 0 ; int i; Bucket *temp = NULL ; temp = new (std::nothrow) Bucket () ; if ( !temp ) { rc = -1 ; goto error ; } _bucket.push_back ( temp ) ; num = 1 << (_index - 1); i = _size % num; _size++; rebuildBucket(i); done: return rc ; error : goto done ; } int BucketManager::rebuildAll () { unsigned int mask, maskhash; unsigned int hashnum; Element *ele; unsigned int random; int size; int rc = 0 ; vector<Bucket *>tmp_bucket ; Bucket *temp = NULL ; temp = new (std::nothrow) Bucket () ; if ( !temp ) { rc = -1 ; goto error ; } _bucket.push_back ( temp ) ; _size++; _index++; cout<<"size:"<<_size<<" index:"<<_index<<"bucket size:"<<_bucket.size()<<endl; for(int num = 0; num < _size; num++) { Bucket *temp = NULL ; temp = new (std::nothrow) Bucket () ; if ( !temp ) { rc = -1 ; goto error ; } tmp_bucket.push_back ( temp ) ; } for(int num = 0; num < _size; num++) { for (multimap<unsigned int, Element*>::iterator it = _bucket[num]->_bucketMap.begin(); it != _bucket[num]->_bucketMap.end(); ++it ) { hashnum = (*it).first; ele = (*it).second; mask = (1<<_index) - 1; size = 1 << (_index - 1); maskhash = hashnum & mask; if (maskhash < _size) random = maskhash; else random = maskhash - size; tmp_bucket[random]->_bucketMap.insert(pair<unsigned int, Element*>(hashnum, ele)) ; } _bucket[num]->_bucketMap.clear(); } for(int num = 0; num < _size; num++) { for (multimap<unsigned int, Element*>::iterator it = tmp_bucket[num]->_bucketMap.begin(); it != tmp_bucket[num]->_bucketMap.end(); ++it ) { hashnum = (*it).first; ele = (*it).second; _bucket[num]->_bucketMap.insert(pair<unsigned int, Element*>(hashnum, ele)) ; } } for ( int i = 0; i < _size; ++i ) { temp = tmp_bucket[i] ; if ( temp ) delete temp ; } done: return rc ; error : goto done ; } void BucketManager::print () { for (int i = 0; i < _size; i++) { cout<<"bucket:"<<i<<endl; _bucket[i]->print(); cout<<endl; } } int BucketManager::Bucket::createIndex ( unsigned int hashNum, Element *ele ) { int rc = 0 ; Element *tmpele = new Element; *tmpele = *ele; _bucketMap.insert(pair<unsigned int, Element *>(hashNum, tmpele)) ; return rc ; } int BucketManager::Bucket::findIndex ( unsigned int hashNum, Element *ele ) { int rc = 0 ; pair<multimap<unsigned int, Element*>::iterator, multimap<unsigned int, Element*>::iterator> ret ; ret = _bucketMap.equal_range (hashNum) ; for ( multimap<unsigned int, Element*>::iterator it = ret.first ; it != ret.second; ++it ) { cout<<(*it).first<<" "<<(*it).second<<endl; } return rc ; } int BucketManager::Bucket::removeIndex ( unsigned int hashNum, Element *ele ) { int rc = 0 ; Element *tmpele; pair<multimap<unsigned int, Element*>::iterator, multimap<unsigned int, Element*>::iterator> ret ; ret = _bucketMap.equal_range (hashNum) ; for ( multimap<unsigned int, Element*>::iterator it = ret.first ; it != ret.second; ++it ) { tmpele = (*it).second; if (!memcmp(tmpele->data, ele->data, sizeof(ele->data))) { _bucketMap.erase(it) ; return rc ; } } return -1 ; } void BucketManager::Bucket::print () { pair<multimap<unsigned int, Element*>::iterator, multimap<unsigned int, Element*>::iterator> ret ; Element *ele; unsigned int hashnum; for ( multimap<unsigned int, Element*>::iterator it = _bucketMap.begin(); it != _bucketMap.end(); ++it ) { hashnum = (*it).first; ele = (*it).second; cout<<hex<<"hashnum:"<<hashnum; cout<<" id:"<<ele->id<<" data:"<<ele->data<<endl; } } void insert(BucketManager *bucketManager, Element &ele) { cout<<"insert: id= "<<ele.id<<" data= "<<ele.data<<endl; cout<<"==============================="<<endl; bucketManager->createIndex(&ele); bucketManager->print(); cout<<"*******************************"<<endl<<endl<<endl; } int main(int argc, const char *argv[]) { unsigned int hashnum; Element ele; BucketManager *bucketManager = new BucketManager(); bucketManager->initialize(); ele.id = 1; ele.data = "hello1"; insert(bucketManager, ele); ele.id = 2; ele.data = "hello2"; insert(bucketManager, ele); ele.id = 3; ele.data = "hello3"; insert(bucketManager, ele); ele.id = 13; ele.data = "hello13"; insert(bucketManager, ele); ele.id = 1; ele.data = "aaa"; insert(bucketManager, ele); ele.id = 2; ele.data = "bbb"; insert(bucketManager, ele); ele.id = 3; ele.data = "ccc"; insert(bucketManager, ele); ele.id = 4; ele.data = "ddd"; insert(bucketManager, ele); ele.id = 5; ele.data = "eee"; insert(bucketManager, ele); ele.id = 6; ele.data = "fff"; insert(bucketManager, ele); ele.id = 7; ele.data = "ggg"; insert(bucketManager, ele); ele.id = 18; ele.data = "hhh"; insert(bucketManager, ele); ele.id = 19; ele.data = "iii"; insert(bucketManager, ele); ele.id = 20; ele.data = "jjj"; insert(bucketManager, ele); ele.id = 21; ele.data = "kkk"; insert(bucketManager, ele); ele.id = 24; ele.data = "lll"; insert(bucketManager, ele); ele.id = 2; ele.data = "haha"; bucketManager->removeIndex(&ele); ele.id = 2; ele.data = "iii"; bucketManager->removeIndex(&ele); //bucketManager->print(); #if 0 multimap <unsigned int, char*> m; m.insert(pair<unsigned int,char*>(1,"Jack")); m.insert(pair<unsigned int,char*>(2,"Body")); m.insert(pair<unsigned int,char*>(2,"abc")); m.insert(pair<unsigned int,char*>(2,"ddd")); m.insert(pair<unsigned int,char*>(3,"Navy")); m.insert(pair<unsigned int,char*>(4,"Demo")); m.insert(pair<unsigned int,char*>(5,"Hello")); multimap<unsigned int, char*>::iterator it; #if 0 int num=m.count(2); it = m.find(2); cout<<"the search result is :"<<endl; for(int i=1;i<=num;i++) { cout<<(*it).first<<" "<<(*it).second<<endl; it++; } #else m.erase(2); pair<multimap<unsigned int, char*>::iterator, multimap<unsigned int, char*>::iterator> ret ; ret = m.equal_range (2) ; for ( multimap<unsigned int, char*>::iterator it = ret.first ; it != ret.second; ++it ) { cout<<(*it).first<<" "<<(*it).second<<endl; } #endif #endif return 0; }
true
8bb1bee257d9fcd47e1547c6e7d0acf4211b552e
C++
VenyaSob/Multiplayer
/Network/UdpSocket/UdpSocket.cpp
UTF-8
3,410
2.65625
3
[]
no_license
////////////////////////////////////////// // Headers // ////////////////////////////////////////// // #include "UdpSocket.h" // // ////////////////////////////////////////// namespace net { ////////////////////////////////////////////////////////////////////////////////////////////// // Methods // ////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// Socket::Status UdpSocket::Bind(const IpAddress address, const UINT16 port) // { Unbind(); socket_core = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); SOCKADDR_IN _addr_in = Socket::CreateSockAddrIn(address, port); if (bind(socket_core, reinterpret_cast<SOCKADDR*>(&_addr_in), sizeof(_addr_in)) == SOCKET_ERROR) return Error; return Done; } ///////////////////////////////////////////////////////////////////////////////// void UdpSocket::Unbind() // { Socket::Close(); } const size_t size = 256; ///////////////////////////////////////////////////////////////////////////////////////////////////////////// Socket::Status UdpSocket::Send(const DataPacket packet, const IpAddress address, const UINT16 port) const // { /* if (socket_core != INVALID_SOCKET) { size_t _size = packet.GetDataSize(); SOCKADDR_IN _addr_in = Socket::CreateSockAddrIn(address, port); if (packet.GetData() != nullptr && _size > 0) { if (sendto(socket_core, reinterpret_cast<LPCSTR>(&_size), sizeof(size_t), NULL, reinterpret_cast<const SOCKADDR*>(&_addr_in), sizeof(_addr_in)) == SOCKET_ERROR || sendto(socket_core, static_cast<LPCSTR>(packet.GetData()), _size, NULL, reinterpret_cast<const SOCKADDR*>(&_addr_in), sizeof(_addr_in)) == SOCKET_ERROR) return Error; } else return Error; } else return Error; */ SOCKADDR_IN _addr_in = Socket::CreateSockAddrIn(address, port); if (sendto(socket_core, static_cast<LPCSTR>(packet.GetData()), size, NULL, reinterpret_cast<const SOCKADDR*>(&_addr_in), sizeof(_addr_in)) == SOCKET_ERROR) return Error; return Done; } ///////////////////////////////////////////////////////////////////////////////////////////////// Socket::Status UdpSocket::Receive(DataPacket& packet, IpAddress& address, UINT16& port) const // { /* if (socket_core != INVALID_SOCKET) { SOCKADDR_IN _addr_in; size_t _size = 0; void* _data = nullptr; int _addr_in_size = sizeof(_addr_in); if (recvfrom(socket_core, reinterpret_cast<LPSTR>(&_size), sizeof(size_t), NULL, reinterpret_cast<SOCKADDR*>(&_addr_in), &_addr_in_size) == SOCKET_ERROR) return Error; _data = new BYTE[_size]; if(recvfrom(socket_core, reinterpret_cast<LPSTR>(_data), _size, NULL, reinterpret_cast<SOCKADDR*>(&_addr_in), &_addr_in_size) == SOCKET_ERROR) return Error; packet.Append(_data, _size); delete[] _data; address = IpAddress(ntohl(_addr_in.sin_addr.s_addr)); port = ntohs(_addr_in.sin_port); } else return Error; */ SOCKADDR_IN _addr_in; int _addr_in_size = sizeof(_addr_in); void* _data = new BYTE[size]; if (recvfrom(socket_core, reinterpret_cast<LPSTR>(_data), size, NULL, reinterpret_cast<SOCKADDR*>(&_addr_in), &_addr_in_size) == SOCKET_ERROR) return Error; return Done; } } // namespace net
true
4cf206b25ccecfce51f058f252ddbca92b6934fc
C++
Akeloya/Interpretator
/interpretator/Stack.h
UTF-8
383
3.171875
3
[ "MIT" ]
permissive
#pragma once namespace Interpreter { namespace Collections { template<typename T> class Stack { private: struct stackItem { public: stackItem* next; T Value; }; stackItem* _stack; int _depth; public: Stack(); void Push(T); T Pop(); T Peek(); T Take(int takenDepth); int Depth(); ~Stack(); }; } }
true
de86d460aeac079f95780ce970828868b9e77320
C++
xdinos/Cocoa
/CocoaEngine/include/cocoa/components/components.h
UTF-8
3,107
2.890625
3
[ "MIT" ]
permissive
#pragma once #include "externalLibs.h" #include "cocoa/physics2d/Physics2D.h" #include "cocoa/renderer/TextureHandle.h" #include "cocoa/renderer/Texture.h" #include "cocoa/util/Log.h" namespace Cocoa { struct Sprite { TextureHandle m_Texture = TextureHandle::null; int m_Width = 32; int m_Height = 32; glm::vec2 m_TexCoords[4] = { {1, 1}, {1, 0}, {0, 0}, {0, 1} }; }; class Spritesheet { public: TextureHandle m_TextureHandle; std::vector<Sprite> m_Sprites; Spritesheet(TextureHandle textureHandle, std::vector<Sprite> sprites) : m_Sprites(std::move(sprites)), m_TextureHandle(textureHandle) {} Spritesheet(TextureHandle textureHandle, int spriteWidth, int spriteHeight, int numSprites, int spacing) { m_TextureHandle = textureHandle; std::shared_ptr<Texture> texture = textureHandle.Get(); // NOTE: If you don't reserve the space before hand, when the vector grows it may // change the pointers it holds m_Sprites.reserve(numSprites); const uint8* rawPixels = texture->GetPixelBuffer(); int bytesPerPixel = texture->BytesPerPixel(); int area = spriteWidth * spriteHeight * bytesPerPixel; // This will be used to house temporary sprite data to calculate bounding boxes for all sprites std::unique_ptr<uint8> tmpSubImage(new uint8[area]); int currentX = 0; int currentY = texture->GetHeight() - spriteHeight; for (int i = 0; i < numSprites; i++) { float topY = (currentY + spriteHeight) / (float)texture->GetHeight(); float rightX = (currentX + spriteWidth) / (float)texture->GetWidth(); float leftX = currentX / (float)texture->GetWidth(); float bottomY = currentY / (float)texture->GetHeight(); for (int y = 0; y < spriteHeight; y++) { for (int x = 0; x < spriteWidth; x++) { int absY = y + currentY; int absX = x + currentX; int offset = (absX + absY * texture->GetWidth()) * bytesPerPixel; const uint8* pixel = rawPixels + offset; tmpSubImage.get()[(x + y * spriteWidth) * bytesPerPixel + 0] = *(pixel + 0); // R tmpSubImage.get()[(x + y * spriteWidth) * bytesPerPixel + 1] = *(pixel + 1); // G tmpSubImage.get()[(x + y * spriteWidth) * bytesPerPixel + 2] = *(pixel + 2); // B tmpSubImage.get()[(x + y * spriteWidth) * bytesPerPixel + 3] = *(pixel + 3); // A } } AABB boundingBox = Physics2D::GetBoundingBoxForPixels(tmpSubImage.get(), spriteWidth, spriteHeight, texture->BytesPerPixel()); Sprite sprite{ textureHandle, spriteWidth, spriteHeight, { {rightX, topY}, {rightX, bottomY}, {leftX, bottomY}, {leftX, topY} } }; m_Sprites.push_back(sprite); currentX += spriteWidth + spacing; if (currentX >= texture->GetWidth()) { currentX = 0; currentY -= spriteHeight + spacing; } } } Sprite GetSprite(int index) { return m_Sprites[index]; } int Size() { return (int)m_Sprites.size(); } }; struct SpriteRenderer { glm::vec4 m_Color = glm::vec4(1, 1, 1, 1); int m_ZIndex = 0; Sprite m_Sprite; }; }
true
8fac544fdae62ed2240227ae5d94fd75fd3304c1
C++
nuriu/ogy-oyunlar
/breakout-ish/src/Scenes/MenuScene.cpp
UTF-8
2,750
2.53125
3
[]
no_license
#include <Scenes/MenuScene.hpp> MenuScene::MenuScene(const CoreComponents& components) : m_Components(components) , m_Title(std::make_unique<sf::Text>()) , m_Start(std::make_unique<sf::Text>()) , m_Exit(std::make_unique<sf::Text>()) , m_MenuSelectedIndex(0) { } void MenuScene::initialize() { m_Components.m_AssetManager->loadSound("click", "sounds/click.wav"); m_Title->setCharacterSize(100); m_Title->setString("Breakout-ish"); m_Title->setFont(m_Components.m_AssetManager->getFont("kenney-high")); m_Title->setPosition(m_Components.m_RenderWindow->getSize().x / 2.0f - m_Title->getLocalBounds().width / 2.0f, m_Components.m_RenderWindow->getSize().y / 4.f); m_Start->setCharacterSize(50); m_Start->setString("Start"); m_Start->setFillColor(sf::Color::Green); m_Start->setFont(m_Components.m_AssetManager->getFont("kenney-high")); m_Start->setPosition(m_Components.m_RenderWindow->getSize().x / 2.0f - m_Start->getLocalBounds().width / 2.0f, m_Components.m_RenderWindow->getSize().y / 1.5f); m_Exit->setCharacterSize(50); m_Exit->setString("Exit"); m_Exit->setFont(m_Components.m_AssetManager->getFont("kenney-high")); m_Exit->setPosition(m_Components.m_RenderWindow->getSize().x / 2.0f - m_Exit->getLocalBounds().width / 2.0f, m_Start->getPosition().y + m_Start->getLocalBounds().height * 2.0f); } void MenuScene::processInput() { if (m_Components.m_InputManager->isKeyPressed(sf::Keyboard::Up) || m_Components.m_InputManager->isKeyPressed(sf::Keyboard::Down)) { m_Components.m_AssetManager->playSound("click"); if (m_MenuSelectedIndex == 0) { m_MenuSelectedIndex = 1; m_Start->setFillColor(sf::Color::White); m_Exit->setFillColor(sf::Color::Green); } else { m_MenuSelectedIndex = 0; m_Start->setFillColor(sf::Color::Green); m_Exit->setFillColor(sf::Color::White); } } if (m_Components.m_InputManager->isKeyPressed(sf::Keyboard::Enter)) { if (m_MenuSelectedIndex == 0) { m_Components.m_SceneManager->pushScene( ScenePtr(std::make_unique<PaddleSelectScene>(m_Components)), true); } else { m_Components.m_RenderWindow->close(); } } } void MenuScene::update() {} void MenuScene::render() const { m_Components.m_RenderWindow->draw(*m_Title); m_Components.m_RenderWindow->draw(*m_Start); m_Components.m_RenderWindow->draw(*m_Exit); }
true
649d10093b5db3eae0c4d97ed12a9c2a8f93ab22
C++
AutumnKite/Codes
/互测2022/day6/C/std.cpp
UTF-8
3,702
2.546875
3
[]
no_license
#include <bits/stdc++.h> template<typename Val> class fast_copy_array { public: typedef std::size_t size_type; protected: size_type n; struct node { node *ls, *rs; Val v; node() : ls(), rs(), v() {} }; node *rt; void modify(node *&u, size_type l, size_type r, size_type x, const Val &v) { if (u == nullptr) { u = new node(); } else { u = new node(*u); } if (l + 1 == r) { u->v = v; return; } size_type mid = (l + r) >> 1; if (x < mid) { modify(u->ls, l, mid, x, v); } else { modify(u->rs, mid, r, x, v); } } Val query(node *u, size_type l, size_type r, size_type x) const { if (u == nullptr) { return Val(); } if (l + 1 == r) { return u->v; } size_type mid = (l + r) >> 1; if (x < mid) { return query(u->ls, l, mid, x); } else { return query(u->rs, mid, r, x); } } public: fast_copy_array(size_type n) : n(n), rt(nullptr) {} void modify(size_type x, const Val &v) { modify(rt, 0, n, x, v); } Val query(size_type x) const { return query(rt, 0, n, x); } }; class AC_automaton { int C, tot; std::vector<std::map<int, int>> son; std::vector<fast_copy_array<int>> trans; std::vector<int> fail; std::vector<int> sum; int new_node() { int u = tot++; son.emplace_back(); trans.emplace_back(C); fail.emplace_back(-1); sum.emplace_back(0); return u; } public: AC_automaton(int C) : C(C), tot() { new_node(); } void insert(const std::vector<int> &a) { int u = 0; for (int x : a) { int &v = son[u][x]; if (!v) { v = new_node(); } u = v; } ++sum[u]; } void build() { std::vector<int> Q; for (auto [c, v] : son[0]) { trans[0].modify(c, v); fail[v] = 0; Q.push_back(v); } for (int i = 0; i < (int)Q.size(); ++i) { int u = Q[i]; trans[u] = trans[fail[u]]; sum[u] += sum[fail[u]]; for (auto [c, v] : son[u]) { trans[u].modify(c, v); fail[v] = trans[fail[u]].query(c); Q.push_back(v); } } } int total() const { return tot; } int next(int u, int c) const { return trans[u].query(c); } bool check(int u) const { return !sum[u]; } }; constexpr long long INF = std::numeric_limits<long long>::max() / 2; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n, m, k; std::cin >> n >> m >> k; std::vector<std::vector<std::pair<int, int>>> E(n); for (int i = 0; i < m; ++i) { int u, v, w; std::cin >> u >> v >> w; --u, --v; E[u].emplace_back(v, w); } AC_automaton A(n); for (int i = 0; i < k; ++i) { int c; std::cin >> c; std::vector<int> p(c); for (int j = 0; j < c; ++j) { std::cin >> p[j]; --p[j]; } A.insert(p); } A.build(); std::vector<std::map<int, long long>> dis(n); std::vector<std::map<int, bool>> vis(n); std::vector<int> cnt(n); std::priority_queue<std::tuple<long long, int, int>> Q; int st = A.next(0, 0); dis[0][st] = 0; Q.emplace(0, 0, st); while (!Q.empty()) { auto [d, u, st] = Q.top(); Q.pop(); if (vis[u][st]) { continue; } if (u == n - 1) { std::cout << dis[u][st] << "\n"; return 0; } vis[u][st] = true; ++cnt[u]; if (cnt[u] >= 50) { continue; } for (auto [v, w] : E[u]) { int nx = A.next(st, v); if (A.check(nx) && (!dis[v].count(nx) || dis[u][st] + w < dis[v][nx])) { dis[v][nx] = dis[u][st] + w; Q.emplace(-dis[v][nx], v, nx); } } } std::cout << -1 << "\n"; }
true
a7416e009415eb7ec05bb174dbecadde5eb5b6e5
C++
mardanovaAA/Laborat_2sem
/Sort/Sort_algorithms.cpp
UTF-8
7,527
3.546875
4
[]
no_license
#include <iostream> #include <cstdlib> #include <chrono> #include <fstream> void print_arr(int* arr, int len){ for (int i = 0; i < len; i++){ std::cout << arr[i] << " "; } std::cout << std::endl; } void bubble_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; int change; for (int i = 0; i < len; i++){ for (int j = 0; j < len - i - 1; j++){ if ((mod) && (arr[j] > arr[j+1])){ change = arr[j]; arr[j] = arr[j+1]; arr[j+1] = change; } if ((!mod) && (arr[j] < arr[j+1])){ change = arr[j]; arr[j] = arr[j+1]; arr[j+1] = change; } } } } void shaker_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; int change; int left_board = 0; int right_board = len - 1; while (right_board >= left_board){ for (int j = left_board; j < right_board; j++){ if ((mod) && (arr[j] > arr[j+1])){ change = arr[j]; arr[j] = arr[j+1]; arr[j+1] = change; } if ((!mod) && (arr[j] < arr[j+1])){ change = arr[j]; arr[j] = arr[j+1]; arr[j+1] = change; } } right_board--; for (int j = right_board; j > left_board; j--){ if ((!mod) && (arr[j] > arr[j-1])){ change = arr[j]; arr[j] = arr[j-1]; arr[j-1] = change; } if ((mod) && (arr[j] < arr[j-1])){ change = arr[j]; arr[j] = arr[j-1]; arr[j-1] = change; } } left_board++; } } void insertion_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; int change; for (int i = 1; i < len; i++){ for (int j = i; j >0; j--){ if ((!mod) && (arr[j] > arr[j-1])){ change = arr[j]; arr[j] = arr[j-1]; arr[j-1] = change; } if ((mod) && (arr[j] < arr[j-1])){ change = arr[j]; arr[j] = arr[j-1]; arr[j-1] = change; } } } } void shell_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; int step = len / 2; while (step > 0){ for (int i = step; i < len; i++){ for (int j = i; j >= step; j -= step){ if ((!mod) && (arr[j] > arr[j - step])){ int change = arr[j]; arr[j] = arr[j - step]; arr[j - step] = change; } if ((mod) && (arr[j] < arr[j - step])){ int change = arr[j]; arr[j] = arr[j - step]; arr[j - step] = change; } } } if (step == 2){ step = 1; } else { step /= 2; } } } void selection_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; for (int i = 0; i < len; i++){ int extreme_pos = i; for (int j = i + 1; j < len; j++){ if ((mod) && (arr[j] < arr[extreme_pos])){ //find minimum extreme_pos = j; } if ((!mod) && (arr[j] > arr[extreme_pos])){ //find maximum extreme_pos = j; } } if (i != extreme_pos){ int change = arr[i]; arr[i] = arr[extreme_pos]; arr[extreme_pos] = change; } } } void merge_sort(int* arr, int len, bool mod = true){ //mod = true - from small to big; //mod = false - from big to small; int len_left = len / 2; int len_right = len - len / 2; if (len > 1){ merge_sort(&arr[0], len_left, mod); merge_sort(&arr[len_left], len_right, mod); int* arr2merge = new int [len]; int i = 0; int start_left = 0; int start_right = len_left; while ((start_left < len_left) || (start_right < len)){ if (mod){ if (arr[start_left] < arr[start_right]){ arr2merge[i] = arr[start_left]; start_left++; i++; } else { arr2merge[i] = arr[start_right]; start_right++; i++; } } if (!mod){ if (arr[start_left] > arr[start_right]){ arr2merge[i] = arr[start_left]; start_left++; i++; } else { arr2merge[i] = arr[start_right]; start_right++; i++; } } if (start_left == len_left){ while (start_right < len){ arr2merge[i] = arr[start_right]; start_right++; i++; } } if (start_right == len){ while (start_left < len_left){ arr2merge[i] = arr[start_left]; start_left++; i++; } } } //replace the part of initial arr with arr2merge for (int i = 0; i < len; i++){ arr[i] = arr2merge[i]; } delete [] arr2merge; } } void quick_sort(int* arr, int len, bool mod = true){ //!This sort is based on the random. //mod = true - from small to big; //mod = false - from big to small; int left = 0; int right = len - 1; int opor = rand() % len; int mid = arr[opor]; do { while ((mod) && (arr[left] < mid)) { left++; } while ((mod) && (arr[right] > mid)) { right--; } while ((!mod) && (arr[left] > mid)) { left++; } while ((!mod) && (arr[right] < mid)) { right--; } if (left <= right) { int tmp = arr[left]; arr[left] = arr[right]; arr[right] = tmp; left++; right--; } } while (left <= right); if (right > 0) { quick_sort(arr, right + 1, mod); } if (left < len) { quick_sort(&arr[left], len - left, mod); } } int main(){ int N = 10; std::ofstream out; out.open("Time_data.txt"); while (N < 500000){ int* arr = new int[N]; for (int i = 0; i < N; i++){ arr[i] = rand(); } auto time_begin = std::chrono::steady_clock::now(); quick_sort(arr, N, true); auto time_finish = std::chrono::steady_clock::now(); //print_arr(arr, N); auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_finish - time_begin); if (out.is_open()){ out << elapsed_ms.count() << std::endl; } std::cout << N << std::endl; delete [] arr; N *= 5; } out.close(); return 0; }
true
8a436e86beac64ec6da7c3d93da1a83c6d8f1fed
C++
DaanNiphuis/Jigsaw3D
/source/Jigsaw3D/Matrix44.h
UTF-8
7,789
2.765625
3
[]
no_license
#ifndef MATRIX44_H #define MATRIX44_H #include "Debug.h" #include "Vector3.h" #include "Vector4.h" #include <string> class Matrix44 { public: union { float m[4][4]; float _m[16]; }; inline Matrix44() { } inline Matrix44( float p_m00, float p_m01, float p_m02, float p_m03, float p_m10, float p_m11, float p_m12, float p_m13, float p_m20, float p_m21, float p_m22, float p_m23, float p_m30, float p_m31, float p_m32, float p_m33 ) { _m[0] = p_m00; _m[1] = p_m01; _m[2] = p_m02; _m[3] = p_m03; _m[4] = p_m10; _m[5] = p_m11; _m[6] = p_m12; _m[7] = p_m13; _m[8] = p_m20; _m[9] = p_m21; _m[10] = p_m22; _m[11] = p_m23; _m[12] = p_m30; _m[13] = p_m31; _m[14] = p_m32; _m[15] = p_m33; } inline float* operator [] (size_t p_iRow) { ASSERT(p_iRow < 4, "Out of bounds."); return m[p_iRow]; } inline const float *const operator [] (size_t p_iRow) const { ASSERT(p_iRow < 4, "Out of bounds."); return m[p_iRow]; } inline Matrix44 concatenate(const Matrix44& p_m2) const { Matrix44 r; r.m[0][0] = m[0][0] * p_m2.m[0][0] + m[0][1] * p_m2.m[1][0] + m[0][2] * p_m2.m[2][0] + m[0][3] * p_m2.m[3][0]; r.m[0][1] = m[0][0] * p_m2.m[0][1] + m[0][1] * p_m2.m[1][1] + m[0][2] * p_m2.m[2][1] + m[0][3] * p_m2.m[3][1]; r.m[0][2] = m[0][0] * p_m2.m[0][2] + m[0][1] * p_m2.m[1][2] + m[0][2] * p_m2.m[2][2] + m[0][3] * p_m2.m[3][2]; r.m[0][3] = m[0][0] * p_m2.m[0][3] + m[0][1] * p_m2.m[1][3] + m[0][2] * p_m2.m[2][3] + m[0][3] * p_m2.m[3][3]; r.m[1][0] = m[1][0] * p_m2.m[0][0] + m[1][1] * p_m2.m[1][0] + m[1][2] * p_m2.m[2][0] + m[1][3] * p_m2.m[3][0]; r.m[1][1] = m[1][0] * p_m2.m[0][1] + m[1][1] * p_m2.m[1][1] + m[1][2] * p_m2.m[2][1] + m[1][3] * p_m2.m[3][1]; r.m[1][2] = m[1][0] * p_m2.m[0][2] + m[1][1] * p_m2.m[1][2] + m[1][2] * p_m2.m[2][2] + m[1][3] * p_m2.m[3][2]; r.m[1][3] = m[1][0] * p_m2.m[0][3] + m[1][1] * p_m2.m[1][3] + m[1][2] * p_m2.m[2][3] + m[1][3] * p_m2.m[3][3]; r.m[2][0] = m[2][0] * p_m2.m[0][0] + m[2][1] * p_m2.m[1][0] + m[2][2] * p_m2.m[2][0] + m[2][3] * p_m2.m[3][0]; r.m[2][1] = m[2][0] * p_m2.m[0][1] + m[2][1] * p_m2.m[1][1] + m[2][2] * p_m2.m[2][1] + m[2][3] * p_m2.m[3][1]; r.m[2][2] = m[2][0] * p_m2.m[0][2] + m[2][1] * p_m2.m[1][2] + m[2][2] * p_m2.m[2][2] + m[2][3] * p_m2.m[3][2]; r.m[2][3] = m[2][0] * p_m2.m[0][3] + m[2][1] * p_m2.m[1][3] + m[2][2] * p_m2.m[2][3] + m[2][3] * p_m2.m[3][3]; r.m[3][0] = m[3][0] * p_m2.m[0][0] + m[3][1] * p_m2.m[1][0] + m[3][2] * p_m2.m[2][0] + m[3][3] * p_m2.m[3][0]; r.m[3][1] = m[3][0] * p_m2.m[0][1] + m[3][1] * p_m2.m[1][1] + m[3][2] * p_m2.m[2][1] + m[3][3] * p_m2.m[3][1]; r.m[3][2] = m[3][0] * p_m2.m[0][2] + m[3][1] * p_m2.m[1][2] + m[3][2] * p_m2.m[2][2] + m[3][3] * p_m2.m[3][2]; r.m[3][3] = m[3][0] * p_m2.m[0][3] + m[3][1] * p_m2.m[1][3] + m[3][2] * p_m2.m[2][3] + m[3][3] * p_m2.m[3][3]; return r; } // Matrix concatenation using '*'. inline Matrix44 operator * (const Matrix44& p_matrix) const { return concatenate(p_matrix); } inline Vector4 operator * (const Vector4& p_vector) const { return Vector4( m[0][0] * p_vector.x + m[0][1] * p_vector.y + m[0][2] * p_vector.z + m[0][3] * p_vector.w, m[1][0] * p_vector.x + m[1][1] * p_vector.y + m[1][2] * p_vector.z + m[1][3] * p_vector.w, m[2][0] * p_vector.x + m[2][1] * p_vector.y + m[2][2] * p_vector.z + m[2][3] * p_vector.w, m[3][0] * p_vector.x + m[3][1] * p_vector.y + m[3][2] * p_vector.z + m[3][3] * p_vector.w); } inline void setTransform(const Vector3& p_position, const Vector3& p_rotation, const Vector3& p_scale) { const float cosX = Math::cosine(p_rotation.x); const float cosY = Math::cosine(p_rotation.y); const float cosZ = Math::cosine(p_rotation.z); const float sinX = Math::sine(p_rotation.x); const float sinY = Math::sine(p_rotation.y); const float sinZ = Math::sine(p_rotation.z); // row 0 m[0][0] = cosY*cosZ * p_scale.x; m[0][1] = (-cosX*sinZ+sinX*sinY*cosZ) * p_scale.y; m[0][2] = (sinX*sinZ+cosX*sinY*cosZ) * p_scale.z; m[0][3] = p_position.x; // row 1 m[1][0] = cosY*sinZ * p_scale.x; m[1][1] = (cosX*cosZ+sinX*sinY*sinZ) * p_scale.y; m[1][2] = (-sinX*cosZ+cosX*sinY*sinZ) * p_scale.z; m[1][3] = p_position.y; // row 2 m[2][0] = -sinY * p_scale.x; m[2][1] = sinX*cosY * p_scale.y; m[2][2] = cosX*cosY* p_scale.z; m[2][3] = p_position.z; // row 3 m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; } inline void transpose() { std::swap(m[1][0],m[0][1]); std::swap(m[2][0],m[0][2]); std::swap(m[3][0],m[0][3]); std::swap(m[2][1],m[1][2]); std::swap(m[3][1],m[1][3]); std::swap(m[3][2],m[2][3]); } inline Matrix44 getTranspose() const { return Matrix44(m[0][0], m[1][0], m[2][0], m[3][0], m[0][1], m[1][1], m[2][1], m[3][1], m[0][2], m[1][2], m[2][2], m[3][2], m[0][3], m[1][3], m[2][3], m[3][3]); } Matrix44 getInverse() const { float m00 = m[0][0], m01 = m[0][1], m02 = m[0][2], m03 = m[0][3]; float m10 = m[1][0], m11 = m[1][1], m12 = m[1][2], m13 = m[1][3]; float m20 = m[2][0], m21 = m[2][1], m22 = m[2][2], m23 = m[2][3]; float m30 = m[3][0], m31 = m[3][1], m32 = m[3][2], m33 = m[3][3]; float v0 = m20 * m31 - m21 * m30; float v1 = m20 * m32 - m22 * m30; float v2 = m20 * m33 - m23 * m30; float v3 = m21 * m32 - m22 * m31; float v4 = m21 * m33 - m23 * m31; float v5 = m22 * m33 - m23 * m32; float t00 = + (v5 * m11 - v4 * m12 + v3 * m13); float t10 = - (v5 * m10 - v2 * m12 + v1 * m13); float t20 = + (v4 * m10 - v2 * m11 + v0 * m13); float t30 = - (v3 * m10 - v1 * m11 + v0 * m12); float invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03); float d00 = t00 * invDet; float d10 = t10 * invDet; float d20 = t20 * invDet; float d30 = t30 * invDet; float d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; float d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; float d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; float d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; v0 = m10 * m31 - m11 * m30; v1 = m10 * m32 - m12 * m30; v2 = m10 * m33 - m13 * m30; v3 = m11 * m32 - m12 * m31; v4 = m11 * m33 - m13 * m31; v5 = m12 * m33 - m13 * m32; float d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet; float d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet; float d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet; float d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet; v0 = m21 * m10 - m20 * m11; v1 = m22 * m10 - m20 * m12; v2 = m23 * m10 - m20 * m13; v3 = m22 * m11 - m21 * m12; v4 = m23 * m11 - m21 * m13; v5 = m23 * m12 - m22 * m13; float d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet; float d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet; float d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet; float d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet; return Matrix44( d00, d01, d02, d03, d10, d11, d12, d13, d20, d21, d22, d23, d30, d31, d32, d33); } friend std::ostream& operator << (std::ostream& p_os, const Matrix44& p_mat) { return p_os << "| " << p_mat[0][0] << " " << p_mat[0][1] << " " << p_mat[0][2] << " " << p_mat[0][3] << " |" << std::endl << "| " << p_mat[1][0] << " " << p_mat[1][1] << " " << p_mat[1][2] << " " << p_mat[1][3] << " |" << std::endl << "| " << p_mat[2][0] << " " << p_mat[2][1] << " " << p_mat[2][2] << " " << p_mat[2][3] << " |" << std::endl << "| " << p_mat[3][0] << " " << p_mat[3][1] << " " << p_mat[3][2] << " " << p_mat[3][3] << " |"; } static const Matrix44 IDENTITY; }; #endif
true
c62c3ac1a323e029a7bab1d3a16614dcddc4f740
C++
petrecristi/SonerieSMART
/ConectareMQTT.cpp
UTF-8
1,666
2.609375
3
[]
no_license
#include "ConectareMQTT.h" WiFiClient wifiClient; PubSubClient client(wifiClient); //constructor ConectareMQTTClass::ConectareMQTTClass() { } void ConectareMQTTClass::Publica(const char *text) { client.publish(MQTT_SERIAL_PUBLISH_CH, text); } void ConectareMQTTClass::setup_wifi() { //Serial.begin(115200); delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { //Serial.print("."); delay(500); } randomSeed(micros()); //Serial.println(WiFi.localIP()); } void ConectareMQTTClass::reconnect() { // Loop until we're reconnected while (!client.connected()) { String clientId = "ESP32ClientTest-"; clientId += String(random(0xffff), HEX); String textSalut = "Salut. Sunt " + (String)clientId + " si m-am conectat la MQTT!"; String cc = clientId; cc+= " IP: "; cc+= (char*)WiFi.localIP().toString().c_str(); if (client.connect(clientId.c_str())) { // Serial.println("connected"); //Once connected, publish an announcement... client.publish(MQTT_SERIAL_PUBLISH_CH, textSalut.c_str()); client.publish(MQTT_SERIAL_PUBLISH_CH, cc.c_str()); //client.publish(MQTT_SERIAL_PUBLISH_CH, "Sunt Esp32, m-am conectat la mqtt. "); // ... and resubscribe client.subscribe(MQTT_SERIAL_RECEIVER_CH); //Serial.println("M=am conectat la mqtt"); } else { //Serial.println("Nu s-a conectat la mqtt"); delay(5000); } } } void ConectareMQTTClass::setupM() { client.setServer(mqtt_server, mqtt_port); client.setCallback([this](char* topic, uint8_t* payload, unsigned int length) {this->callback(topic, payload, length); }); } void ConectareMQTTClass::loopM() { client.loop(); }
true
51f63f8b123262929f93dec492ac9fb2f7af23f8
C++
Aranaevens/tetra-solver
/tile.hxx
UTF-8
1,431
3.421875
3
[]
no_license
template<class T> Tile<T>::Tile() {} template<class T> Tile<T>::Tile(T s, T e, T n, T w) { south_ = s; east_ = e; north_ = n; west_ = w; } template<class T> Tile<T>::~Tile() {} template<class T> void Tile<T>::set_north(T n) { north_ = n; } template<class T> void Tile<T>::set_east(T e) { east_ = e; } template<class T> void Tile<T>::set_south(T s) { south_ = s; } template<class T> void Tile<T>::set_west(T w) { west_ = w; } template<class T> T Tile<T>::get_north() const { return north_; } template<class T> T Tile<T>::get_east() const { return east_; } template<class T> T Tile<T>::get_south() const { return south_; } template<class T> T Tile<T>::get_west() const { return west_; } template<class T> void Tile<T>::print(std::ofstream& ofs) const { ofs << get_south() << " " << get_east() << " " << get_north() << " " << get_west(); } /*template<class T> bool Tile<T>::match_left(Tile& T, Tile& left) { if (T.get_west() == left.get_east()) return true; else return false; } template<class T> bool Tile<T>::match_top(Tile& T, Tile& top) { if (T.get_north() == left.get_south()) return true; else return false; } template<class T> bool Tile<T>::match_both(Tile& T, Tile& left, Tile& top) { if ((T.get_west() == left.get_east()) && (T.get_north() == top.get_south())) return true; else return false; }*/
true
3e49b0b7fc757184bbf31b3fb474278cddfe6f91
C++
TorqueRolled/itsthisonebeth
/Space.hpp
UTF-8
691
2.625
3
[]
no_license
/************************************************************************ * Author: Jacob Theander * Date: 3/18/2019 * Description: hpp file for space class. Contains setters and getters * for space objects. ***********************************************************************/ #ifndef SPACE_HPP #define SPACE_HPP #include "Pack.hpp" class Space { protected: bool completed; Space* up; Space* down; Space* left; Space* right; friend class Player; public: void set(Space*, Space*, Space*, Space*); bool getStatus(); Space* getUp(); Space* getDown(); Space* getLeft(); Space* getRight(); virtual void event(int, Pack&, int&) = 0; }; #endif
true
ce1bb5ff82a32e5744e3af3a967b5854139d90ce
C++
BryceKopan/2RPG
/src/gameLogic/gameObject/attack/Projectile.h
UTF-8
544
2.515625
3
[]
no_license
#ifndef PROJECTILE_H #define PROJECTILE_H #include "Attack.h" #include "../../../util/Vector2.h" class Projectile : public Attack { public: Projectile(Point location, Sprite sprite, bool playerFriendly, int lifetime, int damage, Vector2 velocity, double speed); virtual void update(); virtual void onObjectCollision(ObjectVector gameObjects); virtual void onTileCollision(); private: Vector2 velocity; double speed; void move(); }; #endif
true
20ae3614e367cfa64c375ef5eb683e57b4e9cfca
C++
auroraleso/Cpp-course
/examples_theory/teacher/7_vector_inheritance/vfunct/testShapeFun.cc
UTF-8
1,926
3.84375
4
[]
no_license
#include "Triangle.h" #include "Square.h" #include "Rectangle.h" #include <iostream> #include <vector> using namespace std; // function taking a Shape argument by reference: // its actual type (triangle, square...) is preserved void printRef( int i, const Shape& s ) { cout << "shape " << i << " has perimeter " << s.perimeter() << " and area " << s.area() << endl; return; } // function taking a Shape argument by value: object is copied // and its actual type (triangle, square...) is lost void printVal( int i, const Shape s ) { cout << "shape " << i << " has perimeter " << s.perimeter() << " and area " << s.area() << endl; return; } int main() { // an array of geometric shapes vector<Shape*> shape; cout << "create generic shape" << endl; shape.push_back( new Shape ); cout << "create triangle with base 3.5 and height 6.7" << endl; shape.push_back( new Triangle ( 3.5, 6.7 ) ); cout << "create triangle with sides 5.6, 7.5, 4.2" << endl; shape.push_back( new Triangle ( 5.6, 7.5, 4.2 ) ); cout << "create rectangle with base 5.3 and height 7.6" << endl; shape.push_back( new Rectangle( 5.3, 7.6 ) ); cout << "create square with side 4.4" << endl; shape.push_back( new Square ( 4.4 ) ); cout << "************" << endl; // loop over shapes int i; int n = shape.size(); for ( i = 0; i < n; ++i ) { // get the pointer to the shape const Shape* s = shape[i]; // call the function taking the Shape as argument by reference // its actual type (triangle, square...) is preserved printRef( i, *s ); cout << "----------" << endl; // call the function taking the Shape as argument by value // its actual type (triangle, square...) is lost printVal( i, *s ); cout << "++++++++++" << endl; } // delete all the shapes for ( i = 0; i < n; ++i ) delete shape[i]; return 0; }
true
93056325daa0042a22e919bdc2165087d25ec45d
C++
iwiwi/programming-contests
/sgu/38/C.cpp
UTF-8
1,401
2.515625
3
[]
no_license
#include <cstdio> #include <algorithm> #include <utility> #include <climits> #include <iostream> #include <vector> using namespace std; #define rep(i, n) for (int i = 0; i < int(n); ++i) #define pb push_back #define mp make_pair #define F first #define S second typedef long long ll; int N; vector<pair<int, pair<int, int> > > hor, ver; // hor: -, ver: | int main() { while (1 == scanf("%d", &N) && N) { hor.clear(); ver.clear(); rep (i, N) { int x1, y1, x2, y2; scanf("%d%d%d%d", &x1, &y1, &x2, &y2); if (x1 == x2) ver.pb(mp(x1, mp(min(y1, y2), max(y1, y2)))); else hor.pb(mp(y1, mp(min(x1, x2), max(x1, x2)))); } if (ver.size() > hor.size()) ver.swap(hor); sort(ver.begin(), ver.end()); sort(hor.begin(), hor.end()); ll ans = 0; rep (ri, ver.size()) { int rx = ver[ri].F; rep (li, ri) { int lx = ver[li].F; int min_y = max(ver[li].S.F, ver[ri].S.F); int max_y = min(ver[li].S.S, ver[ri].S.S); if (min_y >= max_y) continue; int cnt = 0; rep (hi, hor.size()) { if (min_y <= hor[hi].F && hor[hi].F <= max_y && hor[hi].S.F <= lx && rx <= hor[hi].S.S) { ++cnt; } } // printf("%d - %d: %d\n", lx, rx, cnt); ans += cnt * (cnt - 1) / 2; } } cout << ans << endl; } return 0; }
true
1ade708f2663592473a86b19a001cccc1dc76581
C++
shunya-s15/Atcoder
/ABC181/d.cpp
UTF-8
1,654
2.828125
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> #include<cmath> using namespace std; int main(){ string s; cin >> s; bool ans=false; int key=104; int key2=16; if(s.length()==1&&s.at(0)=='8'){ cout << "Yes" << endl; return 0; } else if(s.length()==2){ while(key2<100){ bool flag1=false,flag2=false; string copy=to_string(key2); char keta2=copy.at(1); char keta1=copy.at(0); if((keta1==s.at(0) && keta2==s.at(1)) || (keta1==s.at(1)&&keta2==s.at(0))){ cout << "Yes" << endl; return 0; } key2+=8; } } while(key<1000){ bool flag1=false,flag2=false,flag3=false; string copy=to_string(key); char keta3=copy.at(2); char keta2=copy.at(1); char keta1=copy.at(0); int i,j,k; /*cout << keta3 << endl; cout << keta2 << endl; cout << keta1 << endl;*/ for(i=0;i<s.length();i++){ if(keta3==s.at(i)){ flag3=true; break; } } for(j=0;j<s.length();j++){ if(keta2==s.at(j)&&i!=j){ flag2=true; break; } } for(k=0;k<s.length();k++){ if(keta1==s.at(k)&&i!=k&&j!=k){ flag1=true; break; } } if(flag3&&flag2&&flag1){ ans=true; break; } key+=8; } if(ans){ cout<<"Yes"<<endl; }else{ cout<<"No"<<endl; } return 0; }
true
3bbee1e3cd32e0965b2e6befb1ed1e6007756796
C++
FlyingRhenquest/fr_demo
/ephemeris_cache.h
UTF-8
5,694
2.703125
3
[ "Apache-2.0" ]
permissive
/** * This object caches ephemeris lines and can be called upon to * retrieve them for a given time. This object will delete * ephemeris lines put into it when it is deleted, so there's * no need to track that yourself. * * Copyright 2011 Bruce Ide * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _H_EPHEMERIS_CACHE #define _H_EPHEMERIS_CACHE #include "coordinates.h" #include "ephemeris_line.h" #include <map> #include <string> #include <time.h> #include <iostream> #include <vector> #include "time_tree.h" class EphemerisCache { class SatelliteTreeDeallocator { public: void operator()(EphemerisLine *value) { delete value;} }; typedef TimeTree<double, EphemerisLine *, SatelliteTreeDeallocator> SatelliteTree; typedef std::map<std::string, SatelliteTree *> SatelliteMap; typedef std::map<std::string, double> IntervalMap; SatelliteMap satellites; /** * intervals tracks coordinate intervals. If you request a time * later than the latest coordinate + the interval for that satellite, * "not found" should be returned. */ IntervalMap intervals; /** * (re)calculates the average data interval of your ephemeris points. * This is really only to provide "not found" points past the end * of the file, but I guess that's fairly useful information. I * could add a flag to not do this if I don't query that space * that often. Will have to see... */ double calcInterval(const std::string &satellite) { SatelliteMap::iterator iter = satellites.find(satellite); double retval = 0.0; if (iter != satellites.end()) { double timeAccum = 0.0; double lastTime = 0.0; long nelems = 0; SatelliteTree *tree = iter->second; SatelliteTree::RangeType treeRange; SatelliteTree::RangeType::iterator rangeIter; tree->findRange(treeRange, tree->begin(), tree->end()); rangeIter = treeRange.begin(); while(rangeIter != treeRange.end()) { if (lastTime == 0.0) { lastTime = (*rangeIter)->first; rangeIter++; continue; } nelems++; timeAccum += (*rangeIter)->first - lastTime; lastTime = (*rangeIter)->first; rangeIter++; } retval = timeAccum / (double) nelems; intervals[satellite] = retval; } return retval; } public: EphemerisLine *NOT_FOUND; EphemerisCache() { NOT_FOUND = (EphemerisLine *) NULL; } ~EphemerisCache() { SatelliteMap::iterator sats = satellites.begin(); while (sats != satellites.end()) { delete sats->second; sats++; } } /** * Note that if you want this function to work correctly, * you'll need to set your time in your EphemerisLine */ void add(const std::string &satellite, EphemerisLine *line) { SatelliteMap::iterator sat = satellites.find(satellite); SatelliteTree *found = NULL; if (sat == satellites.end()) { SatelliteTree *newSat = new SatelliteTree(NOT_FOUND); satellites[satellite] = newSat; intervals[satellite] = 0.0; found = newSat; } else { found = sat->second; } found->add(line->getTime(), line); } /** * Get gets the EphemerisLine for the satellite for a given * time. Returns NULL if not found. */ EphemerisLine *get(const std::string &satellite, double time) { EphemerisLine *retval = (EphemerisLine *) NULL; SatelliteMap::iterator sat = satellites.find(satellite); SatelliteTree *found = NULL; if (sat != satellites.end()) { found = sat->second; double dataInterval = 0.0; /* * We really only need to know the data interval if we're * querying past the end of the data points we have. */ if (time > found->end()) { IntervalMap::iterator intr = intervals.find(satellite); if (intr == intervals.end() || intr->second == 0.0) { dataInterval = calcInterval(satellite); } else { dataInterval = intr->second; } retval = found->find(time); if (time > retval->getTime() + dataInterval) { retval = (EphemerisLine *) NULL; } } else { retval = found->find(time); } } return retval; } /** * Allow for the explicit query of the data point interval for * your satellite. I've never seen this NOT be regular times, * but it does average. If you collect data points at weird-ass * intervals, you may need to compute a deviation. Or maybe this * information won't do you much good. Or both... */ double getDataInterval(std::string &satellite) { IntervalMap::iterator found = intervals.find(satellite); double retval = 0.0; if (found == intervals.end() || found->second == 0.0) { retval = calcInterval(satellite); } else { retval = found->second; } return retval; } /** * Put list of satellite names into a std::vector<std::string> */ void satelliteNames(std::vector<std::string> &names) { SatelliteMap::iterator it = satellites.begin(); while(it != satellites.end()) { names.push_back(it->first); it++; } } }; #endif
true
6028fbd2ea5f43cb180b571ebca1c494630f637b
C++
Bruteforceman/cp-submissions
/codeforces/1073/G.cpp
UTF-8
5,799
2.921875
3
[]
no_license
#include "bits/stdc++.h" using namespace std; #define next adfdf // Begins Suffix Arrays implementation // O(n log n) - Manber and Myers algorithm // Refer to "Suffix arrays: A new method for on-line txting searches", // by Udi Manber and Gene Myers //Usage: // Fill txt with the characters of the txting. // Call SuffixSort(n), where n is the length of the txting stored in txt. // That's it! //Output: // SA = The suffix array. Contains the n suffixes of txt sorted in lexicographical order. // Each suffix is represented as a single integer (the SAition of txt where it starts). // iSA = The inverse of the suffix array. iSA[i] = the index of the suffix txt[i..n) // in the SA array. (In other words, SA[i] = k <==> iSA[k] = i) // With this array, you can compare two suffixes in O(1): Suffix txt[i..n) is smaller // than txt[j..n) if and only if iSA[i] < iSA[j] const int MAX = 200010; char txt[MAX]; //input int iSA[MAX], SA[MAX]; //output int cnt[MAX], next[MAX]; //internal bool bh[MAX], b2h[MAX]; // Compares two suffixes according to their first characters bool smaller_first_char(int a, int b){ return txt[a] < txt[b]; } void suffixSort(int n){ //sort suffixes according to their first characters for (int i=0; i<n; ++i){ SA[i] = i; } sort(SA, SA + n, smaller_first_char); //{SA contains the list of suffixes sorted by their first character} for (int i=0; i<n; ++i){ bh[i] = i == 0 || txt[SA[i]] != txt[SA[i-1]]; b2h[i] = false; } for (int h = 1; h < n; h <<= 1){ //{bh[i] == false if the first h characters of SA[i-1] == the first h characters of SA[i]} int buckets = 0; for (int i=0, j; i < n; i = j){ j = i + 1; while (j < n && !bh[j]) j++; next[i] = j; buckets++; } if (buckets == n) break; // We are done! Lucky bastards! //{suffixes are separted in buckets containing txtings starting with the same h characters} for (int i = 0; i < n; i = next[i]){ cnt[i] = 0; for (int j = i; j < next[i]; ++j){ iSA[SA[j]] = i; } } cnt[iSA[n - h]]++; b2h[iSA[n - h]] = true; for (int i = 0; i < n; i = next[i]){ for (int j = i; j < next[i]; ++j){ int s = SA[j] - h; if (s >= 0){ int head = iSA[s]; iSA[s] = head + cnt[head]++; b2h[iSA[s]] = true; } } for (int j = i; j < next[i]; ++j){ int s = SA[j] - h; if (s >= 0 && b2h[iSA[s]]){ for (int k = iSA[s]+1; !bh[k] && b2h[k]; k++) b2h[k] = false; } } } for (int i=0; i<n; ++i){ SA[iSA[i]] = i; bh[i] |= b2h[i]; } } for (int i=0; i<n; ++i){ iSA[SA[i]] = i; } } // End of suffix array algorithm // Begin of the O(n) longest common prefix algorithm // Refer to "Linear-Time Longest-Common-Prefix Computation in Suffix // Arrays and Its Applications" by Toru Kasai, Gunho Lee, Hiroki // Arimura, Setsuo Arikawa, and Kunsoo Park. int lcp[MAX]; // lcp[i] = length of the longest common prefix of suffix SA[i] and suffix SA[i-1] // lcp[0] = 0 void getlcp(int n) { for (int i=0; i<n; ++i) iSA[SA[i]] = i; lcp[0] = 0; for (int i=0, h=0; i<n; ++i) { if (iSA[i] > 0) { int j = SA[iSA[i]-1]; while (i + h < n && j + h < n && txt[i+h] == txt[j+h]) h++; lcp[iSA[i]] = h; if (h > 0) h--; } } } // End of longest common prefixes algorithm const int logn = 17; int dp[18][200010]; int logx[200010]; int pos[200010]; int a[200010], b[200010]; int n; const int magic = 450; bool cmp(int p, int q) { return lcp[p] < lcp[q]; } int LCP(int p, int q) { if(p == q) return n - p; p = pos[p]; q = pos[q]; if(p > q) swap(p, q); p += 1; int b = logx[q - p + 1]; return lcp[min(dp[b][p], dp[b][q - (1 << b) + 1], cmp)]; } int rmq(int p, int q) { int b = logx[q - p + 1]; return min(dp[b][p], dp[b][q - (1 << b) + 1], cmp); } int l[200010], r[200010]; int lft[200010], ryt[200010]; int Pa[200010], Pb[200010]; inline int build(int b, int e) { if(b > e) return -1; int idx = rmq(b, e); l[idx] = b; r[idx] = e; lft[idx] = build(b, idx - 1); ryt[idx] = build(idx + 1, e); return idx; } inline int calcA(int i, int j) { i = max(0, i); return i == 0 ? Pa[j] : Pa[j] - Pa[i-1]; } inline int calcB(int i, int j) { i = max(0, i); return i == 0 ? Pb[j] : Pb[j] - Pb[i-1]; } // 6 4 0 2 5 1 3 // 0 1 3 1 0 2 0 int main() { int Q; scanf("%d %d", &n, &Q); scanf("%s", txt); suffixSort(n); getlcp(n); for(int i = 0; i < n; i++) { dp[0][i] = i; pos[SA[i]] = i; } logx[1] = 0; for(int i = 2; i <= n; i++) { logx[i] = logx[i >> 1] + 1; } for(int i = 1; i <= logn; i++) { for(int j = 0; j < n; j++) { int shift = (1 << (i-1)); if(j + shift < n) { dp[i][j] = min(dp[i - 1][j], dp[i - 1][j + shift], cmp); } } } int root = build(0, n-1); while(Q--) { int p, q; scanf("%d %d", &p, &q); for(int i = 0; i < p; i++) { scanf("%d", &a[i]); --a[i]; } for(int i = 0; i < q; i++) { scanf("%d", &b[i]); --b[i]; } long long ans = 0; if(p <= magic || q <= magic) { for(int i = 0; i < p; i++) { for(int j = 0; j < q; j++) { ans += LCP(a[i], b[j]); } } } else { for(int i = 0; i < n; i++) { Pa[i] = Pb[i] = 0; } for(int i = 0; i < p; i++) { Pa[pos[a[i]]] += 1; } for(int i = 0; i < q; i++) { Pb[pos[b[i]]] += 1; } for(int i = 1; i < n; i++) { Pa[i] += Pa[i - 1]; Pb[i] += Pb[i - 1]; } for(int now = 0; now < n; now++) { ans += 1LL * (n - SA[now]) * calcA(now, now) * calcB(now, now); ans += 1LL * lcp[now] * calcA(l[now] - 1, now - 1) * calcB(now, r[now]); ans += 1LL * lcp[now] * calcB(l[now] - 1, now - 1) * calcA(now, r[now]); } } printf("%lld\n", ans); } return 0; }
true
a3b441fd5dbb8ecdf6eda61b9724ff25ec7105d2
C++
xuau34/competitive-programming
/PCCA2017s/Day11/A.cpp
UTF-8
1,247
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int z[300005], N, M; // z[i] : 從s[i]開始的與從s[0]開始的匹配長度 inline void z_alg(char *s,int len,int *z){ int l=0,r=0; z[0]=len; for(int i=1;i<len;++i){ z[i]=i>r?0:(i-l+z[i-l]<z[l]?z[i-l]:r-i+1); while(i+z[i]<len&&s[i+z[i]]==s[z[i]])++z[i]; if(i+z[i]-1>r)r=i+z[i]-1,l=i; } } bool check(int l){ //printf("%d: ", l); for(int i = 0; i < N; ){ //printf("z[%d] = %d, ", i, z[i]); if(z[i] < l) return 0; else i += l; } for(int i = N + 1; i < N + M + 1; ){ //printf("z[%d] = %d, ", i, z[i]); if(z[i] < l) return 0; else i += l; } //printf("!!!!!\n"); return 1; } char A[100005], B[100005], c[300005]; int main(void){ int ans = 0; scanf("%s%s", A, B); N = strlen(A), M = strlen(B); for(int i = 0; i < N; ++i) c[i] = A[i]; c[N] = '@'; for(int i = N + 1, j = 0; i < N + M + 1; ++i, ++j) c[i] = B[j]; //printf("%s %s => %s: ", a, b, c); z_alg(c, N + M + 1, z); for(int i = 1; i <= N && i <= M; ++i){ //printf("A[%d ] = %c, B[%d] = %c\n", i, A[i], i, B[i]); if(A[i - 1] != B[i - 1]) break; if( check(i) ){ //printf("i = %d\n", i); ++ans; } //printf("\n"); } printf("%d\n", ans); }
true
6577a39bc1193a9acee7762767e07cf6e14e5d9e
C++
hideonatc/uva
/20161004/11344.cpp
UTF-8
2,790
2.84375
3
[]
no_license
#include<iostream> #include<cmath> using namespace std; bool by2(string n){ if((int(n[n.length()-1])-int('0'))%2==0) return 1; return false; } bool by3(string n){ int t=0; for(int i=0;i<n.length();i++){ t+=int(n[i])-int('0'); } if(t%3==0) return 1; return 0; } bool by4(string n){ int last=0; last+=int(n[n.length()-1])-int('0'); last+=(int(n[n.length()-2])-int('0'))*10; last+=(int(n[n.length()-3])-int('0'))*100; if(last%4==0) return 1; return 0; } bool by5(string n){ if(n[n.length()-1]=='0'||n[n.length()-1]=='5') return 1; return 0; } bool by6(string n){ if(by2(n)&&by3(n)) return 1; return 0; } int strtoint(string n){ int r=0; for(int i=0;i<n.length();i++){ r+=(int(n[i])-int('0'))*pow(10,n.length()-i-1); } return r; } bool by7(string n){ if(n.length()<=8){ if(strtoint(n)%7==0) return 1; else return 0; } else{ int l2=0,l=int(n[n.length()-1])-int('0'); l*=2; l2+=int(n[n.length()-2])-int('0')+10*(int(n[n.length()-3])-int('0')); l2-=l; string nw=""; for(int i=0;i<n.length()-3;i++) nw+=n[i]; if(l2<10) nw+='0'; else nw+=char(l2/10+int('0')); nw+=char(l2%10+int('0')); return by7(nw); } return 0; } bool by8(string n){ string s=""; if(n.length()<=4){ if(strtoint(n)%8==0) return 1; return 0; } else{ for(int i=3;i>0;i--) s+=n[n.length()-i]; return by8(s); } return 0; } bool by9(string n){ int t=0; for(int i=0;i<n.length();i++) t+=int(n[i])-int('0'); if(t%9==0) return 1; return 0; } bool by10(string n){ if(n[n.length()-1]=='0') return 1; return 0; } bool by11(string n){ int odd=0,even=0; if(n=="0") return 1; for(int i=0;i<n.length();i+=2) odd+=int(n[i])-int('0'); for(int i=1;i<n.length();i+=2) even+=int(n[i])-int('0'); if(abs(odd-even)%11==0) return 1; return 0; } bool by12(string n){ if(by3(n)&&by4(n)) return 1; return 0; } int main(){ int n; cin>>n; bool f=1; while(n--){ if(f)f=0; else cout<<endl; string m; cin>>m; int t; cin>>t; bool ans=1; for(int i=0;i<t;i++){ int c; cin>>c; if(c==2) if(!by2(m)){ ans=0; break; } if(c==3) if(!by3(m)){ ans=0; break; } if(c==4) if(!by4(m)){ ans=0; break; } if(c==5) if(!by5(m)){ ans=0; break; } if(c==6) if(!by6(m)){ ans=0; break; } if(c==7) if(!by7(m)){ ans=0; break; } if(c==8) if(!by8(m)){ ans=0; break; } if(c==9) if(!by9(m)){ ans=0; break; } if(c==10) if(!by10(m)){ ans=0; break; } if(c==11) if(!by11(m)){ ans=0; break; } if(c==12) if(!by12(m)){ ans=0; break; } } if(ans) cout<<m<<" - Wonderful."; else cout<<m<<" - Simple."; } }
true
0a7bfedb2b5fd9409aaa1fb4d7c9c73496be8803
C++
kyeongsoosoo/AlgoStudy
/DFS&BFS/1707myself.cpp
UTF-8
1,257
2.765625
3
[]
no_license
#include <iostream> #include <cstring> #include <vector> using namespace std; int K,V,E; const int MAX = 20000+1; vector<int> graph[MAX]; int p_color[MAX]; void color_dfs(int start, int color){ p_color[start] = color; for(int i=0; i<graph[start].size(); i++){ if(!p_color[graph[start][i]]) color_dfs(graph[start][i],3-color); } } bool canBipartite(){ for(int i=1; i<=V; i++){ for(int j=0; j<graph[i].size(); j++){ if(p_color[i] == p_color[graph[i][j]]) return false; } } return true; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> K; int from,to; for(int i=0; i<K; i++){ //초기화 for(int j=1; j<MAX; j++){ graph[j].clear(); } memset(p_color,0,sizeof(p_color)); cin >> V >> E; for(int j=0; j<E; j++){ cin >> from >> to; graph[from].push_back(to); graph[to].push_back(from); } for(int a=1; a<=V; a++){ if(!p_color[a]) color_dfs(a,1); } bool ans = canBipartite(); string ans_st =ans ? "YES" : "NO"; cout << ans_st << '\n'; } }
true
14077df2ba72ead899e77a3adc7dc3f905490b61
C++
lineCode/MACE-1
/include/MACE/Utility/DynamicLibrary.h
UTF-8
1,675
2.578125
3
[ "MIT" ]
permissive
/* The MIT License (MIT) Copyright (c) 2016 Liav Turkia 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. */ #pragma once #ifndef MACE__UTILITY_DYNAMIC_LIBRARY_H #define MACE__UTILITY_DYNAMIC_LIBRARY_H #include <MACE/Core/Constants.h> #include <string> namespace mc { class DynamicLibrary { public: static DynamicLibrary getRunningProcess(); ~DynamicLibrary(); DynamicLibrary(); DynamicLibrary(const std::string& path); DynamicLibrary(const char* path); void init(const std::string& path); void init(const char* path); void destroy(); void* getFunction(const std::string& name); void* getFunction(const char* name); void* operator[](const char* name) { return getFunction(name); } void* operator[](const std::string& name) { return this->operator[](name.c_str()); } bool isCreated() const; #if defined(MACE_WINAPI)&&defined(MACE_EXPOSE_WINAPI) void* getHandle() const { return dll; } #elif defined(MACE_POSIX)&&defined(MACE_EXPOSE_POSIX) void* getDescriptor() const { return dll; } #endif private: bool created = false; void* dll; };//DynamicLibrary }//mc #endif//MACE__UTILITY_DYNAMIC_LIBRARY_H
true
25538ccba7ad184361290dd3865a0d060ee48547
C++
SaberDa/LeetCode
/C++/325-maximumSizeSubarraySumEqualsK.cpp
UTF-8
727
3.03125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; int main() { vector<int> nums; nums.push_back(1); nums.push_back(0); nums.push_back(-1); int k = -1 ; if (nums.empty()) { return 0; } unordered_map<int, int> m; int ans = 0; int sum = 0; for (int i =0; i < nums.size(); i++) { sum += nums[i]; if (!m.count(sum)) { m[sum] = i; } // m[sum] = i; if (sum == k) { ans = max(ans, i+1); } if (m.count(sum-k)) { int length = i - m[sum-k]; ans = max(ans, length); } } cout << ans <<endl; return 0; }
true
55aed689cfc3e98bd2d393aa14ecdfa3c33ad26e
C++
fz-marchen/learn_data_structures
/2/learn_data_structures/4 队列/顺序存储/判断队列已满已空.cpp
UTF-8
767
3.078125
3
[]
no_license
#define MaxSize 10 #define ElemType int // 判断队列已满/已空 // 1 牺牲一个存储单元,用来判断队列是否满了 typedef struct1 { ElemType data[MaxSize]; int front, rear; } SqQueue1; void InitQueue(SqQueue1& Q) { Q.front = Q.rear = 0; } // 2 添加一个size,用来记录长度 // 初始化是赋值0,插入成功++,删除成功-- // 空: size=0 满: size=MaxSize typedef struct2 { ElemType data[MaxSize]; int front, rear; init size; } SqQueue2; // 3 添加一个tag,用来记录最近进行的是删除/插入 // 每次插入成功时,令tag=1。每次删除成功时,令tag=0 typedef struct3 { ElemType data[MaxSize]; int front, rear; init tag; } SqQueue3; int main() { return 0; }
true
6d0a790e3f4185d103e4a48542e00a37b98c9c56
C++
kstuedem/MuckyFoot-UrbanChaos
/fallen/DDEngine/Source/shape.cpp
UTF-8
35,904
2.515625
3
[ "MIT" ]
permissive
#include <MFStdLib.h> #include <DDLib.h> #include <math.h> #include "aeng.h" #include "..\headers\balloon.h" #include "poly.h" #include "shape.h" #include "night.h" #include "matrix.h" #include "..\editor\headers\prim.h" #include "mesh.h" #include "game.h" // How much to shift the W value up by to prevent Z-fighting. #define DC_SHADOW_Z_ADJUST 0.0001f // // Multiplies the two colours together. // ULONG SHAPE_colour_mult(ULONG c1, ULONG c2) { SLONG r1; SLONG g1; SLONG b1; SLONG r2; SLONG g2; SLONG b2; SLONG r; SLONG g; SLONG b; ULONG ans; r1 = (c1 >> 16) & 0xff; g1 = (c1 >> 8) & 0xff; b1 = (c1 >> 0) & 0xff; r2 = (c2 >> 16) & 0xff; g2 = (c2 >> 8) & 0xff; b2 = (c2 >> 0) & 0xff; r = r1 * r2 >> 8; g = g1 * g2 >> 8; b = b1 * b2 >> 8; ans = (r << 16) | (g << 8) | (b << 0); return ans; } void SHAPE_semisphere( SLONG x, SLONG y, SLONG z, SLONG dx, // Gives the and direction of the semi-sphere. SLONG dy, SLONG dz, SLONG radius, SLONG page, UBYTE red, UBYTE green, UBYTE blue) { SLONG i; SLONG j; SLONG px; SLONG py; SLONG pz; SLONG ax; SLONG ay; SLONG az; SLONG bx; SLONG by; SLONG bz; SLONG ox; SLONG oy; SLONG oz; SLONG c_num; SLONG c_points; SLONG c_red; SLONG c_green; SLONG c_blue; ULONG c_colour; SLONG angle; SLONG width; SLONG height; SLONG elevation; SLONG along_a; SLONG along_b; SLONG p1; SLONG p2; POLY_Point *pp; POLY_Point *tri [3]; POLY_Point *quad[4]; // // Construct two vectors orthogonal to (dx,dy,dz) and to eachother. // px = dy; py = dz; pz = dx; // // (px,py,pz) is not paralell to (dx,dy,dz) so (d x p) will be // orthogonal to (dx,dy,dz) // ax = dy*pz - dz*py >> 8; ay = dz*px - dx*pz >> 8; az = dx*py - dy*px >> 8; // // Create a vector parallel to both a and d. // bx = dy*az - dz*ay >> 8; by = dz*ax - dx*az >> 8; bz = dx*ay - dy*ax >> 8; // // Make the three vectors 'radius' long. // bx = bx * radius >> 8; by = by * radius >> 8; bz = bz * radius >> 8; ax = ax * radius >> 8; ay = ay * radius >> 8; az = az * radius >> 8; dx = dx * radius >> 8; dy = dy * radius >> 8; dz = dz * radius >> 8; // // Decide how detailed the semi-sphere should be. We need the number // of concentric circles and the number of points per circle. // c_points = 6; // Constants for now! c_num = 4; // // Build the points in the POLY_buffer. // ASSERT(WITHIN(c_points * c_num + 1, 0, POLY_BUFFER_SIZE)); for (i = 0; i < c_num; i++) { // // The width and height of this circle. // elevation = i * (512 / c_num); width = COS(elevation) >> 8; height = SIN(elevation) >> 8; // // The centre of the circle. // ox = x + (dx * height >> 8); oy = y + (dy * height >> 8); oz = z + (dz * height >> 8); // // The colour of the points along this circle. // c_red = red * height >> 8; c_green = green * height >> 8; c_blue = blue * height >> 8; c_colour = (c_red << 16) | (c_green << 8) | (c_blue << 0); for (j = 0; j < c_points; j++) { angle = j * (2048 / c_points); along_a = SIN(angle) * width >> 8; along_b = COS(angle) * width >> 8; px = ox; py = oy; pz = oz; px += ax * along_a >> 16; py += ay * along_a >> 16; pz += az * along_a >> 16; px += bx * along_b >> 16; py += by * along_b >> 16; pz += bz * along_b >> 16; // // Build the point. // pp = &POLY_buffer[i * c_points + j]; POLY_transform( (float) px, (float) py, (float) pz, pp); if (!pp->IsValid()) { // // Abandon the whole thing if one of the points is behind us! // return; } pp->colour = c_colour; pp->specular = 0; pp->u = 0.0F; pp->v = 0.0F; } } // // Finally the uppermost point. // px = x + dx; py = y + dy; pz = z + dz; pp = &POLY_buffer[c_num * c_points]; POLY_transform( (float) px, (float) py, (float) pz, pp); if (!pp->IsValid()) { // // Abandon the whole thing if one of the points is behind us! // return; } pp->colour = (red << 16) | (green << 8) | (blue << 0); pp->specular = 0; pp->u = 0.0F; pp->v = 0.0F; // // Now create the polygons. // for (i = 0; i < c_num - 1; i++) { if (i == c_num - 2) { // // Triangles connecting to the uppermost point. // tri[2] = &POLY_buffer[c_num * c_points]; // Constant. for (j = 0; j < c_points; j++) { p1 = j + 0; p2 = j + 1; if (p2 == c_points) {p2 = 0;} tri[0] = &POLY_buffer[(i + 0) * c_points + p1]; tri[1] = &POLY_buffer[(i + 0) * c_points + p2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, page, TRUE); } } } else { // // Quads between this level and the one above. // for (j = 0; j < c_points; j++) { p1 = j + 0; p2 = j + 1; if (p2 == c_points) {p2 = 0;} quad[0] = &POLY_buffer[(i + 0) * c_points + p1]; quad[1] = &POLY_buffer[(i + 0) * c_points + p2]; quad[2] = &POLY_buffer[(i + 1) * c_points + p1]; quad[3] = &POLY_buffer[(i + 1) * c_points + p2]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, page, TRUE); } } } } } void SHAPE_semisphere_textured( SLONG x, SLONG y, SLONG z, SLONG dx, // Gives the and direction of the semi-sphere. SLONG dy, SLONG dz, SLONG radius, float u_mid, float v_mid, float uv_radius, SLONG page, UBYTE red, UBYTE green, UBYTE blue) { SLONG i; SLONG j; SLONG px; SLONG py; SLONG pz; SLONG ax; SLONG ay; SLONG az; SLONG bx; SLONG by; SLONG bz; SLONG ox; SLONG oy; SLONG oz; SLONG c_num; SLONG c_points; SLONG c_red; SLONG c_green; SLONG c_blue; ULONG c_colour; float f_angle; float uv_width; SLONG angle; SLONG width; SLONG height; SLONG elevation; SLONG along_a; SLONG along_b; SLONG p1; SLONG p2; POLY_Point *pp; POLY_Point *tri [3]; POLY_Point *quad[4]; // // Construct two vectors orthogonal to (dx,dy,dz) and to eachother. // px = dy; py = dz; pz = dx; // // (px,py,pz) is not paralell to (dx,dy,dz) so (d x p) will be // orthogonal to (dx,dy,dz) // ax = dy*pz - dz*py >> 8; ay = dz*px - dx*pz >> 8; az = dx*py - dy*px >> 8; // // Create a vector parallel to both a and d. // bx = dy*az - dz*ay >> 8; by = dz*ax - dx*az >> 8; bz = dx*ay - dy*ax >> 8; // // Make the three vectors 'radius' long. // bx = bx * radius >> 8; by = by * radius >> 8; bz = bz * radius >> 8; ax = ax * radius >> 8; ay = ay * radius >> 8; az = az * radius >> 8; dx = dx * radius >> 8; dy = dy * radius >> 8; dz = dz * radius >> 8; // // Decide how detailed the semi-sphere should be. We need the number // of concentric circles and the number of points per circle. // c_points = 9; // Constants for now! c_num = 5; // // Build the points in the POLY_buffer. // ASSERT(WITHIN(c_points * c_num + 1, 0, POLY_BUFFER_SIZE)); for (i = 0; i < c_num; i++) { // // The width and height of this circle. // elevation = i * (512 / c_num); width = COS(elevation) >> 8; height = SIN(elevation) >> 8; // // The radius of the circle in uv space. // uv_width = float(width) * uv_radius * (1.0F / 256.0F); // // The centre of the circle. // ox = x + (dx * height >> 8); oy = y + (dy * height >> 8); oz = z + (dz * height >> 8); // // The colour of the points along this circle. // c_red = red * height >> 8; c_green = green * height >> 8; c_blue = blue * height >> 8; c_colour = (c_red << 16) | (c_green << 8) | (c_blue << 0); for (j = 0; j < c_points; j++) { angle = j * (2048 / c_points); f_angle = float(angle) * (2.0F * PI / 2048.0F); along_a = SIN(angle) * width >> 8; along_b = COS(angle) * width >> 8; px = ox; py = oy; pz = oz; px += ax * along_a >> 16; py += ay * along_a >> 16; pz += az * along_a >> 16; px += bx * along_b >> 16; py += by * along_b >> 16; pz += bz * along_b >> 16; // // Build the point. // pp = &POLY_buffer[i * c_points + j]; POLY_transform( (float) px, (float) py, (float) pz, pp); if (!pp->IsValid()) { // // Abandon the whole thing if one of the points is behind us! // return; } pp->colour = c_colour; pp->specular = 0; pp->u = (u_mid + sin(f_angle) * uv_width); pp->v = (v_mid + cos(f_angle) * uv_width); } } // // Finally the uppermost point. // px = x + dx; py = y + dy; pz = z + dz; pp = &POLY_buffer[c_num * c_points]; POLY_transform( (float) px, (float) py, (float) pz, pp); if (!pp->IsValid()) { // // Abandon the whole thing if one of the points is behind us! // return; } pp->colour = (red << 16) | (green << 8) | (blue << 0); pp->specular = 0; pp->u = u_mid; pp->v = v_mid; // // Now create the polygons. // for (i = 0; i < c_num; i++) { if (i == c_num - 1) { // // Triangles connecting to the uppermost point. // tri[2] = &POLY_buffer[c_num * c_points]; // Constant. for (j = 0; j < c_points; j++) { p1 = j + 0; p2 = j + 1; if (p2 == c_points) {p2 = 0;} tri[0] = &POLY_buffer[(i + 0) * c_points + p1]; tri[1] = &POLY_buffer[(i + 0) * c_points + p2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, page, TRUE); } } } else { // // Quads between this level and the one above. // for (j = 0; j < c_points; j++) { p1 = j + 0; p2 = j + 1; if (p2 == c_points) {p2 = 0;} quad[0] = &POLY_buffer[(i + 0) * c_points + p1]; quad[1] = &POLY_buffer[(i + 0) * c_points + p2]; quad[2] = &POLY_buffer[(i + 1) * c_points + p1]; quad[3] = &POLY_buffer[(i + 1) * c_points + p2]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, page, TRUE); } } } } } void SHAPE_sphere( SLONG ix, SLONG iy, SLONG iz, SLONG iradius, ULONG colour) { SLONG i; SLONG j; SLONG p1; SLONG p2; SLONG index1; SLONG index2; SLONG index3; SLONG index4; SLONG line1; SLONG line2; float px; float py; float pz; float pitch; float yaw; float sx = float(ix); float sy = float(iy); float sz = float(iz); float sradius = float(iradius); float vector[3]; POLY_Point pp_top; POLY_Point pp_bot; POLY_Point *pp; POLY_Point *quad[4]; POLY_Point *tri [3]; // // The top and bottom points. // POLY_transform(sx, sy + sradius, sz, &pp_top); POLY_transform(sx, sy - sradius, sz, &pp_bot); if (!pp_top.IsValid() || !pp_bot.IsValid()) { return; } NIGHT_get_d3d_colour( NIGHT_ambient_at_point(0, +256, 0), &pp_top.colour, &pp_top.specular); NIGHT_get_d3d_colour( NIGHT_ambient_at_point(0, -256, 0), &pp_bot.colour, &pp_bot.specular); pp_top.colour = SHAPE_colour_mult(pp_top.colour, colour); pp_bot.colour = SHAPE_colour_mult(pp_bot.colour, colour); // // All the points in the middle. // #define SHAPE_SPHERE_NUM_UPDOWN 8 #define SHAPE_SPHERE_NUM_AROUND 8 pp = &POLY_buffer[0]; pitch = PI / 2.0F; for (i = 1; i < SHAPE_SPHERE_NUM_UPDOWN; i++) { pitch -= PI / float(SHAPE_SPHERE_NUM_UPDOWN); yaw = 0.0F; for (j = 0; j < SHAPE_SPHERE_NUM_AROUND; j++) { MATRIX_vector( vector, yaw, pitch); px = sx + vector[0] * sradius; py = sy + vector[1] * sradius; pz = sz + vector[2] * sradius; ASSERT(WITHIN(pp, &POLY_buffer[0], &POLY_buffer[POLY_BUFFER_SIZE - 1])); POLY_transform( px, py, pz, pp); if (!pp->IsValid()) { return; } NIGHT_get_d3d_colour( NIGHT_ambient_at_point( SLONG(vector[0] * 256.0F), SLONG(vector[1] * 256.0F), SLONG(vector[2] * 256.0F)), &pp->colour, &pp->specular); pp->colour = SHAPE_colour_mult(pp->colour, colour); yaw += 2.0F * PI / float(SHAPE_SPHERE_NUM_AROUND); pp += 1; } } // // The triangles at the top and bottom. // for (i = 0; i < SHAPE_SPHERE_NUM_AROUND; i++) { p1 = i; p2 = i + 1; if (p2 == SHAPE_SPHERE_NUM_AROUND) {p2 = 0;} // // Top... // index1 = p1; index2 = p2; tri[0] = &pp_top; tri[1] = &POLY_buffer[index1]; tri[2] = &POLY_buffer[index2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, POLY_PAGE_COLOUR, FALSE); } // // Bottom... // index1 = p1 + SHAPE_SPHERE_NUM_AROUND * (SHAPE_SPHERE_NUM_UPDOWN - 2); index2 = p2 + SHAPE_SPHERE_NUM_AROUND * (SHAPE_SPHERE_NUM_UPDOWN - 2); tri[0] = &pp_bot; tri[1] = &POLY_buffer[index1]; tri[2] = &POLY_buffer[index2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, POLY_PAGE_COLOUR, FALSE); } } // // The quads in the middle. // for (i = 1; i < SHAPE_SPHERE_NUM_UPDOWN - 1; i++) { line1 = (i - 1) * SHAPE_SPHERE_NUM_AROUND; line2 = (i - 0) * SHAPE_SPHERE_NUM_AROUND; for (j = 0; j < SHAPE_SPHERE_NUM_AROUND; j++) { p1 = j; p2 = j + 1; if (p2 == SHAPE_SPHERE_NUM_AROUND) {p2 = 0;} quad[0] = &POLY_buffer[line1 + p1]; quad[1] = &POLY_buffer[line1 + p2]; quad[2] = &POLY_buffer[line2 + p1]; quad[3] = &POLY_buffer[line2 + p2]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_COLOUR, FALSE); } } } } void SHAPE_sparky_line( SLONG num_points, SLONG px[], SLONG py[], SLONG pz[], ULONG colour, float width) { ASSERT(WITHIN(num_points, 2, SHAPE_MAX_SPARKY_POINTS)); SLONG i; SLONG p1; SLONG p2; float dx; float dy; float len; float overlen; float size; float pnx; float pny; SLONG n1_valid; SLONG n2_valid; POLY_Point pp1; POLY_Point pp2; float nx[SHAPE_MAX_SPARKY_POINTS]; float ny[SHAPE_MAX_SPARKY_POINTS]; POLY_Point pp[SHAPE_MAX_SPARKY_POINTS]; POLY_Point *quad[4]; // // Transform all the points along the middle of the line. // for (i = 0; i < num_points; i++) { POLY_transform( float(px[i]), float(py[i]), float(pz[i]), &pp[i]); pp[i].colour = colour | 0xff000000; pp[i].specular = 0x00000000; pp[i].u = 0.0F; pp[i].v = 0.0F; } // // Work out the 2d point 'normals' // for (i = 0; i < num_points; i++) { if (pp[i].IsValid()) { if (i == 0 && width == 20.0F) { size = POLY_world_length_to_screen(width * 2.0F) * pp[i].Z; } else if (i == num_points - 1) { size = 2.0F; } else { size = POLY_world_length_to_screen(width) * pp[i].Z; } p1 = i - 1; p2 = i + 1; n1_valid = FALSE; n2_valid = FALSE; if (p1 > 0 && pp[p1].IsValid()) { dx = pp[i].X - pp[p1].X; dy = pp[i].Y - pp[p1].Y; // // Hmm... I guess that .414F is better than 0.500F // len = (fabsf(dx) > fabs(dy)) ? fabs(dx) + 0.414F * fabsf(dy) : fabsf(dy) + 0.414F * fabsf(dx); overlen = size / len; dx *= overlen; dy *= overlen; pnx = -dy; pny = dx; n1_valid = TRUE; } if (p2 < num_points && pp[p2].IsValid()) { dx = pp[p2].X - pp[i].X; dy = pp[p2].Y - pp[i].Y; // // Hmm... I guess that .414F is better than 0.500F // len = (fabsf(dx) > fabsf(dy)) ? fabsf(dx) + 0.414F * fabsf(dy) : fabsf(dy) + 0.414F * fabsf(dx); overlen = size / len; dx *= overlen; dy *= overlen; if (n1_valid) { pnx = (pnx + -dy) * 0.5F; pny = (pny + dx) * 0.5F; // // Normlise (pnx,pny); // len = (fabsf(pnx) > fabsf(pny)) ? fabsf(pnx) + 0.414F * fabsf(pny) : fabsf(pny) + 0.414F * fabsf(pnx); overlen = size / len; pnx *= overlen; pny *= overlen; } else { pnx = -dy; pny = dx; } n2_valid = TRUE; } nx[i] = pnx; ny[i] = pny; } } // // The quads... // for (i = 0; i < num_points - 1; i++) { if (pp[i + 0].IsValid() && pp[i + 1].IsValid()) { quad[0] = &pp[i + 0]; quad[1] = &pp[i + 1]; quad[2] = &pp1; quad[3] = &pp2; // // The two auxillary points. // pp1 = pp[i + 0]; pp2 = pp[i + 1]; if (!POLY_valid_quad(quad)) { continue; } pp1.X += nx[i + 0]; pp1.Y += ny[i + 0]; pp2.X += nx[i + 1]; pp2.Y += ny[i + 1]; UBYTE which=(GAME_TURN+i)&3; float which_v = (float)which*0.25f; pp[i + 0].colour = colour | 0xff000000; pp[i + 1].colour = colour | 0xff000000; /* pp1.colour = colour & 0x00ffffff; pp2.colour = colour & 0x00ffffff;*/ pp1.colour = colour | 0x00ffffff; pp2.colour = colour | 0x00ffffff; pp[i + 0].u = 0.0f; pp[i + 0].v = which_v; pp[i + 1].u = 2.0f; pp[i + 1].v = which_v; pp1.u = 0.0f; pp1.v = which_v+0.25f; pp2.u = 2.0f; pp2.v = which_v+0.25f; POLY_add_quad(quad, POLY_PAGE_LITE_BOLT, FALSE, true); /* pp1.X = pp[i + 0].X + (nx[i + 0] * 0.25F); pp1.Y = pp[i + 0].Y + (ny[i + 0] * 0.25F); pp2.X = pp[i + 1].X + (nx[i + 1] * 0.25F); pp2.Y = pp[i + 1].Y + (ny[i + 1] * 0.25F); pp[i + 0].colour = 0xffffffff; pp[i + 1].colour = 0xffffffff; pp1.colour = colour; pp2.colour = colour; POLY_add_quad(quad, POLY_PAGE_ADDITIVE, FALSE, true);*/ /* pp1.X = pp[i + 0].X - nx[i + 0]; pp1.Y = pp[i + 0].Y - ny[i + 0]; pp2.X = pp[i + 1].X - nx[i + 1]; pp2.Y = pp[i + 1].Y - ny[i + 1]; pp[i + 0].colour = colour | 0xff000000; pp[i + 1].colour = colour | 0xff000000; pp1.colour = colour & 0x00ffffff; pp2.colour = colour & 0x00ffffff; POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE, true); pp1.X = pp[i + 0].X - (nx[i + 0] * 0.25F); pp1.Y = pp[i + 0].Y - (ny[i + 0] * 0.25F); pp2.X = pp[i + 1].X - (nx[i + 1] * 0.25F); pp2.Y = pp[i + 1].Y - (ny[i + 1] * 0.25F); pp[i + 0].colour = 0xffffffff; pp[i + 1].colour = 0xffffffff; pp1.colour = colour; pp2.colour = colour; POLY_add_quad(quad, POLY_PAGE_ADDITIVE, FALSE, true);*/ } } } void SHAPE_glitter( SLONG x1, SLONG y1, SLONG z1, SLONG x2, SLONG y2, SLONG z2, ULONG colour) { float dpx; float dpy; float dx = float(x2 - x1); float dy = float(y2 - y1); float dz = float(z2 - z1); float adpx; float adpy; float len; float mul; float size; POLY_Point pp1; POLY_Point pp2; POLY_Point top; POLY_Point bot; POLY_Point *tri[3]; POLY_transform( float(x1), float(y1), float(z1), &pp1); if (!pp1.IsValid()) { return; } POLY_transform( float(x2 + dx), float(y2 + dy), float(z2 + dz), &pp2); if (!pp2.IsValid()) { return; } dpx = pp1.X - pp2.X; dpy = pp1.Y - pp2.Y; adpx = fabs(dpx); adpy = fabs(dpy); if (adpx > adpy) { len = adpx + (adpy * 0.5F); } else { len = adpy + (adpx * 0.5F); } size = POLY_world_length_to_screen(30.0F) * pp1.Z; mul = size / len; dpx *= mul; dpy *= mul; top = pp1; bot = pp1; top.X += dpy; top.Y -= dpx; bot.X -= dpy; bot.Y += dpx; tri[0] = &top; tri[1] = &bot; tri[2] = &pp2; if (POLY_valid_triangle(tri)) { pp2.colour = colour; pp2.specular = 0xff000000; pp2.u = 1.0F; pp2.v = 0.5F; top.colour = colour; top.specular = 0xff000000; top.u = 0.0F; top.v = 0.0F; bot.colour = colour; bot.specular = 0xff000000; bot.u = 0.0F; bot.v = 1.0F; POLY_add_triangle(tri, POLY_PAGE_SPARKLE, FALSE, true); } } // // Sets uv coordinates depending on the frame counter. // void SHAPE_tripwire_uvs( UWORD counter, float *u1, float *v1, float *u2, float *v2, float *u3, float *v3, float *u4, float *v4) { float v = float(counter & 0x7fff) * (1.0F / (128.0F * 256.0F)); if (counter & 0x8000) { *u1 = 0.6F; *u2 = 0.6F; *u3 = 0.9F; *u4 = 0.9F; } else { *u1 = 0.1F; *u2 = 0.1F; *u3 = 0.4F; *u4 = 0.4F; } *v1 = *v3 = v; *v2 = *v4 = v + (16.0F / 256.0F); } void SHAPE_tripwire( SLONG ix1, SLONG iy1, SLONG iz1, SLONG ix2, SLONG iy2, SLONG iz2, SLONG width, ULONG colour, UWORD counter, UBYTE along) { float x1 = float(ix1); float y1 = float(iy1); float z1 = float(iz1); float x2 = float(ix2); float y2 = float(iy2); float z2 = float(iz2); POLY_Point pp[4]; POLY_Point *quad[4]; float dx = x2 - x1; float dy = y2 - y1; float dz = z2 - z1; if (along == 0) { return; } else if (along != 255) { float falong = float(along) * (1.0F / 256.0F); // // Change (x2,y2,z2). // x2 = x1 + dx * falong; y2 = y1 + dy * falong; z2 = z1 + dz * falong; } float len; if (fabs(dx) > fabs(dz)) { len = fabsf(dx) + 0.5F * fabsf(dz); } else { len = fabsf(dz) + 0.5F * fabsf(dx); } float overlen = float(width) / len; dx *= overlen; dz *= overlen; quad[0] = &pp[0]; quad[1] = &pp[1]; quad[2] = &pp[2]; quad[3] = &pp[3]; // // Transform the four point. If any of them fail abandon // the whole line. // POLY_transform( x1 + dz, y1, z1 - dx, &pp[0]); if (!pp[0].MaybeValid()) { return; } POLY_transform( x1 - dz, y1, z1 + dx, &pp[1]); if (!pp[1].MaybeValid()) { return; } POLY_transform( x2 + dz, y2, z2 - dx, &pp[2]); if (!pp[2].MaybeValid()) { return; } POLY_transform( x2 - dz, y2, z2 + dx, &pp[3]); if (!pp[3].MaybeValid()) { return; } if (POLY_valid_quad(quad)) { // // Draw two overlapping lines. // pp[0].colour = colour; pp[1].colour = colour; pp[2].colour = colour; pp[3].colour = colour; pp[0].specular = 0x00000000; pp[1].specular = 0x00000000; pp[2].specular = 0x00000000; pp[3].specular = 0x00000000; SHAPE_tripwire_uvs( counter, &pp[0].u, &pp[0].v, &pp[1].u, &pp[1].v, &pp[2].u, &pp[2].v, &pp[3].u, &pp[3].v); POLY_add_quad(quad, POLY_PAGE_FOG, FALSE); SHAPE_tripwire_uvs( 0x2345 - counter, &pp[0].u, &pp[0].v, &pp[1].u, &pp[1].v, &pp[2].u, &pp[2].v, &pp[3].u, &pp[3].v); POLY_add_quad(quad, POLY_PAGE_FOG, FALSE); } } void SHAPE_waterfall( SLONG map_x, SLONG map_z, SLONG dx, SLONG dz, SLONG top, SLONG bot) { SLONG i; SLONG y; ULONG colour; SLONG mid_x = (map_x << 8) + 0x80; SLONG mid_z = (map_z << 8) + 0x80; SLONG px1 = mid_x + (dx << 7) + (-dz << 7); SLONG pz1 = mid_z + (dz << 7) + (+dx << 7); SLONG px2 = mid_x + (dx << 7) + (+dz << 7); SLONG pz2 = mid_z + (dz << 7) + (-dx << 7); POLY_Point pp [6]; POLY_Point *quad[4]; for (i = 0; i < 3; i++) { switch(i) { case 0: y = top; colour = 0xaa4488aa; break; case 1: y = top - 0x10; colour = 0x884488aa; break; case 2: y = top - 0x40; colour = 0x004488aa; break; default: ASSERT(0); break; } POLY_transform( float(px1), float(y), float(pz1), &pp[0 + i]); pp[0 + i].colour = colour; pp[0 + i].specular = 0xff000000; pp[0 + i].u = 0.0F; pp[0 + i].v = 0.0F; POLY_transform( float(px2), float(y), float(pz2), &pp[3 + i]); pp[3 + i].colour = colour; pp[3 + i].specular = 0xff000000; pp[3 + i].u = 0.0F; pp[3 + i].v = 0.0F; px1 -= dx << 4; pz1 -= dz << 4; px2 -= dx << 4; pz2 -= dz << 4; } quad[0] = &pp[3]; quad[1] = &pp[0]; quad[2] = &pp[4]; quad[3] = &pp[1]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_SEWATER, TRUE); } quad[0] = &pp[4]; quad[1] = &pp[1]; quad[2] = &pp[5]; quad[3] = &pp[2]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_SEWATER, TRUE); } } void SHAPE_droplet( SLONG x, SLONG y, SLONG z, SLONG dx, SLONG dy, SLONG dz, ULONG colour, SLONG page) { float dpx; float dpy; float adpx; float adpy; float len; float mul; float size; POLY_Point pp1; POLY_Point pp2; POLY_Point top; POLY_Point bot; POLY_Point *tri[3]; POLY_flush_local_rot(); POLY_transform( float(x), float(y), float(z), &pp1); if (!pp1.IsValid()) { return; } POLY_transform( float(x - dx), float(y - dy), float(z - dz), &pp2); if (!pp2.IsValid()) { return; } dpx = pp1.X - pp2.X; dpy = pp1.Y - pp2.Y; adpx = fabs(dpx); adpy = fabs(dpy); if (adpx > adpy) { len = adpx + (adpy * 0.5F); } else { len = adpy + (adpx * 0.5F); } size = POLY_world_length_to_screen(10.0F) * pp1.Z; mul = size / len; dpx *= mul; dpy *= mul; top = pp1; bot = pp1; top.X += dpy; top.Y -= dpx; bot.X -= dpy; bot.Y += dpx; tri[0] = &top; tri[1] = &bot; tri[2] = &pp2; if (POLY_valid_triangle(tri)) { pp2.colour = colour; pp2.specular = 0xff000000; pp2.u = 1.0F; pp2.v = 0.5F; top.colour = colour; top.specular = 0xff000000; top.u = 0.0F; top.v = 0.0F; bot.colour = colour; bot.specular = 0xff000000; bot.u = 0.0F; bot.v = 1.0F; POLY_add_triangle(tri, page, FALSE, TRUE); } } // // Draws a cylindrical shadow // void SHADOW_cylindrical_shadow(float px, float py, float pz, float radius, float length) { POLY_Point pp [6]; POLY_Point *quad[4]; POLY_transform( px - radius * -0.707F, py + 2.0F, pz - radius * -0.707F, &pp[0], TRUE); if (!pp[0].IsValid()) { return; } POLY_transform( px - radius * +0.707F, py + 2.0F, pz - radius * +0.707F, &pp[1]); if (!pp[1].IsValid()) { return; } POLY_transform( px - radius * -0.707F + length * +0.707F, py + 2.0F, pz - radius * -0.707F + length * -0.707F, &pp[2]); if (!pp[2].IsValid()) { return; } POLY_transform( px - radius * +0.707F + length * +0.707F, py + 2.0F, pz - radius * +0.707F + length * -0.707F, &pp[3]); if (!pp[3].IsValid()) { return; } quad[0] = &pp[0]; quad[1] = &pp[1]; quad[2] = &pp[2]; quad[3] = &pp[3]; if (POLY_valid_quad(quad)) { pp[0].colour = 0x88000000; pp[0].specular = 0xff000000; pp[0].u = 0.0F; pp[0].v = 0.0F; pp[0].Z += DC_SHADOW_Z_ADJUST; pp[1].colour = 0x88000000; pp[1].specular = 0xff000000; pp[1].u = 0.0F; pp[1].v = 0.0F; pp[1].Z += DC_SHADOW_Z_ADJUST; pp[2].colour = 0x00000000; pp[2].specular = 0xff000000; pp[2].u = 0.0F; pp[2].v = 0.0F; pp[2].Z += DC_SHADOW_Z_ADJUST; pp[3].colour = 0x00000000; pp[3].specular = 0xff000000; pp[3].u = 0.0F; pp[3].v = 0.0F; pp[3].Z += DC_SHADOW_Z_ADJUST; POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE); } } void SHAPE_prim_shadow(OB_Info *oi) { POLY_Point pp [6]; POLY_Point *quad[4]; #define SHAPE_PRIM_SHADOW_RADIUS (24.0F) #define SHAPE_PRIM_SHADOW_LENGTH (128.0F) float px = float(oi->x); float py = float(oi->y); float pz = float(oi->z); SLONG i; PrimInfo *pi; float angle; float sin_yaw; float cos_yaw; float matrix[4]; float wx; float wz; struct { float x; float z; } world[4]; UBYTE order[3]; POLY_Point *pp_upto; switch(prim_get_shadow_type(oi->prim)) { case PRIM_SHADOW_NONE: return; case PRIM_SHADOW_CYLINDER: // // Circular shadow. // SHADOW_cylindrical_shadow( px, py, pz, SHAPE_PRIM_SHADOW_RADIUS, SHAPE_PRIM_SHADOW_LENGTH); break; case PRIM_SHADOW_FULLBOX: // // A shadow of shadow under the prim. // pi = get_prim_info(oi->prim); angle = float(-oi->yaw) * (2.0F * PI / 2048.0F); sin_yaw = sin(angle); cos_yaw = cos(angle); matrix[0] = cos_yaw; matrix[1] = -sin_yaw; matrix[2] = sin_yaw; matrix[3] = cos_yaw; for (i = 0; i < 4; i++) { wx = (i & 0x1) ? float(pi->maxx) : float(pi->minx); wz = (i & 0x2) ? float(pi->maxz) : float(pi->minz); world[i].x = wx * matrix[0] + wz * matrix[1]; world[i].z = wx * matrix[2] + wz * matrix[3]; world[i].x += px; world[i].z += pz; POLY_transform( world[i].x, py, world[i].z, &pp[i], TRUE); if (!pp[i].MaybeValid()) { // // Abandon the prim shadow. // return; } pp[i].colour = 0x88000000; pp[i].specular = 0xff000000; pp[i].u = 0.0F; pp[i].v = 0.0F; pp[i].Z += DC_SHADOW_Z_ADJUST; } quad[0] = &pp[0]; quad[1] = &pp[1]; quad[2] = &pp[2]; quad[3] = &pp[3]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE); } // // FALLTHROUGH! // case PRIM_SHADOW_BOXEDGE: // // Bounding box shadow. // if (prim_get_shadow_type(oi->prim) == PRIM_SHADOW_FULLBOX) { // // We've fallen through from the case: above... // no need to work out this stuff. // } else { pi = get_prim_info(oi->prim); angle = float(-oi->yaw) * (2.0F * PI / 2048.0F); sin_yaw = sin(angle); cos_yaw = cos(angle); matrix[0] = cos_yaw; matrix[1] = -sin_yaw; matrix[2] = sin_yaw; matrix[3] = cos_yaw; for (i = 0; i < 4; i++) { wx = (i & 0x1) ? float(pi->maxx) : float(pi->minx); wz = (i & 0x2) ? float(pi->maxz) : float(pi->minz); world[i].x = wx * matrix[0] + wz * matrix[1]; world[i].z = wx * matrix[2] + wz * matrix[3]; world[i].x += px; world[i].z += pz; } } switch(((oi->yaw + 256) & 2047) >> 9) { case 0: order[0] = 0; order[1] = 1; order[2] = 3; break; case 1: order[0] = 1; order[1] = 3; order[2] = 2; break; case 2: order[0] = 3; order[1] = 2; order[2] = 0; break; case 3: order[0] = 2; order[1] = 0; order[2] = 1; break; default: ASSERT(0); break; } pp_upto = &pp[0]; for (i = 0; i < 3; i++) { POLY_transform( world[order[i]].x, py + 2.0F, world[order[i]].z, pp_upto, TRUE); if (!pp_upto->MaybeValid()) { return; } pp_upto->colour = 0x88000000; pp_upto->specular = 0xff000000; pp_upto->u = 0.0F; pp_upto->v = 0.0F; pp_upto->Z += DC_SHADOW_Z_ADJUST; pp_upto++; POLY_transform( world[order[i]].x + SHAPE_PRIM_SHADOW_LENGTH * +0.707F, py + 2.0F, world[order[i]].z + SHAPE_PRIM_SHADOW_LENGTH * -0.707F, pp_upto); if (!pp_upto->MaybeValid()) { return; } pp_upto->colour = 0x00000000; pp_upto->specular = 0xff000000; pp_upto->u = 0.0F; pp_upto->v = 0.0F; pp_upto->Z += DC_SHADOW_Z_ADJUST; pp_upto++; } quad[0] = &pp[0]; quad[1] = &pp[1]; quad[2] = &pp[2]; quad[3] = &pp[3]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE); } quad[0] = &pp[2]; quad[1] = &pp[3]; quad[2] = &pp[4]; quad[3] = &pp[5]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE); } break; case PRIM_SHADOW_FOURLEGS: // // Find the four corner points of the prim. // pi = get_prim_info(oi->prim); angle = float(-oi->yaw) * (2.0F * PI / 2048.0F); sin_yaw = sin(angle); cos_yaw = cos(angle); matrix[0] = cos_yaw; matrix[1] = -sin_yaw; matrix[2] = sin_yaw; matrix[3] = cos_yaw; for (i = 0; i < 4; i++) { wx = (i & 0x1) ? float(pi->maxx) : float(pi->minx); wz = (i & 0x2) ? float(pi->maxz) : float(pi->minz); world[i].x = wx * matrix[0] + wz * matrix[1]; world[i].z = wx * matrix[2] + wz * matrix[3]; world[i].x += px; world[i].z += pz; } // // Draw a circular shadow at each corner. // for (i = 0; i < 4; i++) { SHADOW_cylindrical_shadow( world[i].x, py, world[i].z, SHAPE_PRIM_SHADOW_RADIUS, SHAPE_PRIM_SHADOW_LENGTH); } break; default: ASSERT(0); break; } } void SHAPE_alpha_sphere( SLONG ix, SLONG iy, SLONG iz, SLONG iradius, ULONG colour, ULONG alpha) { SLONG i; SLONG j; SLONG p1; SLONG p2; SLONG index1; SLONG index2; SLONG index3; SLONG index4; SLONG line1; SLONG line2; float px; float py; float pz; float pitch; float yaw; float sx = float(ix); float sy = float(iy); float sz = float(iz); float sradius = float(iradius); float vector[3]; POLY_Point pp_top; POLY_Point pp_bot; POLY_Point *pp; POLY_Point *quad[4]; POLY_Point *tri [3]; // // The top and bottom points. // POLY_transform(sx, sy + sradius, sz, &pp_top); POLY_transform(sx, sy - sradius, sz, &pp_bot); if (!pp_top.MaybeValid() || !pp_bot.MaybeValid()) { return; } NIGHT_get_d3d_colour( NIGHT_ambient_at_point(0, +256, 0), &pp_top.colour, &pp_top.specular); NIGHT_get_d3d_colour( NIGHT_ambient_at_point(0, -256, 0), &pp_bot.colour, &pp_bot.specular); pp_top.colour = SHAPE_colour_mult(pp_top.colour, colour); pp_bot.colour = SHAPE_colour_mult(pp_bot.colour, colour); pp_top.colour |= alpha; pp_bot.colour |= alpha; // // All the points in the middle. // #define SHAPE_SPHERE_NUM_UPDOWN 8 #define SHAPE_SPHERE_NUM_AROUND 8 pp = &POLY_buffer[0]; pitch = PI / 2.0F; for (i = 1; i < SHAPE_SPHERE_NUM_UPDOWN; i++) { pitch -= PI / float(SHAPE_SPHERE_NUM_UPDOWN); yaw = 0.0F; for (j = 0; j < SHAPE_SPHERE_NUM_AROUND; j++) { MATRIX_vector( vector, yaw, pitch); px = sx + vector[0] * sradius; py = sy + vector[1] * sradius; pz = sz + vector[2] * sradius; ASSERT(WITHIN(pp, &POLY_buffer[0], &POLY_buffer[POLY_BUFFER_SIZE - 1])); POLY_transform( px, py, pz, pp); if (!pp->MaybeValid()) { return; } NIGHT_get_d3d_colour( NIGHT_ambient_at_point( SLONG(vector[0] * 256.0F), SLONG(vector[1] * 256.0F), SLONG(vector[2] * 256.0F)), &pp->colour, &pp->specular); pp->colour = SHAPE_colour_mult(pp->colour, colour); pp->colour |= alpha; yaw += 2.0F * PI / float(SHAPE_SPHERE_NUM_AROUND); pp += 1; } } // // The triangles at the top and bottom. // for (i = 0; i < SHAPE_SPHERE_NUM_AROUND; i++) { p1 = i; p2 = i + 1; if (p2 == SHAPE_SPHERE_NUM_AROUND) {p2 = 0;} // // Top... // index1 = p1; index2 = p2; tri[0] = &pp_top; tri[1] = &POLY_buffer[index1]; tri[2] = &POLY_buffer[index2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, POLY_PAGE_ALPHA, FALSE); } // // Bottom... // index1 = p1 + SHAPE_SPHERE_NUM_AROUND * (SHAPE_SPHERE_NUM_UPDOWN - 2); index2 = p2 + SHAPE_SPHERE_NUM_AROUND * (SHAPE_SPHERE_NUM_UPDOWN - 2); tri[0] = &pp_bot; tri[1] = &POLY_buffer[index1]; tri[2] = &POLY_buffer[index2]; if (POLY_valid_triangle(tri)) { POLY_add_triangle(tri, POLY_PAGE_ALPHA, FALSE); } } // // The quads in the middle. // for (i = 1; i < SHAPE_SPHERE_NUM_UPDOWN - 1; i++) { line1 = (i - 1) * SHAPE_SPHERE_NUM_AROUND; line2 = (i - 0) * SHAPE_SPHERE_NUM_AROUND; for (j = 0; j < SHAPE_SPHERE_NUM_AROUND; j++) { p1 = j; p2 = j + 1; if (p2 == SHAPE_SPHERE_NUM_AROUND) {p2 = 0;} quad[0] = &POLY_buffer[line1 + p1]; quad[1] = &POLY_buffer[line1 + p2]; quad[2] = &POLY_buffer[line2 + p1]; quad[3] = &POLY_buffer[line2 + p2]; if (POLY_valid_quad(quad)) { POLY_add_quad(quad, POLY_PAGE_ALPHA, FALSE); } } } } #ifndef TARGET_DC ULONG SHAPE_balloon_colour; void SHAPE_draw_balloon(SLONG balloon) { SLONG i; POLY_Point pp[BALLOON_POINTS_PER_BALLOON]; ASSERT(WITHIN(balloon, 1, BALLOON_balloon_upto - 1)); BALLOON_Balloon *bb; bb = &BALLOON_balloon[balloon]; for (i = 0; i < BALLOON_POINTS_PER_BALLOON - 1; i++) { AENG_world_line( bb->bp[i + 0].x >> 8, bb->bp[i + 0].y >> 8, bb->bp[i + 0].z >> 8, 4, 0x558845, bb->bp[i + 1].x >> 8, bb->bp[i + 1].y >> 8, bb->bp[i + 1].z >> 8, 4, 0x558845, FALSE); } static ULONG balloon_colours[4] = {0xffff0000, 0xffffff00, 0xff00ff00, 0xff0000ff}; SHAPE_balloon_colour = balloon_colours[balloon & 3]; MESH_draw_poly( PRIM_OBJ_BALLOON, bb->bp[BALLOON_POINTS_PER_BALLOON - 1].x >> 8, bb->bp[BALLOON_POINTS_PER_BALLOON - 1].y >> 8, bb->bp[BALLOON_POINTS_PER_BALLOON - 1].z >> 8, bb->yaw, bb->pitch, 0, NULL,0xff); } #endif
true
09ad8812339a0f60220f6fea46876c7f5e8928a1
C++
JEERU/ADS
/Trees/TREAP/Treap_C/main.cpp
UTF-8
1,495
3.765625
4
[]
no_license
#include "Treap.h" ctree nullnode, root; /* * Main Contains Menu */ int main() { srand ((unsigned int)time (NULL)); int num; char choice; bool flag = false; initialize(); while (1) { printf("\n---------------------"); printf("\n Operations on Treap"); printf("\n---------------------\n"); printf("\n1. Insert Element;"); printf("\n2. Delete Element;"); printf("\n3. Inorder Traversal;"); printf("\n4. Display in Order;"); printf("\n5. Quit.\n"); printf("\nEnter your choice: "); scanf(" %c", &choice); switch (choice) { case '1': printf("Enter the number to be inserted: "); scanf("%d", &num); insert(root, num); break; case '2': if (root == nullnode) { printf("Tree is empty, nothing to delete"); continue; } printf("Enter the number to be deleted: "); scanf("%d", &num); if (find(root, num)) flag = true; else printf("Element not found.\n"); remove(root, num); if (!find(root, num) && flag) printf("Element Deleted.\n"); break; case '3': if (root == nullnode) { printf("Tree is empty, insert element first.\n"); continue; } printf("Inorder Traversal:\n"); inorder(root); printf("\n"); break; case '4': if (root == nullnode) { printf("Tree is empty.\n"); continue; } printf("Display Treap:\n"); display(root, 1); printf("\n"); break; case '5': exit(1); break; default: printf("Wrong choice!\n"); } } }
true
f0813ea23cfe2e0366e8f4f9201935a0de2deede
C++
pyrovski/scalasca
/cube-3.0/src/GUI-qt/display/FontWidget.cpp
UTF-8
3,055
2.65625
3
[]
no_license
/**************************************************************************** ** SCALASCA http://www.scalasca.org/ ** ***************************************************************************** ** Copyright (c) 1998-2013 ** ** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre ** ** ** ** See the file COPYRIGHT in the package base directory for details ** ****************************************************************************/ #include "FontWidget.h" #include <QLabel> #include <QVBoxLayout> #include <QDialogButtonBox> #include <QPushButton> FontWidget::FontWidget(QWidget* parent, QFont font, int spacing) : QDialog(parent){ setWindowTitle("Font settings"); this->font = font; this->spacing = spacing; QVBoxLayout * layout = new QVBoxLayout(); setLayout(layout); QLabel * fontLabel = new QLabel(this); fontLabel->setText("Font: "); layout->addWidget(fontLabel); fontCombo = new QFontComboBox(this); layout->addWidget(fontCombo); fontCombo->setCurrentFont(font); QLabel * sizeLabel = new QLabel(this); sizeLabel->setText("Size [pt]: "); layout->addWidget(sizeLabel); sizeSpin = new QSpinBox(this); sizeSpin->setRange(1,30); sizeSpin->setSingleStep(1); sizeSpin->setValue(font.pointSize()); layout->addWidget(sizeSpin); QLabel * spaceLabel = new QLabel(this); spaceLabel->setText("Line spacing [pixel]: "); layout->addWidget(spaceLabel); spaceSpin = new QSpinBox(this); spaceSpin->setRange(0,30); spaceSpin->setSingleStep(1); spaceSpin->setValue(spacing); layout->addWidget(spaceSpin); QDialogButtonBox * buttonBox = new QDialogButtonBox(); buttonBox->addButton(QDialogButtonBox::Ok); QPushButton* applyButton = buttonBox->addButton(QDialogButtonBox::Apply); buttonBox->addButton(QDialogButtonBox::Cancel); connect(buttonBox, SIGNAL(accepted()), this, SLOT(onOk())); connect(applyButton,SIGNAL(clicked()), this, SLOT(onApply())); connect(buttonBox, SIGNAL(rejected()), this, SLOT(onCancel())); layout->addWidget(buttonBox); setWhatsThis("Opens a dialog to specify the font, the font size (in pt), and the line spacing for the tree displays. The \"Ok\" button applies the settings to the display and closes the dialog, the \"Apply\" button applies the settings to the display, and \"Cancel\" cancels all changes since the dialog was opened (even if \"Apply\" was pressed in between) and closes the dialog."); } QFont FontWidget::getFont(){ QFont font = fontCombo->currentFont(); font.setPointSize(sizeSpin->value()); return font; } int FontWidget::getSpacing(){ return spaceSpin->value(); } void FontWidget::onOk(){ onApply(); accept(); } void FontWidget::onApply(){ emit apply(this); } void FontWidget::onCancel(){ fontCombo->setCurrentFont(font); sizeSpin->setValue(font.pointSize()); spaceSpin->setValue(spacing); onApply(); reject(); }
true
23ecea7ac8c5fdd018c51efb46196258424c78f0
C++
SillyPasty/ybserver
/dao/connection_pool.h
UTF-8
1,267
2.59375
3
[]
no_license
#ifndef CONNECTION_POOL_H #define CONNECTION_POOL_H #include <stdio.h> #include <list> #include <mysql/mysql.h> #include <error.h> #include <string.h> #include <iostream> #include <string> #include "../locker/locker.h" #include "../log/logger.h" using namespace std; class connection_pool { public: MYSQL *get_connection(); //获取数据库连接 bool release_connection(MYSQL *conn); //释放连接 int cur_free_conn(); //获取连接 void destory_pool(); //销毁所有连接 //单例模式 static connection_pool *GetInstance(); void init(string url, string user, string passWord, string db_name, int port, int max_conn, int close_log); private: connection_pool(); ~connection_pool(); int max_conn; //最大连接数 int cur_conn; //当前已使用的连接数 int free_conn; //当前空闲的连接数 locker lock; list<MYSQL *> conn_list; //连接池 cond reserve; public: string m_url; //主机地址 int m_port; //数据库端口号 string m_user; //登陆数据库用户名 string m_password; //登陆数据库密码 string m_db_name; //使用数据库名 int m_close_log; //日志开关 }; #endif
true
47bd8d4d9c2e298cdd9e9839dfb839997f5fc3b3
C++
neesarg-yb/N-gene
/Engine/Code/Engine/Renderer/SpriteAnimation.hpp
UTF-8
1,434
2.71875
3
[]
no_license
#pragma once #include "Engine/Renderer/SpriteSheet.hpp" enum SpriteAnimMode { SPRITE_ANIM_MODE_PLAY_TO_END, // Play from time=0 to durationSeconds, then finish SPRITE_ANIM_MODE_LOOPING, // Play from time=0 to end then repeat (never finish) NUM_SPRITE_ANIM_MODES }; class SpriteAnimation { public: // Data const SpriteSheet& m_spriteSheet; SpriteAnimMode m_playbackMode; float m_durationSeconds; int m_startSpriteIndex; int m_endSpriteIndex; // State bool m_isPlaying; bool m_isFinished; float m_elapsedSeconds; SpriteAnimation( const SpriteSheet& spriteSheet, float durationSeconds, SpriteAnimMode playbackMode, int startSpriteIndex, int endSpriteIndex ); void Update( float deltaSeconds ); AABB2 GetCurrentTexCoords() const; // Based on the current elapsed time const Texture& GetTexture() const; void Pause(); // Starts unpaused (playing) by default void Resume(); // Resume after pausing void Reset(); // Rewinds to time 0 and starts (re)playing bool IsFinished() const; bool IsPlaying() const; float GetDurationSeconds() const; float GetSecondsElapsed() const; float GetSecondsRemaining() const; float GetFractionElapsed() const; float GetFractionRemaining() const; void SetSecondsElapsed( float secondsElapsed ); // Jump to specific time void SetFractionElapsed( float fractionElapsed ); // e.g. 0.33f for one-third in };
true
e065b84eb912b7fa601b7a8ac37edda13ae76b27
C++
zhiyb/Y1Labs
/P5 Digital Objects/14_9/main.cpp
UTF-8
566
2.796875
3
[]
no_license
#include <iostream> #include "balrog.h" #include "cyberdemon.h" #include "elf.h" #include "human.h" #ifdef __linux__ #include <unistd.h> #define msleep(ms) usleep(ms * 1000) #else #include <windows.h> #define msleep(ms) Sleep(ms) #endif using namespace std; int main() { Balrog barlog; Cyberdemon cyberdemon; Elf elf; Human human; for (int i = 0; i < 60; i++) { cout << "****** New round! (" << i << ") ******" << endl; barlog.getDamage(); cyberdemon.getDamage(); elf.getDamage(); human.getDamage(); msleep(1000); cout << endl; } return 0; }
true
0d5b39e1d0be09a5fb0bd4849c2ee46dbc94f326
C++
zymov/leetcode
/cpp/172_Factorial_Trailing_Zeroes.cpp
UTF-8
711
3.796875
4
[]
no_license
/* Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explanation: 3! = 6, no trailing zero. Example 2: Input: 5 Output: 1 Explanation: 5! = 120, one trailing zero. Note: Your solution should be in logarithmic time complexity. */ #include <iostream> #include <cmath> using namespace std; class Solution { public: int trailingZeroes(int n) { int count = 0; int k = 0; while(n > 0) { k = n / 5; count += k; n = k; } return count; } }; int main() { Solution sol; cout << sol.trailingZeroes(625) << endl; return 0; } /* */
true
330d20768c82c00379e1450ade8d42531d225002
C++
ldematte/beppe
/src/Camera.h
UTF-8
1,639
2.625
3
[ "BSD-3-Clause" ]
permissive
/*******************************************************************\ * Bezier Patch Editor --- Camera * * * * Una semplice interfaccia per gestire una telecamera. * * La telecamera puo' muoversi avanti ed indietro, lateralmente e * * puo' ruotare su se stessa. * * Agisce sulla matrice MODELVIEW utilizzando la funzione gluLookAt * \*******************************************************************/ #ifndef CAMERA_H #define CAMERA_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "common.h" #include "Mtxlib.h" class Camera { public: Camera(); virtual ~Camera(); // Setta in maniera diretta la posizione della telecamera void PositionCamera(float positionX, float positionY, float positionZ, float viewX, float viewY, float viewZ, float upVectorX, float upVectorY, float upVectorZ); // Ruota la vista void RotateView(float X, float Y, float Z); // muove la telecamera lateralmente void StrafeCamera(float speed); // muove la telecamera avanti e indietro void MoveCamera(float speed); // cattura lo spostamento del mouse, traducendolo in uno // spostamento della telecamera (Rotate) void HandleMouse(int deltaX, int deltaY); // muove la telecamera verticalmente void FlyCamera(float speed); public: // i vettori per la posizione, saranno dati // in input alla gluLookAt vector3 vPosition; vector3 vView; vector3 vUp; }; #endif //CAMERA_H
true
e063cab171fb54c8e67c01c981bafbbc5277909f
C++
donaldvenus/Revolution
/empire.cpp
UTF-8
437
3.21875
3
[]
no_license
#include "empire.h" /* Create the empire. */ Empire::Empire() { } /* Adjust troop deployment and return true if valid move. */ bool Empire::adjustTroopValues(City& src, City& dest, int num) { if (num > src.getNumEmpire()) { printf("Invalid number of troops, attempted to move %d but only %d exist.\n", num, src.getNumEmpire()); return false; } src.setNumEmpire(src.getNumEmpire() - num); dest.setNewEmpire(num); return true; }
true
3e54a7dade6ee951f8fb5624eb2da49b97d251e3
C++
gyanesh94/Coding
/practice/question5.cpp
UTF-8
2,228
4.28125
4
[]
no_license
/* Created Linked list is 1->2->3->4->5->6->7->8->9 */ #include <iostream> using namespace std; typedef struct node { int data; struct node *next; } node; void addNode(node **head, int data) { node *newNode = new node; node *temp = *head; newNode->data = data; newNode->next = NULL; if (temp == NULL) { *head = newNode; return; } while (temp->next) { temp = temp->next; } temp->next = newNode; } void printLinkedList(node *head) { while (head) { cout << head->data << " "; head = head->next; } } // O(n^2) node *reverseLinkedListRecursiveLong(node *head) { if (head == NULL) { return NULL; } node *tempNode, *result; if (head->next != NULL) { result = reverseLinkedListRecursiveLong(head->next); } else { return head; } tempNode = result; while (tempNode->next != NULL) { tempNode = tempNode->next; } tempNode->next = head; head->next = NULL; return result; } // O(n) void reverseLinkedListRecursiveShort(node **head) { if (*head == NULL || (*head)->next == NULL) { return; } node *first = (*head); node *rest = first->next; reverseLinkedListRecursiveShort(&rest); first->next->next = first; first->next = NULL; *head = rest; return; } // O(n) node *reverseLinkedListIterative(node *head) { if (head == NULL) { return NULL; } if (head->next == NULL) { return head; } node *prev, *curr, *next; prev = NULL; curr = head; while (curr){ next = curr->next; curr->next = prev; prev = curr; curr = next; } head = prev; return head; } int main() { node *head = NULL; addNode(&head, 1); addNode(&head, 2); addNode(&head, 3); addNode(&head, 4); addNode(&head, 5); addNode(&head, 6); addNode(&head, 7); addNode(&head, 8); addNode(&head, 9); cout << "Actual Linked List\n"; printLinkedList(head); // head = reverseLinkedListIterative(head); reverseLinkedListRecursiveShort(&head); cout << "\nReversed Linked List\n"; printLinkedList(head); return 0; }
true
638c7040eecaf61141dad944918d3eab0203f954
C++
yeomko22/TIL
/algorithm/codility/prime/perimeter.cpp
UTF-8
391
2.890625
3
[]
no_license
#include <math.h> #include <iostream> using namespace std; int solution(int N) { int sqrtNum = sqrt(N); if (sqrtNum * sqrtNum ==N) { return 4 * sqrtNum; } int answer = 0; while (1) { if (N % sqrtNum != 0) { sqrtNum--; continue; } answer = 2 * ((N / sqrtNum) + sqrtNum); break; } return answer; }
true
6d2345a49707c9e28654186f604d041e1ef19097
C++
tectronics/Synthesizer
/my/my/Operation.cpp
UTF-8
3,172
3.140625
3
[]
no_license
#include "StdAfx.h" #include "Operation.h" Operation::Operation() { op = NONE; p = SINGLE; } Operation::Operation(OP op) { this->op = op; p = SINGLE; switch (op) { case PLUS: case MINUS: case R_MINUS: p = PLUS_MUNUS; break; case MUL: case DIV: case R_DIV: p =MUL_DIV; break; } } double Operation::calculate(double num1, double num2) const { double result = 0; switch (op) { case PLUS: result = num1 + num2; break; case MINUS: result = num1 - num2; break; case R_MINUS: result = num2 - num1; break; case MUL: result = num1 * num2; break; case DIV: result = num1 / num2; break; case R_DIV: result = num2 / num1; break; } return result; } double Operation::inverse1(double result, double num2) const { double num1 = 0; switch (op) { case PLUS: num1 = result - num2; break; case MINUS: num1 = result + num2; break; case R_MINUS: num1 = num2 - result; break; case MUL: num1 = result / num2; break; case DIV: num1 = result * num2; break; case R_DIV: num1 = num2 / result; break; } return num1; } double Operation::inverse2(double result, double num1) const { double num2 = 0; switch (op) { case PLUS: num2 = result - num1; break; case MINUS: num2 = num1 - result; break; case R_MINUS: num2 = num1 + result; break; case MUL: num2 = result / num1; break; case DIV: num2 = num1 / result; break; case R_DIV: num2 = num1 * result; break; } return num2; } OP Operation::getOp() const { return op; } PRIORITY Operation::getPriority() const { return p; } string Operation::toString(const string &num1, PRIORITY p1, const string &num2, PRIORITY p2) const { string result, left, right; switch (op) { case PLUS: left = num1; right = num2; if (p1 < PLUS_MUNUS) { left = "(" + left + ")"; } if (p2 <= PLUS_MUNUS) { right = "(" + right + ")"; } result = left + " + " + right; break; case MINUS: left = num1; right = num2; if (p1 < PLUS_MUNUS) { left = "(" + left + ")"; } if (p2 <= PLUS_MUNUS) { right = "(" + right + ")"; } result = left + " - " + right; break; case R_MINUS: left = num2; right = num1; if (p2 < PLUS_MUNUS) { left = "(" + left + ")"; } if (p1 <= PLUS_MUNUS) { right = "(" + right + ")"; } result = left + " - " + right; break; case MUL: left = num1; right = num2; if (p1 < MUL_DIV) { left = "(" + left + ")"; } if (p2 <= MUL_DIV) { right = "(" + right + ")"; } result = left + " * " + right; break; case DIV: left = num1; right = num2; if (p1 < MUL_DIV) { left = "(" + left + ")"; } if (p2 <= MUL_DIV) { right = "(" + right + ")"; } result = left + " / " + right; break; case R_DIV: left = num2; right = num1; if (p2 < MUL_DIV) { left = "(" + left + ")"; } if (p1 <= MUL_DIV) { right = "(" + right + ")"; } result = left + " / " + right; break; } return result; }
true
93e33465726d4b37883317dfc822180b337f622c
C++
lukeflima/Page-replacement-algorithm-fault-counter-
/faultCounter.cpp
UTF-8
3,264
3.328125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <fstream> #include <sstream> std::stringstream output; int main(int argc, char const *argv[]) { ///Ler entrada std::fstream f("input", std::ifstream::in); size_t memSize; f >> memSize; std::vector<int> mem(memSize,0); int temp; std::vector<int> pages; while(!f.eof()) { f >> temp; pages.push_back(temp); } //#################################################################### //FIFO int falts = 0, memIndex = 0; for(auto page: pages){ if(std::find(mem.begin(), mem.end(), page) == mem.end()){ // se não estiver na memoria ++falts; mem[memIndex] = page; memIndex = (memIndex + 1) % memSize; } } std::cout << "FIFO " << falts << '\n'; output << "FIFO " << falts << '\n'; //#################################################################### //OTM for(auto &v: mem) v = 0; // zerando memória falts = memIndex = 0; for(int i = 0; i < pages.size(); i++){ if(std::find(mem.begin(), mem.end(), pages[i]) == mem.end()){ // se não estiver na memoria ++falts; if(!mem[memIndex]){ // se estiver lugar vazio na memória mem[memIndex] = pages[i]; memIndex = (memIndex + 1) % memSize; }else{ std::vector<int> delay; std::copy(mem.begin(), mem.end(), std::back_inserter(delay)); std::for_each(delay.begin(), delay.end(), [&pages,i](auto &p){ p = std::distance(pages.begin() + i, std::find(pages.begin() + i, pages.end(), p)); // calcula o tempo }); //calcula o máximos dos tempo e substitui a página mem[std::distance(delay.begin(), std::max_element(delay.begin(), delay.end()) )] = pages[i]; } } } std::cout << "OTM " << falts << '\n'; output << "OTM " << falts << '\n'; //################################################################### //LRU for(auto &v: mem) v = 0; // zerando memória falts = memIndex = 0; for(int i = 0; i < pages.size(); i++){ if(std::find(mem.begin(), mem.end(), pages[i]) == mem.end()){ // se não estiver na memoria ++falts; if(!mem[memIndex]){ mem[memIndex] = pages[i]; memIndex = (memIndex + 1) % memSize; }else{ std::vector<int> delay; std::copy(mem.begin(), mem.end(), std::back_inserter(delay)); std::for_each(delay.begin(), delay.end(), [&pages,i](auto &p){ // calcula o tempo p = std::distance(pages.rbegin() + (pages.size() - i - 1), std::find(pages.rbegin() + (pages.size() - i - 1), pages.rend(), p)); }); //calcula o máximos dos tempo e substitui a página mem[std::distance(delay.begin(), std::max_element(delay.begin(), delay.end()) )] = pages[i]; } } } std::cout << "LRU " << falts << '\n'; output << "LRU " << falts << '\n'; std::ofstream out("output", std::ofstream::out); out << output.str(); return 0; }
true
69785ecd84289c41e38e4660ea962796754d00d4
C++
Supersil/FamilyTreeRemade
/family.h
UTF-8
712
2.6875
3
[]
no_license
#ifndef FAMILY_H #define FAMILY_H #include <QObject> #include <QMap> #include <QList> #include "person.h" #include "treeleaf.h" class Family : public QObject { Q_OBJECT public: Family(QObject *parent = nullptr); void addPerson(Person * nPers) { personList.append(nPers);} void addLeaf(Person * pers, TreeLeaf * leaf) { leavesMap.insert(pers,leaf);} int size() { return personList.size();} Person * getPerson(int num) { return personList[num];} TreeLeaf * getLeaf(Person * pers) { return leavesMap[pers];} TreeLeaf * getLeaf(int num) { return leavesMap[personList[num]];} signals: public slots: private: QList<Person *> personList; QMap<Person *, TreeLeaf *> leavesMap; }; #endif // FAMILY_H
true
f9dd503c2483920c59f788bfeb2067cb7930e1df
C++
kkdas088/sorting_network
/src/algo_sorting.cpp
UTF-8
8,349
2.703125
3
[]
no_license
#include "algo_unpacked.h" /* * algo_unpacked interface exposes fully unpacked input and output link data. * This version assumes use of 10G 8b10b links, and thus providing 192bits/BX/link. * * !!! N.B.: Do NOT use the first bytes of link_in/link_out (i.e. link_in/link_out[].range(7,0) * as this portion is reserved for transmission of 8b10b input/output link alignment markers. * * The remaining 184 bits are available for algorithm use. * * !!! N.B. 2: make sure to assign every bit of link_out[] data. First byte should be assigned zero. */ void capture_objects(ap_uint<192> link_in[N_CH_IN], ap_uint<10> *array_objects){ //Test insertions - Arrays //#pragma HLS inline off int index=0; ap_uint<192> obj; for (int lnk = 0; lnk<N_CH_IN; lnk++) { //#pragma HLS UNROLL index=lnk*5; obj = link_in[lnk]; array_objects[index]= obj.range(41,32) ; array_objects[index+1]= obj.range(73,64) ; array_objects[index+2]= obj.range(105,96) ; array_objects[index+3]= obj.range(137,128) ; array_objects[index+4]= obj.range(169,160) ; } } void swap(ap_uint<10> *x, ap_uint<10> *y) { ap_uint<10> temp; temp = *x; *x = *y; *y = temp; } void even_odd_sort_4_256(ap_uint<10> array_objects[NUM_OBJECTS]){ static int N=4; int numstage=1;int len_comp=0; // From 256 objects,take a 4 for sorting. for (int obj_num= 0; obj_num<NUM_OBJECTS-1; obj_num++) { //#pragma HLS UNROLL factor=4 //1st stage comparators if (obj_num %2 ==0){ if ((array_objects[obj_num]) > (array_objects[obj_num+1])) { swap(&array_objects[obj_num], &array_objects[obj_num+1]); } } } //------------------------------------------------------------------------------------------- // Merging for 2*2 inputs- Make odd even for (int obj_num= 0; obj_num<NUM_OBJECTS; obj_num=obj_num+4) { //#pragma HLS UNROLL factor=8 //Number of stages for(int i=0;i<numstage;i++){ //check the elements len_comp=((N/2)-(2*i)); for (int j=2*i;j<N/2;j++){ if ((array_objects[obj_num+j]) > (array_objects[obj_num+j+len_comp])) { swap(&array_objects[obj_num+j], &array_objects[obj_num+j+len_comp]); } } } } //------------------------------------------------------------------------------------------- for(int i=0;i<NUM_OBJECTS-1;i=i+4){ for (int j = i+1;j<i+N-1;j++){ if(j%2!=0){ if ((array_objects[j]) > (array_objects[j+1])) { swap(&array_objects[j], &array_objects[j+1]); } } } } } void even_odd_merge_8(ap_uint<10> array_objects[NUM_OBJECTS]){ int N=8; int numstage=((N-4)/4)+1; int len_comp=0; //chg for (int obj_num= 0; obj_num<NUM_OBJECTS; obj_num=obj_num+8) { //#pragma HLS UNROLL factor=8 //Number of stages for(int i=0;i<numstage;i++){ //check the elements len_comp=((N/2)-(2*i)); for (int j=2*i;j<N/2;j++){ if ((array_objects[obj_num+j]) > (array_objects[obj_num+j+len_comp])) { swap(&array_objects[obj_num+j], &array_objects[obj_num+j+len_comp]); } } } } //------------------------------------------------------------------------------------------- for(int i=0;i<NUM_OBJECTS-1;i=i+8){ for (int j = i+1;j<i+N-1;j++){ if(j%2!=0){ if ((array_objects[j]) > (array_objects[j+1])) { swap(&array_objects[j], &array_objects[j+1]); } } } } } void even_odd_merge_16 (ap_uint<10> array_objects[NUM_OBJECTS]){ int N=16; int numstage=((N-4)/4)+1; int len_comp=0; //chg for (int obj_num= 0; obj_num<NUM_OBJECTS; obj_num=obj_num+16) { //#pragma HLS UNROLL factor=8 //Number of stages for(int i=0;i<numstage;i++){ //check the elements len_comp=((N/2)-(2*i)); for (int j=2*i;j<N/2;j++){ if ((array_objects[obj_num+j]) > (array_objects[obj_num+j+len_comp])) { swap(&array_objects[obj_num+j], &array_objects[obj_num+j+len_comp]); } } } } //------------------------------------------------------------------------------------------ for(int i=0;i<NUM_OBJECTS-1;i=i+16){ for (int j = i+1;j<i+N-1;j++){ if(j%2!=0){ if ((array_objects[j]) > (array_objects[j+1])) { swap(&array_objects[j], &array_objects[j+1]); } } } } } void even_odd_merge_32 (ap_uint<10> array_objects[NUM_OBJECTS]){ int N=32; int numstage=((N-4)/4)+1; int len_comp=0; //chg for (int obj_num= 0; obj_num<NUM_OBJECTS; obj_num=obj_num+32) { //#pragma HLS UNROLL factor=8 //Number of stages for(int i=0;i<numstage;i++){ //check the elements len_comp=((N/2)-(2*i)); for (int j=2*i;j<N/2;j++){ if ((array_objects[obj_num+j]) > (array_objects[obj_num+j+len_comp])) { swap(&array_objects[obj_num+j], &array_objects[obj_num+j+len_comp]); } } } } //----------------------------------------------------------------------------------------- for(int i=0;i<NUM_OBJECTS-1;i=i+32){ for (int j = i+1;j<i+N-1;j++){ if(j%2!=0){ if ((array_objects[j]) > (array_objects[j+1])) { swap(&array_objects[j], &array_objects[j+1]); } } } } } void even_odd_merge_64 (ap_uint<10> array_objects[NUM_OBJECTS]){ int N=64; int numstage=((N-4)/4)+1; int len_comp=0; //chg for (int obj_num= 0; obj_num<NUM_OBJECTS; obj_num=obj_num+64) { //#pragma HLS UNROLL factor=8 //Number of stages for(int i=0;i<numstage;i++){ //check the elements len_comp=((N/2)-(2*i)); for (int j=2*i;j<N/2;j++){ if ((array_objects[obj_num+j]) > (array_objects[obj_num+j+len_comp])) { swap(&array_objects[obj_num+j], &array_objects[obj_num+j+len_comp]); } } } } //------------------------------------------------------------------------------------------- //Final compare for(int i=0;i<NUM_OBJECTS-1;i=i+64){ for (int j = i+1;j<i+N-1;j++){ if(j%2!=0){ if ((array_objects[j]) > (array_objects[j+1])) { swap(&array_objects[j], &array_objects[j+1]); } } } } } void connect_output(ap_uint<10> *array_objects, ap_uint<192> link_out[0]){ int index=0; //#pragma HLS inline off //#pragma HLS ARRAY_RESHAPE variable=link_out block factor=48 dim=0 for (int lnk = 0; lnk < N_CH_OUT; lnk++) { index = lnk*5; link_out[lnk].range(7,0) = 0; link_out[lnk].range(41,32) =array_objects[index]; link_out[lnk].range(73,64) =array_objects[index+1]; link_out[lnk].range(105,96) =array_objects[index+2]; link_out[lnk].range(137,128) =array_objects[index+3]; link_out[lnk].range(169,160) = array_objects[index+4]; } } void algo_unpacked(ap_uint<192> link_in[N_CH_IN], ap_uint<192> link_out[N_CH_OUT]) { //Test insertions - Array ap_uint<10> array_objects[NUM_OBJECTS]; // !!! Retain these 4 #pragma directives below in your algo_unpacked implementation !!! #pragma HLS ARRAY_PARTITION variable=link_in complete dim=0 //#pragma HLS ARRAY_PARTITION variable=link_out complete dim=0 #pragma HLS ARRAY_PARTITION variable=link_out complete dim=0 #pragma HLS ARRAY_PARTITION variable=array_objects complete dim=0 #pragma HLS PIPELINE II=3 #pragma HLS INTERFACE ap_ctrl_hs port=return // null algo specific pragma: avoid fully combinatorial algo by specifying min latency // otherwise algorithm clock input (ap_clk) gets optimized away #pragma HLS latency min=3 //Capture all objects from the link capture_objects(&link_in[0],&array_objects[0]); even_odd_sort_4_256(&array_objects[0]); even_odd_merge_8(&array_objects[0]); even_odd_merge_16(&array_objects[0]); even_odd_merge_32(&array_objects[0]); even_odd_merge_64 (&array_objects[0]); //void even_odd_merge_128 (int array_objects[NUM_OBJECTS]); //void even_odd_merge_256 (int array_objects[NUM_OBJECTS]); connect_output(&array_objects[0],&link_out[0]); }
true
a2e89a6a8bd5e512303875cbcd57c8554e5ed431
C++
smj2mm/OS
/homework2/homework2_4.cpp
UTF-8
2,210
3.28125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <iostream> using namespace std; /* GLOBALS */ struct threadStuff { int index; }; pthread_barrier_t barrier; int numCompetitors; int* numbers; threadStuff* threadStructs; void* getMax(void *arg1) { threadStuff* info = (threadStuff*) arg1; int index = info->index; int r; for(r=1; r<numCompetitors; r*=2) { //*(info->x) = numbers[index]; //*(info_>y) = numbers[index+r]; numbers[index] = (numbers[index]>=numbers[index+r]) ? numbers[index] : numbers[index+r]; index *=2; //if(index >= numCompetitors) //pthread_exit(NULL); pthread_barrier_wait(&barrier); } } int fightToTheDeath(int numCompetitors, int** nums) { int i; int r; int* numbers = *nums; for(r=1; r<numCompetitors; r*=2) { //cout << "r value: " << r << "\n"; for(i=0; i<numCompetitors-r; i++) { numbers[i] = max(numbers[i], numbers[i+r]); cout << "WINNER: numbers[" << i << "] = " << numbers[i] << "\n"; } } return numbers[0]; } int fightToTheDeathThreads(int numCompetitors) { pthread_t tids[numCompetitors]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_barrierattr_t barrier_attr; pthread_barrierattr_init(&barrier_attr); int numThreads = numCompetitors / 2; int i; pthread_barrier_init(&barrier, &barrier_attr, numThreads); for(i=0; i<numThreads; i++) { threadStructs[i].index = i*2; cout << "i is: " << i << " threadStructs[i].index = " << i*2 << "\n"; pthread_create(&tids[i], &attr, getMax, (void*)&threadStructs[i]); } return numbers[0]; } int main() { numbers = new int[16384]; threadStructs = new threadStuff[8192]; int i=0; string s = ""; while(getline(cin, s)) { //numbers[i] = new int; if(s.empty()) { break; } numbers[i] = atoi(s.c_str()); i++; } int numCompetitors = i; // TEST : CREATE 1 THREAD TO COMPARE 1st 2 ELEMENTS int numShowdowns = 0; //int maximum = fightToTheDeath(numCompetitors, &numbers); int maximum = fightToTheDeathThreads(numCompetitors); //int maximum = fightToTheDeath(numCompetitors, &numbers); //cout << "MAX IS:" << *numbers[0] << "\n"; cout << "MAXIMUM IS: "<< maximum << "\n"; return 0; }
true
34ddf06f87ab606b5a73e25ad77e7f5e0a5a6558
C++
zhanggyang/-offer
/连续最大子数组和/main.cpp
UTF-8
521
3.171875
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { vector<int> Dp(array.size(),0); Dp[0] = array[0]; int Max = array[0]; for(int i=1;i<array.size();i++){ if(Dp[i-1]<=0) Dp[i] = array[i]; else Dp[i] = Dp[i-1]+array[i]; Max =max(Dp[i],Max); } return Max; } }; int main() { cout << "Hello world!" << endl; return 0; }
true
f7418ec1b9aaa91de6db5541736cbe01ecfbddb9
C++
cognimancer/infinidungeon
/infinidungeon/InstanceClass.h
UTF-8
1,451
3
3
[]
no_license
/*-------------------------------------------------------------------------------------------------- Created by Alberto Bobadilla (labigm@rit.edu) in 2013 --------------------------------------------------------------------------------------------------*/ #ifndef _INSTANCECLASS_H #define _INSTANCECLASS_H #include "ModelClass.h" class InstanceClass { MaterialManagerClass* m_pMaterialManager; String m_sName; //Example Variable std::vector<ShapeClass> m_vShape; //Vector of shapes glm::mat4 m_mModel; //GLM Model Matrix public: InstanceClass(void); //Constructor InstanceClass(const InstanceClass& other); //Copy Constructor InstanceClass& operator=(const InstanceClass& other); //Copy Assignment Operator void Release(void); //Release the fields in the class ~InstanceClass(void); //Destructor void InstanceModel(ModelClass& a_Model); //Create an Instance of a previously loaded model void Render(void);//Render all groups void Swap(InstanceClass& other); //Swaps Content with other Instance class //Accessors void SetModelMatrix(const glm::mat4 a_mModel = glm::mat4(1.0f)); glm::mat4& GetModelMatrix(void); __declspec(property(put = SetModelMatrix, get = GetModelMatrix)) glm::mat4 ModelMatrix; void SetName(String a_sName); //Sets Variable String GetName(void);//Gets Variable __declspec(property(get = GetName, put = SetName)) String Name; //Property private: void Init(void); //Initializes the variables }; #endif //_INSTANCECLASS_H
true
7ba1030692b5c1fa57378af3a79866ce3738f843
C++
zie87/sdl2_cxx
/src/test/video/rect_test.cxx
UTF-8
3,291
2.953125
3
[]
no_license
/** * @file rect_test.cxx * @Author: zie87 * @Date: 2017-10-19 04:50:55 * @Last Modified by: zie87 * @Last Modified time: 2017-10-19 05:04:38 * * @brief Brief description of file. * * Detailed description of file. **/ #include <sdl2_cxx/video/rect.hxx> #include <catch.hpp> TEST_CASE("check rectangle wrapper", "[video]") { SECTION("rectangle construction test") { // default values sdl2::rect r1; REQUIRE(0 == r1.x()); REQUIRE(0 == r1.y()); REQUIRE(0 == r1.width()); REQUIRE(0 == r1.height()); // value construction sdl2::rect r2(1, 2, 3, 4); REQUIRE(1 == r2.x()); REQUIRE(2 == r2.y()); REQUIRE(3 == r2.width()); REQUIRE(4 == r2.height()); // copy construction sdl2::rect r3(r2); REQUIRE(1 == r3.x()); REQUIRE(2 == r3.y()); REQUIRE(3 == r3.width()); REQUIRE(4 == r3.height()); } SECTION("rectangle assignment test") { sdl2::rect r1(1, 2, 3, 4); sdl2::rect r2(5, 6, 7, 8); REQUIRE(r1 != r2); // assignment operator r1 = r2; REQUIRE(r1 == r2); // element setter r1.x() = 10; r1.y() = 20; r1.width() = 30; r1.height() = 40; REQUIRE(10 == r1.x()); REQUIRE(20 == r1.y()); REQUIRE(30 == r1.width()); REQUIRE(40 == r1.height()); r1.set_coordinates(-1, -2); r1.set_dimension(-3, -4); r2.set(-1, -2, -3, -4); REQUIRE(r1 == r2); } SECTION("rectangle area test") { sdl2::rect r1; REQUIRE(r1.empty()); sdl2::point p1(10, 10); REQUIRE(!r1.point_in(p1)); r1.set_dimension(100, 100); REQUIRE(!r1.empty()); REQUIRE(r1.point_in(p1)); sdl2::rect r2(200, 90, 50, 50); REQUIRE(!r1.has_intersection(r2)); sdl2::rect r3 = r1.intersection_rectangle(r2); REQUIRE(r3.empty()); r2.x() = 0; REQUIRE(r1.has_intersection(r2)); r3 = r1.intersection_rectangle(r2); REQUIRE(0 == r3.x()); REQUIRE(90 == r3.y()); REQUIRE(50 == r3.width()); REQUIRE(10 == r3.height()); r3 = r1.union_rectangel(r2); REQUIRE(0 == r3.x()); REQUIRE(0 == r3.y()); REQUIRE(100 == r3.width()); REQUIRE(140 == r3.height()); int x1 = 10; int y1 = 10; int x2 = 200; int y2 = 200; REQUIRE(r1.intersection_line(x1, y1, x2, y2)); REQUIRE(x2 == y2); REQUIRE(99 == x2); sdl2::point start(0, 200); sdl2::point end(400, 0); REQUIRE(!r1.intersection_line(start, end)); end.x() = 150; REQUIRE(r1.intersection_line(start, end)); REQUIRE(75 == start.x()); REQUIRE(99 == start.y()); REQUIRE(99 == end.x()); REQUIRE(68 == end.y()); } SECTION("rectangle converter test") { SDL_Rect sdl_r{-1, -2, -3, 4}; sdl2::rect r1(-1, -2, -3, 4); // raw pointer access SDL_Rect* sdl_r1 = sdl2::to_sdl_type(r1); REQUIRE(SDL_TRUE == SDL_RectEquals(&sdl_r, sdl_r1)); sdl_r1->x = 1; sdl_r1->y = 2; sdl_r1->w = 3; sdl_r1->h = 4; REQUIRE(1 == r1.x()); REQUIRE(2 == r1.y()); REQUIRE(3 == r1.width()); REQUIRE(4 == r1.height()); // const access to raw pointer const sdl2::rect r2(r1); const SDL_Rect* sdl_r2 = sdl2::to_sdl_type(r2); REQUIRE(1 == sdl_r2->x); REQUIRE(2 == sdl_r2->y); REQUIRE(3 == sdl_r2->w); REQUIRE(4 == sdl_r2->h); } }
true
56a8e1755b9b24a830b2de0121638cba3625ea3d
C++
JLPlummer79/CISC205
/Project_3/src/menu.cpp
UTF-8
4,493
3.53125
4
[]
no_license
/* * * Jesse Plummer * * Chapter 11, Programming Challenge #3 * * March 19th, 2021 * */ #include "menu.h" #include "error.h" #include "options.h" #include "display.h" #include <string> #include <iostream> //******************************************************* // name: menu // called by: main // passed: // passed: const int size // returns: nothing // The menu function controls the flow of the program * // using an initial Main Menu, validating user input and* // functions to process user requests and enter data * //******************************************************* void menu(access::Record* customerData) { std::string input; //hold user input int flag = 0; //hold menu cont/exit char c; //hold error check int numCustomers = 0; //keep track of number of customers //keep menu looping until 5 entered while(flag != 5 ) { //print company header printHeader(); std::cout << "\n Main Menu\n"; std::cout << "----------------------------------------\n"; std::cout << "1. Input a customer's information\n"; std::cout << "2. Edit a customer's information\n"; std::cout << "3. Search for contract by value\n"; std::cout << "4. Display all contract information\n"; std::cout << "5. Exit\n"; std::cout << "----------------------------------------\n\n"; std::getline(std::cin,input); //validate user input flag = checkSingleChar(input); switch(flag) { case 1: //add customer to customerData addNewCustomer(customerData, numCustomers); break; case 2: //edit existing customer editCustomer(customerData, numCustomers); break; case 3: //search for contracts equal or greater than //specified amount searchContract(customerData, numCustomers); break; case 4: //Display all contract info, print total of contracts contractTotal(customerData, numCustomers); break; case 5: //Exit program std::cout << "Exiting program\n"; border(); std::exit(0); default: //invalid input, start from beginning std::cout <<"Invalid input, please enter option from menu.\n"; break; }//end switch }//end while }//end menu //******************************************************* // name: editCustomerMenu // called by: editCustomer // passed: const std::string // returns: const int // The editCustomerMenu function prints the * // Edit Customer Menu, validate the user input, then * // returns the valid user entry, or prompts the user for* // a valid entry. * //******************************************************* const int editCustomerMenu(const std::string name) { //declare variables int flag = 0; //loop monitor std::string input; //holds user input //print Company heading printHeader(); //editCustomer menu while(flag != 5){ std::cout << "\n\n Edit Customer Menu\n"; std::cout << "----------------------------------------\n"; std::cout << "1. Edit customer name\n"; std::cout << "2. Edit boat name\n"; std::cout << "3. Edit contract value\n"; std::cout << "4. Edit paid to date amount\n"; std::cout << "5. Back to Main Menu\n"; std::cout << "----------------------------------------\n"; std::cout << "Currently selected customer to edit: " << name << ".\n\n"; //get input std::getline(std::cin, input); //validate input flag = checkSingleChar(input); //return user choice for editCustomer function to handle //or prompt a valid entry switch(flag) { case 1: case 2: case 3: case 4: return flag; break; case 5: flag = 5; break; default: std::cout << "Invalid entry. Please enter a menu option.\n"; break; } //end switch }//end while //Exit choice, will bring user to Main Menu return 0; }//end editCustomerMenu
true
a6964b9a61732389d59bab48ce94fbd7c7e16a3e
C++
jccarvalhosa/maratona
/uri/balls.cpp
UTF-8
362
3.046875
3
[]
no_license
#include <algorithm> #include <iostream> using namespace std; int valid(int n, int v) { for(int i=1;i<=v;i++) { int d=0; for(int ii=i;ii>0;ii--) for(int j=0;j<ii;j++) { d += ii; if(d==n) return 1; } } return 0; } int main() { int n, v; while(cin>>n>>v && n) { if(valid(n, v)) cout<<"possivel\n"; else cout<<"impossivel\n"; } return 0; }
true
7ca9a236663e5fdafe3ff0891336f83110c834d9
C++
L-Naej/Grassman
/src/antitrivector.cpp
UTF-8
1,107
2.8125
3
[]
no_license
#include "antitrivector.hpp" namespace gca { GCA_antitrivector::GCA_antitrivector() : Base() { setBases(); } GCA_antitrivector::GCA_antitrivector(const GCA_antitrivector& other) : Base(other) { setBases(); } GCA_antitrivector::GCA_antitrivector(double x, double y, double z, double w) : Base() { *this << x, y, z, w; setBases(); } GCA_antitrivector::~GCA_antitrivector() { } GCA_antitrivector&GCA_antitrivector::operator =(const GCA_antitrivector& other) { *this = other; Bases = other.Bases; return *this; } void GCA_antitrivector::setBases(){ for (int i=1; i<=2; ++i){ for (int j=i+1; j<=3; ++j){ for (int k=j+1; k<= 4; ++k){ Bases.push_back(i*100+j*10+k); } } } } //Bases e123 , e124 , e134 , e234 std::ostream& operator <<(std::ostream& stream, const GCA_antitrivector& antitrivector) { stream << "Antitrivector["; for (unsigned int i = 0; i < antitrivector.rows(); ++i) { stream << antitrivector(i) << "e" << antitrivector.Bases[i]; i != (antitrivector.rows() - 1) ? stream << ", " : stream << "]"; } return stream; } }//namespace gca
true
68115db23c0188f42b1c3c888390ef91fd623ce8
C++
mosmeh/islands
/islands/include/Model.h
UTF-8
1,615
2.609375
3
[ "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "BSD-3-Clause", "Zlib", "Unlicense" ]
permissive
#pragma once #include "Resource.h" #include "Component.h" #include "Texture.h" #include "Mesh.h" #include "Geometry.h" namespace islands { class Model : public SharedResource<Model> { public: Model(const std::string& filename); Model(const Model&) = delete; Model& operator=(const Model&) = delete; Model(Model&&) = default; virtual ~Model() = default; const std::vector<std::shared_ptr<Mesh>>& getMeshes(); bool isOpaque(); bool hasSkinnedMesh(); const geometry::AABB& getLocalAABB(); private: std::vector<std::shared_ptr<Mesh>> meshes_; bool opaque_, hasSkinned_; geometry::AABB localAABB_; void loadImpl() override; }; class ModelDrawer : public Drawable { public: ModelDrawer(std::shared_ptr<Model> model); virtual ~ModelDrawer() = default; void update() override; void draw() override; bool isOpaque() const override; std::shared_ptr<Model> getModel() const; void setVisible(bool visible); void setCullFaceEnabled(bool enabled); void pushMaterial(std::shared_ptr<Material> material); std::shared_ptr<Material> popMaterial(); void enableAnimation(const std::string& name, bool loop = true, double tps = 24.0, size_t startFrame = 0); void stopAnimation(); bool isPlayingAnimation() const; size_t getCurrentAnimationFrame() const; protected: std::shared_ptr<Model> model_; bool visible_, cullFaceEnabled_; Material::UpdateUniformCallback defaultUpdateCallback_; std::stack<std::shared_ptr<Material>> materialStack_; struct Animation { std::string name; bool playing = false, loop; double duration, tps; double startTime; size_t startFrame; } anim_; }; }
true
0cde89ed1a398fba22e5e5615529db82601c3cc7
C++
pombredanne/Clonewise
/src/Launcher/main.cpp
UTF-8
2,057
2.625
3
[]
no_license
#include <cstdlib> #include <cstdio> #include <cstring> struct Command { const char *name; int (*main)(int argc, char *argv[]); }; int Clonewise_build_database(int argc, char *argv[]); int Clonewise_train(int argc, char *argv[]); int Clonewise_train2(int argc, char *argv[]); int Clonewise_query(int argc, char *argv[]); int Clonewise_query_embedded(int argc, char *argv[]); int Clonewise_query_cache(int argc, char *argv[]); int Clonewise_query_embedded_cache(int argc, char *argv[]); int Clonewise_make_cache(int argc, char *argv[]); int Clonewise_make_embedded_cache(int argc, char *argv[]); int Clonewise_parse_database(int argc, char *argv[]); int Clonewise_find_bugs(int argc, char *argv[]); int Clonewise_find_file(int argc, char *argv[]); int Clonewise_query_source(int argc, char *argv[]); int Clonewise_find_license_problems(int argc, char *argv[]); Command commands[] = { { "build-database", Clonewise_build_database }, { "train-shared", Clonewise_train }, { "train-embedded", Clonewise_train2 }, { "query-shared", Clonewise_query }, { "query-embedded", Clonewise_query_embedded }, { "query-shared-source", Clonewise_query_source }, { "make-shared-cache", Clonewise_make_cache }, { "make-embedded-cache", Clonewise_make_embedded_cache }, { "query-shared-cache", Clonewise_query_cache }, { "query-embedded-cache", Clonewise_query_embedded_cache }, { "parse-database", Clonewise_parse_database }, { "find-bugs", Clonewise_find_bugs }, { "find-license-problems", Clonewise_find_license_problems }, { "find-file", Clonewise_find_file }, { NULL, NULL }, }; static void Usage(const char *argv0) { fprintf(stderr, "Usage: %s command [args ...]\n", argv0); fprintf(stderr, "Commands:\n"); for (int i = 0; commands[i].main; i++) { fprintf(stderr, "\t%s\n", commands[i].name); } exit(0); } int main(int argc, char *argv[]) { if (argc < 2) { Usage(argv[0]); } for (int i = 0; commands[i].main; i++) { if (strcmp(argv[1], commands[i].name) == 0) { exit(commands[i].main(argc - 1, &argv[1])); } } Usage(argv[0]); }
true
0fc9a96ee5759e7010477fbf34b4fe365b028927
C++
DinuCr/CS
/Info/Anton and Danik/main.cpp
UTF-8
336
2.828125
3
[]
no_license
#include <iostream> using namespace std; int a,b,i; int main() { int n; cin>>n; for(i=1; i<=n; ++i) { char c; cin>>c; if(c=='A') ++a; else ++b; } if(a>b) cout<<"Anton"; if(a<b) cout<<"Danik"; if(b==a) cout<<"Friendship"; }
true
6aaf17921546f59e7729d9f6195f2e12bbc59f1f
C++
koravel/textEditor-Cpp
/SaveFileDialog.cpp
UTF-8
1,140
2.546875
3
[]
no_license
#include "SaveFileDialog.h" SaveFileDialog::SaveFileDialog() { } BOOL SaveFileDialog::SaveFile(HWND hwnd, HWND hEdit) { return Dialog(hwnd ,hEdit); } BOOL SaveFileDialog::ActionType(OPENFILENAME ofn, HWND hEdit, LPCTSTR szFileName) { if (GetSaveFileName(&ofn)) { if (Action(hEdit, szFileName)) return true; return false; } return false; } BOOL SaveFileDialog::Action(HWND hEdit, LPCTSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { DWORD dwTextLength; dwTextLength = GetWindowTextLength(hEdit); // No need to bother if there's no text. if (dwTextLength > 0) { LPSTR pszText; DWORD dwBufferSize = dwTextLength + 1; pszText = (LPSTR)GlobalAlloc(GPTR, dwBufferSize); if (pszText != NULL) { if (GetWindowText(hEdit, pszText, dwBufferSize)) { DWORD dwWritten; if (WriteFile(hFile, pszText, dwTextLength, &dwWritten, NULL)) bSuccess = TRUE; } GlobalFree(pszText); } } CloseHandle(hFile); } return bSuccess; }
true
7be1ec9d288ee20634be5b9b4a57a0de259a44df
C++
Foidolite/Ray-Tracing-Demo
/rayTracer/rayTrace/matrix.h
UTF-8
12,304
3.4375
3
[ "MIT" ]
permissive
#pragma once #include <stdexcept> #include <vector> #include <cmath> template <typename component> class Matrix { public: //constructors Matrix() {} Matrix(std::initializer_list < Vector<component>> cols) : columns(cols) { nRows = this->columns[0].getDimension(); nCols = cols.size(); verifyDims(); } Matrix(std::initializer_list <component *> cols) : columns(cols) { nRows = this->columns[0].getDimension(); nCols = cols.size(); verifyDims(); } Matrix(component * vals, unsigned int numCols, unsigned int numRows); Matrix(std::vector<std::vector<component>> vals); Matrix(std::vector<Vector<component>> vals); void verifyDims() { unsigned int colDim = columns[0].getDimension(); for (unsigned int i = 1; i < nCols; ++i) { if (colDim != columns[i].getDimension()) { throw std::invalid_argument("All matrix columns must be of the same length"); } } } Matrix(unsigned int numRows, unsigned int numCols); //getters component getValueRC(unsigned int row, unsigned int column) const; component getValueCR(unsigned int column, unsigned int row) const; Vector<component> getColumn(unsigned int column) const; Vector<component> getRow(unsigned int row) const; unsigned int getNumRows() const { return nRows; }; unsigned int getNumCols() const { return nCols; }; //setters void setValueRC(component value, unsigned int row, unsigned int column); void setValueCR(component value, unsigned int column, unsigned int row); void setColumn(Vector<component> value, unsigned int column); //matrix operations double determinant(); Matrix transpose(); Matrix inverse(); //row/column major conversions void toColArray(component * valArray); void toRowArray(component * valArray); static void toColArray(component * vals, component * retVals, unsigned int numCols, unsigned int numRows); static void toRowArray(component * vals, component * retVals, unsigned int numCols, unsigned int numRows); //member function overloads void operator +=(const Matrix b) { for (int i = 0; i < nCols; ++i) columns[i] += b[i]; } void operator -=(const Matrix b) { for (int i = 0; i < nCols; ++i) columns[i] -= b[i]; } Matrix operator-() const { std::vector<Vector<component>> newVals; for (int i = 0; i < nCols; ++i) newVals.push_back(-columns[i]); return Matrix<component>(newVals); } Matrix operator *=(double b) { for (int i = 0; i < nCols; ++i) columns[i] *= b; } Matrix operator /=(double b) { for (int i = 0; i < nCols; ++i) columns[i] /= b; } Vector<component> operator [] (int i) const { return getColumn(i); } private: std::vector<Vector<component>> columns; unsigned int nRows, nCols; }; //some constructors template <typename component> Matrix<component>::Matrix(component * vals, unsigned int numCols, unsigned int numRows) { nRows = numRows; nCols = numCols; for (int c = 0; c < nCols; ++c) { Vector<component> column(numRows); for (int r = 0; r < nRows; ++r) column.setValue(vals[c*numRows + r], r); columns.push_back(column); } this->verifyDims(); } template <typename component> Matrix<component>::Matrix(std::vector<std::vector<component>> vals) { if (vals.size() == 0 || vals[0].size() == 0) throw std::invalid_argument("Attempt to construct Matrix with empty vector."); nRows = vals[0].size(); nCols = vals.size(); for (unsigned int c = 0; c < vals.size(); ++c) { columns.push_back(Vector<component>(vals[c])); } verifyDims(); } template <typename component> Matrix<component>::Matrix(std::vector<Vector<component>> vals) { if (vals.size() == 0 || vals[0].getDimension() == 0) throw std::invalid_argument("Attempt to construct Matrix with empty vector."); nRows = vals[0].getDimension(); nCols = vals.size(); for (unsigned int c = 0; c < vals.size(); ++c) { columns.push_back(vals[c]); } verifyDims(); } template <typename component> Matrix<component>::Matrix(unsigned int numRows, unsigned int numCols) { nRows = numRows; nCols = numCols; while (columns.size() < numCols) columns.push_back(Vector<component>(numRows)); verifyDims(); } //some getters template <typename component> component Matrix<component>::getValueRC(unsigned int row, unsigned int column) const{ if (row < nRows && column < nCols) return columns[column][row]; else throw std::out_of_range("Attempt to index matrix out of range."); } template <typename component> component Matrix<component>::getValueCR(unsigned int column, unsigned int row) const { return this->getValueRC(row, column); } template <typename component> Vector<component> Matrix<component>::getColumn(unsigned int column) const { if (column < nCols) return columns[column]; else throw std::out_of_range("Attempt to index matrix out of range."); } template <typename component> Vector<component> Matrix<component>::getRow(unsigned int row) const { if (row < nRows) { std::vector<component> newRow; for (int c = 0; c < nCols; ++c) { newRow.push_back(columns[row]); } return Vector<component>(newRow); } else throw std::out_of_range("Attempt to index matrix out of range."); } //setters template <typename component> void Matrix<component>::setValueRC(component value, unsigned int row, unsigned int column) { if (row < nRows && column < nCols) columns[column].setValue(value, row); else throw std::out_of_range("Attempt to index matrix out of range."); } template <typename component> void Matrix<component>::setValueCR(component value, unsigned int column, unsigned int row) { this->setValueRC(value, row, column); } template <typename component> void Matrix<component>::setColumn(Vector<component> value, unsigned int column) { if (column < nCols) columns[column] = value; else throw std::out_of_range("Attempt to index matrix out of range."); } //matrix operations template <typename component> double Matrix<component>::determinant() { if (nRows != nCols || nRows == 1) std::invalid_argument("Determinant only defined for square matrices."); else { if (nRows == 2) return (double)columns[0][0] * (double)columns[1][1] - (double)columns[1][0] * (double)columns[0][1]; else { double result = 0; for (unsigned int i = 0; i < nRows; ++i) { std::vector<std::vector<component>> conjugate; for (unsigned int c = 1; c < nCols; ++c) { std::vector<component> column; for (unsigned int r = 0; r < nRows; ++r) { if (r != i) column.push_back(columns[c][r]); } conjugate.push_back(column); } result += pow(-1,i)*columns[0][i]*Matrix(conjugate).determinant(); } return result; } } } template <typename component> Matrix<component> Matrix<component>::transpose() { std::vector<std::vector<component>> transposed; for (unsigned int r = 0; r < nRows; ++r) { std::vector<component> column; for (unsigned int c = 0; c < nCols; ++c) { column.push_back(columns[c][r]); } transposed.push_back(column); } return Matrix(transposed); } template <typename component> Matrix<component> Matrix<component>::inverse() { if (this->determinant() == 0) throw std::invalid_argument("Matrix is not invertible."); std::vector<std::vector<component>> cof; for (unsigned int c = 0; c < nCols; ++c) { std::vector<component> column; for (unsigned int r = 0; r < nRows; ++r) { std::vector<std::vector<component>> det; for (unsigned int C = 0; C < nCols; ++C) { if (C != c) { std::vector<component> detCol; for (unsigned int R = 0; R < nRows; ++R) { if (R != r) detCol.push_back(columns[C][R]); } det.push_back(detCol); } } column.push_back(pow(-1, r + c)*Matrix<component>(det).determinant()); } cof.push_back(column); } Matrix<component> adj = Matrix<component>(cof).transpose(); return (1 / this->determinant())*adj; } //operator overloads template <typename component> Matrix<component> operator + (const Matrix<component> &a, const Matrix<component> &b) { std::vector<Vector<component>> newValues; int numCols = a.getNumCols() < b.getNumCols() ? a.getNumCols() : b.getNumCols(); for (int c = 0; c < numCols; ++c) newValues.push_back(a[c] + b[c]); return Matrix<component>(newValues); } template <typename component> Matrix<component> operator - (const Matrix<component> &a, const Matrix<component> &b) { std::vector<Vector<component>> newValues; int numCols = a.getNumCols() < b.getNumCols() ? a.getNumCols() : b.getNumCols(); for (int c = 0; c < numCols; ++c) newValues.push_back(a[c] - b[c]); return Matrix<component>(newValues); } template <typename component> Matrix<component> operator * (double a, const Matrix<component> &b) { std::vector<Vector<component>> newValues; for (unsigned int c = 0; c < b.getNumCols(); ++c) { newValues.push_back(a*b[c]); } return Matrix<component>(newValues); } template <typename component> Matrix<component> operator * (const Matrix<component> &a, double b) { std::vector<Vector<component>> newValues; for (int c = 0; c < a.getNumCols(); ++c) { newValues.push_back(b*a[c]); } return Matrix<component>(newValues); } template <typename component> Matrix<component> operator * (const Matrix<component>& a, const Matrix<component>& b) { if (b.getNumRows() != a.getNumCols()) throw std::invalid_argument("Attempt to multiply matrices of incompatible dimension."); std::vector<Vector<component>> newValues; for (int c = 0; c < b.getNumCols(); ++c) { Vector<component> newCol(a[0].getDimension()); for (int r = 0; r < b.getNumRows(); ++r) { newCol += a[r] * b[c][r]; } newValues.push_back(newCol); } return Matrix<component>(newValues); } template <typename component> Vector<component> operator * (const Matrix<component>& a, const Vector<component>& b) { if (b.getDimension() != a.getNumRows()) throw std::invalid_argument("Attempt to multiply vector with matrix of incompatible dimension."); Vector<component> newVec(b.getDimension()); for (int c = 0; c < a.getNumCols(); ++c) { newVec += a[c] * b[c]; } return newVec; } template <typename component> Vector<component> operator * (const Vector<component>& a, const Matrix<component>& b) { if (a.getDimension() != b.getNumRows()) throw std::invalid_argument("Attempt to multiply vector with matrix of incompatible dimension."); Vector<component> newVec(a.getDimension()); for (int c = 0; c < b.getNumCols(); ++c) { newVec += b[c] * a[c]; } return newVec; } template <typename component> Matrix<component> operator / (const Matrix<component> &a, double b) { std::vector<Vector<component>> newValues; for (int c = 0; c < a.getNumCols(); ++c) { newValues.push_back(a[c]/b); } return Matrix<component>(newValues); } //row/column major conversions template <typename component> void Matrix<component>::toColArray(component * valArray) { for (unsigned int c = 0; c < nCols; ++c) { for (unsigned int r = 0; r < nRows; ++r) { valArray[c*nCols + r] = columns[c][r]; } } } template <typename component> void Matrix<component>::toRowArray(component * valArray) { for (unsigned int c = 0; c < nCols; ++c) { for (unsigned int r = 0; r < nRows; ++r) { valArray[r*nRows + c] = columns[c][r]; } } } template <typename component> static void Matrix<component>::toColArray(component * vals, component * retVals, unsigned int numCols, unsigned int numRows) { for (unsigned int c = 0; c < numCols; ++c) { for (unsigned int r = 0; r < numRows; ++r) { retVals[c*numCols + r] = vals[r*numRows, + c]; } } } template <typename component> static void Matrix<component>::toRowArray(component * vals, component * retVals, unsigned int numCols, unsigned int numRows) { for (unsigned int c = 0; c < numCols; ++c) { for (unsigned int r = 0; r < numRows; ++r) { retVals[r*numRows, + c] = vals[c*numCols + r]; } } } //print function template <typename component> std::ostream& operator << (std::ostream& out, const Matrix<component>& data) { for (int i = 0; i < data.getNumCols(); ++i) out << data[i] << std::endl; return out; }
true
5a010bfadf6aadaf7992973a144f1932bdebc620
C++
artongdou/CarND-Path-Planning-Project
/src/costs.cpp
UTF-8
3,516
3.1875
3
[ "MIT" ]
permissive
#include "costs.h" #include <iostream> using std::cout; using std::endl; using std::vector; // Cost functions weights configuration #define SPEED_WEIGHT 15 #define DIST_WEIGHT 40 #define LANE_CHANGE_WEIGHT 4 #define UNSAFE_DIST (10) /** * Function calculate costs based on given trajectory at {t=0, t=1} * @param trajectory - vehicle trajectory at {t=0, t=1} * @param predictions - vector of all predicted vehicles detected in the * surroundings * @return total cost */ double calculate_cost(vector<Vehicle> &trajectory, vector<Vehicle> &predictions) { vector<std::function<double(vector<Vehicle> &, vector<Vehicle> &)>> cf_list = {speed_cost, safe_distance_cost, lane_change_cost}; vector<double> weight_list = {SPEED_WEIGHT, DIST_WEIGHT, LANE_CHANGE_WEIGHT}; double cost = 0; for (int i = 0; i < cf_list.size(); ++i) { double new_cost = weight_list[i] * cf_list[i](trajectory, predictions); cost += new_cost; } return cost; } /** * Function calculate speed cost. Closer to the speed limit yields lower cost, * but exceeding speed limit will be max cost. * @param trajectory - vehicle trajectory at {t=0, t=1} * @param predictions - vector of all predicted vehicles detected in the * surroundings * @return speed cost */ double speed_cost(vector<Vehicle> &trajectory, vector<Vehicle> &predictions) { double cost; if (trajectory[1].v > SPEED_LIMIT) { cost = 1; // max cost } else { double diff_d = fabs(trajectory[0].d - trajectory[1].d); double diff_v = fabs(SPEED_LIMIT - trajectory[1].v) / 4; cost = (1 - exp(-diff_v)); } cout << " " << "speed cost= " << cost << endl; return cost; } /** * Function to calculate lane change cost. It panelizes the distance travel at d * direction. * @param trajectory - vehicle trajectory at {t=0, t=1} * @param predictions - vector of all predicted vehicles detected in the * surroundings * @return lane change cost */ double lane_change_cost(vector<Vehicle> &trajectory, vector<Vehicle> &predictions) { double diff_d = fabs(trajectory[0].d - trajectory[1].d); double cost = 1 - exp(-diff_d); cout << " " << "lane change cost= " << cost << endl; return cost; } /** * Function calculate safe distance cost. It panalizes trajectory that puts the * vehicle too close to other vehicles. * @param trajectory - vehicle trajectory at {t=0, t=1} * @param predictions - vector of all predicted vehicles detected in the * surroundings * @return safe distance cost */ double safe_distance_cost(vector<Vehicle> &trajectory, vector<Vehicle> &predictions) { double dist_to_veh_ahead = 9999999; double dist_to_veh_behind = 9999999; Vehicle veh_ahead, veh_behind; if (trajectory[1].get_vehicle_ahead(trajectory[1].get_lane(), predictions, veh_ahead)) { dist_to_veh_ahead = veh_ahead.s - trajectory[1].s; } if (trajectory[1].get_vehicle_behind(trajectory[1].get_lane(), predictions, veh_behind)) { dist_to_veh_behind = -veh_behind.s + trajectory[1].s; } double cost; double min_dist = fmin(fabs(dist_to_veh_ahead), fabs(dist_to_veh_behind)); if (min_dist <= UNSAFE_DIST) { cost = 1; } else { cost = exp(-fabs(min_dist - UNSAFE_DIST) / 10); } cout << "dist to veh ahead: " << dist_to_veh_ahead << endl; cout << " " << "distance cost= " << cost << endl; return cost; }
true
f55c21292eadd85895b3286914fd4c93bcb097cf
C++
predatorsfr/OOP-tek-2
/CCP_plazza_2018/loop.cpp
UTF-8
1,166
2.6875
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** plazza ** File description: ** loop file */ #include "my.hpp" void loop4(ini::Info *info, const int chiefs) { int buf; buf = info->g_to_m() / chiefs; if (info->g_to_m() % chiefs != 0) { buf = buf + 1; } info->s_kitchen(buf); } void loop3(ini::Info *info, std::vector<int> n_nb) { int i = 0; int j = 0; while (i != info->g_how()) { j = j + n_nb.at(i); i++; } info->s_num(n_nb); info->a_to_m(j); } int loop2(int i, std::string buf) { int j = 0; if (i != 0) buf.erase(buf.length() - 1); buf.erase(0, 1); j = std::atoi(buf.c_str()); return (j); } int loop(ini::Info *info, std::string tamp, ini::get_ready get_ready) { std::vector<std::string> nbr; std::vector<int> n_nb; int i = 0; printf("OK\n"); if (tamp == "exit") exit(0); info->init_info(tamp); nbr = info->g_nbr(); while (i != info->g_how() - 1) { n_nb.push_back(loop2(0, nbr.at(i))); i++; } n_nb.push_back(loop2(1, nbr.at(info->g_how() - 1))); loop3(info, n_nb); fork(info, get_ready); return (0); }
true
54a55ac372c6abc90cd23adcdd332e019191829f
C++
dscrawford/homework
/Junior/Fall_2018/CS4348/Project2/semFunctions.cc
UTF-8
471
2.90625
3
[]
no_license
#include "project2_dsc160130.h" void wait(sem_t &semaphore) { if (sem_wait(&semaphore) == -1) { printf("ERROR: waiting for semaphore"); exit(1); } } void send(sem_t &semaphore) { if (sem_post(&semaphore) == -1) { printf("ERROR: sending semaphore"); exit(1); } } void init_semaphore(sem_t& semaphore, int initialValue) { if (sem_init (&semaphore,0,initialValue) == -1) { printf("ERROR: Failed to initialize semaphore."); exit(1); } }
true
cbd1015552589e64ccc6955bfcd227790b7a1360
C++
DaeYeon24/Portfolio
/etc/Telephone/TelephoneNumber.h
UHC
1,129
2.65625
3
[]
no_license
#pragma once #include <iostream> #include <string> using namespace std; #define GROUPNUM 1 #define GROUPNUMNEXT 2 // 010 SKT 011, 017 KT 016, 018 LG 019 // 02 // 031 //õ 032 // 033 //泲 041 // 042 // 043 //λ 051 // 052 //뱸 053 // 054 //泲 055 // 061 // 062 // 063 // 064 enum TRUENUM // ι° ڸ Ǻ { PHONE = 49, SEOUL, REGIONSTART = 51, GYEONGGI = 51, CHUNGCHEONG, GYEONGSANG, JEOLLA = 54, REGIONEND = 54 }; enum TELECOMNUM //Ż ° ȣ Ǻ { TELECOMNUM_PUBLIC = 48, TELECOMNUM_SKT1, TELECOMNUM_KT1 = 54, TELECOMNUM_SKT2, TELECOMNUM_KT2, TELECOMNUM_LG }; enum REGIONNUM // ° ȣ Ǻ { REGIONNUM_NUM1 = 49, REGIONNUM_NUM2, REGIONNUM_NUM3, REGIONNUM_NUM4, REGIONNUM_NUM5 }; class TelephoneNumber { private: char* m_chpNum; string m_strTemp; public: TelephoneNumber(); ~TelephoneNumber(); void NewSetting(); void Matching(); bool RegionMatching(); void MakingNumber(); inline void Show() { cout << "ϼ ȣ : " << m_chpNum << endl; } };
true
d5951f0de1bdb7cd13e7c17c4914e3103a92f7a2
C++
anirul/DataStructures
/ListTest.cpp
UTF-8
519
2.71875
3
[ "MIT" ]
permissive
#include <cassert> #include <iostream> #include <gtest/gtest.h> #include "List.h" TEST(ListTest, SimpleTest) { List<float> myList; for (int i = 0; i < 100; ++i) myList.push_back((float)i); float i = 0.0f; EXPECT_EQ(100, myList.size()); for (float f : myList) { EXPECT_FLOAT_EQ(i, f); i += 1.0f; } EXPECT_FLOAT_EQ(0.0f, myList.front()); EXPECT_FLOAT_EQ(99.0f, myList.back()); EXPECT_EQ(100, myList.size()); } int main(int ac, char** av) { ::testing::InitGoogleTest(&ac, av); return RUN_ALL_TESTS(); }
true
86ea740f7f5a5007047026204c3c0084cff6490b
C++
Harrypotterrrr/Algorithm-ACM
/String/LC 0071 - getline.cpp
UTF-8
629
3.125
3
[]
no_license
/* 71. Simplify Path */ class Solution { public: string simplifyPath(string path) { vector<string>V; stringstream ss(path); string cur; while(getline(ss, cur, '/')){ if(cur == "." || cur == "") continue; if(cur == ".."){ if(!V.empty()) V.pop_back(); } else{ V.push_back(cur); } } cur.clear(); for(int i=0; i<V.size() ; i++){ cur += '/' + V[i]; } if(cur == "") return "/"; return cur; } };
true
1444b3fa7a8696a27be8cacb32902b33dcda3439
C++
Malcom-Nubbins/DX11-Engine
/DirectX 11 Engine/Core/Scene/Scene Elements/Element Components/Transform.h
UTF-8
741
2.625
3
[]
no_license
#pragma once #include "../../../Globals/stdafx.h" #include "../../../Globals/Structs.h" class Transform { private: XMFLOAT4X4 m_World; XMFLOAT3 m_Position; XMFLOAT3 m_Rotation; XMFLOAT3 m_Scale; XMFLOAT3 m_PrevPosition; Transform* m_Parent; public: Transform(); ~Transform(); void SetPosition(XMFLOAT3 pos) { m_Position = pos; } XMFLOAT3 GetPosition() const { return m_Position; } void SetRotation(XMFLOAT3 rot) { m_Rotation = rot; } XMFLOAT3 GetRotation() const { return m_Rotation; } void SetScale(XMFLOAT3 scale) { m_Scale = scale; } XMFLOAT3 GetScale() const { return m_Scale; } XMFLOAT4X4& GetWorld() { return m_World; } void SetParent(Transform* parent) { m_Parent = parent; } void Update(double delta); };
true
e7490cfa054ede0ff9696ecf2f930b05ff25dde7
C++
tavallat/ECE244Lab2
/main.cpp
UTF-8
8,145
3.0625
3
[]
no_license
// main.cpp // lab3 // Created by Tina Tavallaeian on 2017-10-15. // Copyright © 2017 Tina Tavallaeian. All rights reserved. #include <iostream> #include "Node.h" #include "Resistor.h" #include "RParser.h" #include <cstdlib> #include <sstream> #include <string> #include <iomanip> using namespace std; int main(int argc, char** argv) { string command, line, input; int maxnode, maxres; rIndex = 0; cout << "> "; getline(cin, line); while (!cin.eof()) { stringstream linestream(line); //command is retracted from line stream linestream >> command; //going through each command and applying what is needed if (command == "maxVal"){ linestream >> maxnode >> maxres; if (maxnode == 0 || maxres == 0) cout << "Error: maxVal arguments must be greater than 0" << endl; else{ //dynamically allocate two arrays in main nodeArray = new Node [maxnode+1]; resArray = new Resistor [maxres]; cout << "New network: max node number is " << maxnode << "; max resistors is " << maxres << endl; } } //***** insertR COMMAND ***** else if (command == "insertR") { string Rname, extra; float Rvalue; int node1, node2; //initializing each variable Rname = "Rname"; Rvalue = 1000000000; node1 = 4999; node2 = 4998; extra = "extra"; linestream >> Rname; linestream >> Rvalue; linestream >> node1; //making sure the user doesnt enter decimal numbers char next; next = linestream.peek(); if (next == '.' || next > 33) //this is to ensure the user dosent type a wrong character after cout << "Error: invalid argument" << endl; else { linestream >> node2; next = linestream.peek(); if (next == '.' || next > 33 ) cout << "Error: invalid argument" << endl; else { linestream >> extra; if (Rvalue < 0) //negative resistance cout << "Error: negative resistance" << endl; else if (linestream.fail() && !linestream.eof()) cout << "Error: invalid argument" << endl; //if input is invalid else insertRCommand(Rname, Rvalue, node1, node2, extra); } } } //***** modifyR COMMAND ***** else if (command == "modifyR") { string Rname, extra; float newvalue; Rname = "Rname"; //initialized value of newvalue newvalue = 99999; //initialized value of newvalue extra = "extra"; //initialized value of extra linestream >> Rname >> newvalue; char next; next = linestream.peek(); if (next == '.' || next > 33) cout << "Error: invalid argument" << endl; else { linestream >> extra; if (linestream.fail() && !linestream.eof()) //if invalid argument cout << "Error: invalid argument" << endl; else modifyCommand(Rname, newvalue, extra); }} //***** deleteR COMMAND ***** else if (command == "deleteR") { string Rname, extra; //initializing the values Rname = "Rname"; extra = "extra"; //get the input from stream linestream >> Rname >>extra; if (Rname == "Rname") cout << "Error: too few arguments" << endl; else if (extra != "extra") cout << "Error: too many arguments" << endl; else if (linestream.fail() && !linestream.eof()) cout << "Error: invalid argument" << endl; else deleteRCommand(Rname, extra); } //***** printNode COMMAND ***** else if (command == "printNode") { int nodevalue; string extra; nodevalue = 4999; //initialized value extra = "extra"; //initialized value linestream >> nodevalue; char nextchar; if (linestream.fail() & linestream.eof()) cout << "Error: too few arguments" << endl; else if (linestream.fail()) { //clear the integer to see whats up linestream.clear(); string badinput; linestream >> badinput; //i have to check if badinput is all or not //MY ALL BLOCK if (badinput == "all") { //i have to check if they inputed extra or not linestream >> extra; if (extra != "extra") cout << "Error: too many arguments" << endl; else cout << "Print: all nodes" << endl; // by now i have dealt with all } else cout << "Error: invalid argument" << endl; } //now lets consider all cases where an integer input can go wrong else { nextchar = linestream.peek (); if (nextchar == '.' || nextchar > 33) cout <<"Error: invalid argument" << endl; else { linestream >> extra; if (nodevalue < 0 || nodevalue > 5000) cout << "Error: node " << nodevalue << " is out of permitted range 0-5000" << endl; else if (nodevalue == 4999) cout << "Error: too few arguments" << endl; else if (nodevalue != 4999 && extra != "extra") cout << "Error: too many arguments" << endl; else if (extra != extra) cout << "Error: too many arguments" << endl; else printNodeCommand(nodevalue, extra); } } }//****** PRINTR COMMAND *************** else if (command == "printR") { string Rname, extra; //initializing the values Rname = "Rname"; extra = "extra"; //get the input from stream linestream >> Rname >> extra; if (linestream.fail() && !linestream.eof()) cout << "Error: invalid argument" << endl; else printRCommand(Rname, extra); } else cout << "Error: invalid command" << endl; linestream.ignore(1000, '\n'); command = "hehe...nottoday"; //this is to ensure if the user //presses enter i dont get invalid command cout << "> "; getline(cin, line); } return (0); }
true
7e2a9c5908899ce46fbc12556157880c189b3cdf
C++
NaimaHasan/Data-Structure
/13.Graph/BFSDFS/party.cpp
UTF-8
1,096
2.6875
3
[]
no_license
#include<bits/stdc++.h> #define WHITE 0 #define GREY 1 #define BLACK 2 using namespace std; queue<int>q; void bfs(int s, int color[],vector<int> adj[],int depth[]) { int i,x; while(!q.empty()) q.pop(); q.push(s); color[s]=GREY; while(!q.empty()) { int u=q.front(); q.pop(); for(i=0;i<adj[u].size();i++) { int x=adj[u][i]; if(color[x]==WHITE) { color[x]=GREY; depth[x]=depth[u]+1; q.push(x); } } color[u]=BLACK; } } int main() { int t,u,v,n,m,i; scanf("%d\n",&t); while(t--) { vector<int> adj[10000]; int depth[10000]={0}; int color[10000]={WHITE}; scanf("%d%d",&n,&m); for(i=0;i<m;i++) { scanf("%d%d",&u,&v); adj[u].push_back(v); adj[v].push_back(u); } bfs(0,color,adj,depth); for(i=1;i<n;i++) { printf("%d\n",depth[i]); } if(t)printf("\n"); } }
true
481438a0cd040e40c0161567182809eb262c020b
C++
PixelCatalyst/CodingStandard
/vector/Vector.cpp
UTF-8
378
3.25
3
[]
no_license
#include "Vector.hpp" #include <cmath> Vector::Vector(double x, double y) : x(x), y(y) { } std::string Vector::toString() { return "(" + std::to_string(x) + ", " + std::to_string(y) + ")"; } double Vector::getLength() const { return sqrt(x * x + y * y); } double Vector::getX() const { return x; } double Vector::getY() const { return y; }
true
28118f8f390a78dc67c6c4018eadcf5a38ed6b98
C++
BackupTheBerlios/mgmodeler-svn
/plugins/IO/vrmlimport.cc
UTF-8
1,334
2.65625
3
[]
no_license
#include "plugin.h" #include <vector> #include "math/vector3.h" #include <cstdlib> #include <cstdio> #define PLUGIN_NAME "VRML Import Plugin" #define PLUGIN_MENU "Vrml Import" #define PLUGIN_ICON "vrml.png" namespace { std::vector<Vec3f> *points; std::vector<std::vector<int> > *faces; }; extern "C" int yyparse (); extern "C" void yyrestart (FILE *); extern "C" void addPoint(double x, double y, double z) { points->push_back(Vec3f(x,y,z)); } extern "C" void addFace(int *vec, int len) { std::vector<int> face; for (int i=0; i<len; i++) { if (vec[i]==-1) { faces->push_back(face); face.clear (); } else face.push_back(vec[i]); } } class VRMLImport : public PluginIO { public: VRMLImport () : PluginIO (PLUGIN_NAME, PLUGIN_MENU, PLUGIN_ICON) {} int importData(const std::string &filename) { points.clear (); faces.clear (); FILE *input = fopen(filename.c_str(), "r"); if (!input) return -2; ::points=&points; ::faces=&faces; yyrestart (input); yyparse(); fclose (input); return 0; } const std::vector<Vec3f> &getPoints() { return points; } const std::vector<std::vector<int> > &getFaces() { return faces; } private: std::vector<Vec3f> points; std::vector<std::vector<int> > faces; }; DECLARE_PLUGIN (VRMLImport);
true
ea2c2598ecb5cf540a5b74610a89fd506b2eb610
C++
jcfalcone/FalconeEngine
/FalconeEngine/Physics/spherecollider.cpp
UTF-8
9,469
2.578125
3
[]
no_license
#include "spherecollider.h" #define _USE_MATH_DEFINES #include "boxcollider.h" #include "polycollider.h" #include "rigidbody.h" #include <algorithm> #include <float.h> #include <math.h> namespace FalconeEngine { namespace Physics { SphereCollider::SphereCollider() : Collider() { } SphereCollider::SphereCollider(float _radius) : Collider() { this->radius = _radius; } SphereCollider::~SphereCollider() { } void SphereCollider::Start() { this->type = "SPHERE"; //FalconeEngine::ObjectControl::Instance()->getPhysics()-> } void SphereCollider::Update(float deltaTime) { } void SphereCollider::Render() { } float SphereCollider::CalcMass(float _density) { float radiusCM = this->radius;// * UNITTOCM; float volume = (4.0f / 3.0f) * M_PI * (radiusCM * radiusCM * radiusCM); float mass = _density * volume; this->rigidBody->SetMass(mass); this->rigidBody->SetInertia(mass * radiusCM * radiusCM); return _density * volume; } bool SphereCollider::CheckCollision(Collider * other) { if (other->GetType() == "SPHERE") { return this->CheckCollisionSphere(other); } else if (other->GetType() == "BOX") { return this->CheckCollisionBox(other); } else if (other->GetType() == "POLY") { return this->CheckCollisionPoly(other); } return false; } bool SphereCollider::CheckCollisionSphere(Collider * other) { if (SphereCollider* collider = dynamic_cast<SphereCollider*>(other)) { FalconeEngine::Vector2 posOther = collider->GetPosition(); FalconeEngine::Vector2 position = this->GetPosition(); double deltaX = position.x - posOther.x; deltaX *= deltaX; double deltaY = position.y - posOther.y; deltaY *= deltaY; float sumRadius = collider->GetRadius() + this->GetRadius(); sumRadius *= sumRadius; if (deltaX + deltaY <= sumRadius) { return true; } } return false; } bool SphereCollider::CheckCollisionBox(Collider * other) { if (BoxCollider* collider = dynamic_cast<BoxCollider*>(other)) { float distance = collider->SquaredDistPointAABB(this->GetPosition()); return distance <= (this->radius * this->radius); } return false; } bool SphereCollider::CheckCollisionPoly(Collider * other) { this->lastData.Clear(); this->lastData.object = this; this->lastData.other = other; if (PolyCollider* collider = dynamic_cast<PolyCollider*>(other)) { // Transform circle center to Polygon model space Vector2 center = this->GetPosition(); //center = collider->GetMatrix().Transpose() * (center - collider->GetPosition()); -- TODO // Find edge with minimum penetration // Exact concept as using support points in Polygon vs Polygon float separation = 0;//-FLT_MAX; -- TODO int faceNormal = 0; for (int count = 0;count < collider->GetVerticesCount(); ++count) { float sep = collider->GerNormal()[count].Dot(center - collider->GetVertices()[count]); if (sep > this->radius) return false; if (sep > separation) { separation = sep; faceNormal = count; } } // Grab face's vertices Vector2 vertice1 = collider->GetVertices()[faceNormal]; int count2 = faceNormal + 1 < collider->GetVerticesCount() ? faceNormal + 1 : 0; Vector2 vertice2 = collider->GetVertices()[count2]; // Check to see if center is within polygon if (separation < FLT_EPSILON) { this->lastData.normal = (collider->GetMatrix() * collider->GerNormal()[faceNormal]); this->lastData.normal = this->lastData.normal * -1; this->lastData.contacts.push_back(this->lastData.normal * this->radius + this->GetPosition()); this->lastData.penetration = this->radius; return true; } // Determine which voronoi region of the edge center of circle lies within Vector2 centerVert1 = center - vertice1; Vector2 centerVert2 = center - vertice2; float dot1 = centerVert1.Dot(vertice2 - vertice1); float dot2 = centerVert2.Dot(vertice1 - vertice2); this->lastData.penetration = this->radius - separation; // Closest to v1 if (dot1 <= 0.0f) { if (center.distanceSqr(vertice1) > this->radius * this->radius) { return false; } Vector2 normal = vertice1 - center; normal = (collider->GetMatrix() * normal); normal = normal.normalize(); this->lastData.normal = normal; //vertice1 = collider->GetMatrix() * (vertice1 + collider->GetPosition()); -- TODO this->lastData.contacts.push_back(vertice1); } // Closest to v2 else if (dot2 <= 0.0f) { if (center.distanceSqr(vertice2) > this->radius * this->radius) { return false; } Vector2 normal = vertice2 - center; //vertice2 = collider->GetMatrix() * (vertice2 + collider->GetPosition()); -- TODO this->lastData.contacts.push_back(vertice2); this->lastData.normal = (collider->GetMatrix() * normal); this->lastData.normal = this->lastData.normal.normalize(); } // Closest to face else { Vector2 normal = collider->GerNormal()[faceNormal]; Vector2 centerVertice = center - vertice1; if (centerVertice.Dot(normal) > this->radius) { return false; } normal = collider->GetMatrix() * normal; this->lastData.normal = normal * -1; this->lastData.contacts.push_back((this->lastData.normal * this->radius) + this->GetPosition()); } return true; } return false; } HitData SphereCollider::CalcHitData(Collider * other) { if (other->GetType() == "SPHERE") { return this->HitDataSphere(other); } else if (other->GetType() == "BOX") { return this->HitDataBox(other); } else if (other->GetType() == "POLY") { return this->lastData; } } HitData SphereCollider::HitDataSphere(Collider * other) { HitData returnValue; returnValue.object = this; returnValue.other = other; if (SphereCollider* collider = dynamic_cast<SphereCollider*>(other)) { FalconeEngine::Vector2 posOther = collider->GetPosition(); FalconeEngine::Vector2 position = this->GetPosition(); FalconeEngine::Vector2 direction = posOther - position; float sumRadius = collider->GetRadius() + this->GetRadius(); sumRadius *= sumRadius; double deltaX = position.x - posOther.x; deltaX *= deltaX; double deltaY = position.y - posOther.y; deltaY *= deltaY; if (deltaX + deltaY <= sumRadius) { float dist = direction.length(); if (dist != 0) { returnValue.penetration = sumRadius - dist; returnValue.normal = direction / dist; returnValue.contacts.push_back(returnValue.normal * this->radius + this->parent->getPosition()); } else { returnValue.penetration = this->GetRadius(); returnValue.normal = FalconeEngine::Vector2::Up(); returnValue.contacts.push_back(this->GetPosition()); } } } return returnValue; } HitData SphereCollider::HitDataBox(Collider * other) { HitData returnValue; returnValue.object = this; returnValue.other = other; if (BoxCollider* collider = dynamic_cast<BoxCollider*>(other)) { FalconeEngine::Vector2 posOther = collider->GetPosition(); FalconeEngine::Vector2 position = this->GetPosition(); FalconeEngine::Vector2 direction = posOther - position; FalconeEngine::Vector2 closest = direction; float otherExtentX = (collider->GetMaxAABB().x - collider->GetMinAABB().x) / 2; float otherExtentY = (collider->GetMaxAABB().y - collider->GetMinAABB().y) / 2; closest.x = std::min(otherExtentX, std::max(closest.x, -otherExtentX)); closest.y = std::min(otherExtentY, std::max(closest.y, -otherExtentY)); bool inside = false; if (direction == closest) { inside = true; // Find closest axis if (std::abs(direction.x) > std::abs(direction.y)) { if (closest.x > 0) { closest.x = otherExtentX; } else { closest.x = -otherExtentX; } } else { // Clamp to closest extent if (closest.y > 0) { closest.y = otherExtentY; } else { closest.y = -otherExtentY; } } } FalconeEngine::Vector2 normal = direction - closest; float distance = normal.lengthSqrd(); float radius = this->GetRadius(); if (distance > radius * radius && !inside) { return returnValue; } distance = std::sqrt(distance); if (inside) { returnValue.normal = normal * -1;//normal * -1; returnValue.penetration = radius - distance; } else { returnValue.normal = normal; returnValue.penetration = radius - distance; } } return returnValue; } HitData SphereCollider::HitDataPoly(Collider * other) { this->CheckCollisionPoly(other); return this->lastData; } } }
true
d1f1899a2ad5c310253776e53f72908af3269ce1
C++
Gaston-Paz/GENERALA
/main.cpp
UTF-8
22,247
2.5625
3
[]
no_license
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; #include "funcionesNuestras.h" #include "rlutil.h" int modoDeDos (char jugador1[], char jugador2[], int &rondasGanador, int &puntajeGanador, char nombreGanador [], char nombreEmpate[],int &rondasPerdedor, int &puntajePerdedor, char nombrePerdedor[]); int modoDeUno(char jugador1 [], int &rondasGanador, char nombreGanador[], int &puntajeGanador); void titulo(); void dadoSeis(int x, int y); void dadoCinco(int x, int y); void dadoCuatro(int x, int y); void dadoTres(int x, int y); void dadoDos(int x, int y); void dadoUno(int x, int y); void puntuacionAlta (int rondasMasAlta, int rondasMasAlta1, int rondasMasAlta2, int puntajeMasAlta, int puntajeMasAlta1, int puntajeMasAlta2, char nombreMasAlta [], char nombreMasAlta1 [], char nombreMasAlta2 []); int main() { bool bandera = 0; int rondasPerdedor = 0, puntajePerdedor = 0, rondasGanador = 0, puntajeGanador = 0, rondasMasAlta = 11, puntajeMasAlta = 0,rondasMasAlta1 = 11, puntajeMasAlta1 = 0,rondasMasAlta2 = 11, puntajeMasAlta2 = 0; char nombreMasAlta [30]; char nombreMasAlta1 [30]; char nombreMasAlta2 [30]; char nombreGanador [30]; char nombreEmpate [30]{'-'}; //char empatados[30]; char nombrePerdedor [30]; //int tam = 3; char nombre1[30]; char nombre2[30]; int opcion, opcion2; titulo(); rlutil::setColor(rlutil::WHITE); rlutil::locate(30,15); rlutil::setColor(rlutil::MAGENTA); cout<<"[ENTER PARA INICIAR]"; rlutil::setColor(rlutil::BLACK); cout<<'\t'<<'\t'<<'\t'<<" "; system("pause"); system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-JUEGO NUEVO"<<endl; rlutil::setColor(rlutil::LIGHTGREEN); rlutil::locate(30,18); cout<<"2-PUNTUACION MAS ALTA"<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-CERRAR"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion; while((opcion != 1) && (opcion != 2) && (opcion != 3)){ rlutil::locate(30,23); cout<<"OPCION INCORRECTA"; rlutil::setColor(rlutil::BLACK); system("pause"); system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-JUEGO NUEVO"<<endl; rlutil::setColor(rlutil::LIGHTGREEN); rlutil::locate(30,18); cout<<"2-PUNTUACION MAS ALTA"<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-CERRAR"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion; } while(opcion){ system("cls"); switch(opcion){ case 1: system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-UN JUGADOR"<<endl; rlutil::locate(30,18); rlutil::setColor(rlutil::LIGHTGREEN); cout<<"2-DOS JUGADORES "<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-VOLVER ATRAS"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion2; while((opcion2 != 1) && (opcion2 != 2) && (opcion2 != 3)){ rlutil::locate(30,23); cout<<"OPCION INCORRECTA"; rlutil::setColor(rlutil::BLACK); system("pause"); system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-UN JUGADOR"<<endl; rlutil::locate(30,18); rlutil::setColor(rlutil::LIGHTGREEN); cout<<"2-DOS JUGADORES "<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-VOLVER ATRAS"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion2; } switch(opcion2){ case 1: system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"INGRESAR NOMBRE: "; rlutil::setColor(rlutil::WHITE); cin>>nombre1; cout<<endl; system("cls"); modoDeUno(nombre1, rondasGanador, nombreGanador, puntajeGanador); if(bandera == 0){ bandera = 1; rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); } else{if(rondasGanador < rondasMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasMasAlta; puntajeMasAlta1 = puntajeMasAlta; strcpy(nombreMasAlta1, nombreMasAlta); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); } else{if(rondasGanador == rondasMasAlta){ if(puntajeGanador > puntajeMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasMasAlta; puntajeMasAlta1 = puntajeMasAlta; strcpy(nombreMasAlta1, nombreMasAlta); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); }else{ if(rondasGanador < rondasMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador == rondasMasAlta1){ if(puntajeGanador > puntajeMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}}}}} } } else{ if(rondasGanador < rondasMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador == rondasMasAlta1){ if(puntajeGanador > puntajeMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}}}} else{ if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}} }} }}} break; case 2: system("cls"); titulo(); rlutil::locate(21,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"INGRESAR NOMBRE DEL JUGADOR 1: "; rlutil::setColor(rlutil::WHITE); cin>>nombre1; system("cls"); titulo(); rlutil::locate(21,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"INGRESAR NOMBRE DEL JUGADOR 2: "; rlutil::setColor(rlutil::WHITE); cin>>nombre2; cout<<endl; system("cls"); modoDeDos(nombre1, nombre2, rondasGanador, puntajeGanador, nombreGanador, nombreEmpate, rondasPerdedor, puntajePerdedor, nombrePerdedor); if(bandera == 0){ bandera = 1; rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); if(nombreEmpate[0] != '-'){ rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreEmpate); } } else{ if(nombreEmpate[0] != '-'){ if(rondasGanador < rondasMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreEmpate); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); } else{if(rondasGanador == rondasMasAlta){ if(puntajeGanador > puntajeMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreEmpate); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); }else{if(rondasGanador < rondasMasAlta1){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreEmpate); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador == rondasMasAlta1){ if(puntajeGanador > puntajeMasAlta1){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreEmpate); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}}}}}}}}} else{if(rondasGanador < rondasMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasMasAlta; puntajeMasAlta1 = puntajeMasAlta; strcpy(nombreMasAlta1, nombreMasAlta); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); } else{if(rondasGanador == rondasMasAlta){ if(puntajeGanador > puntajeMasAlta){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasMasAlta; puntajeMasAlta1 = puntajeMasAlta; strcpy(nombreMasAlta1, nombreMasAlta); rondasMasAlta = rondasGanador; puntajeMasAlta = puntajeGanador; strcpy(nombreMasAlta, nombreGanador); }else{ if(rondasGanador < rondasMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador == rondasMasAlta1){ if(puntajeGanador > puntajeMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}}}}} } } else{ if(rondasGanador < rondasMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador == rondasMasAlta1){ if(puntajeGanador > puntajeMasAlta1){ rondasMasAlta2 = rondasMasAlta1; puntajeMasAlta2 = puntajeMasAlta1; strcpy(nombreMasAlta2, nombreMasAlta1); rondasMasAlta1 = rondasGanador; puntajeMasAlta1 = puntajeGanador; strcpy(nombreMasAlta1, nombreGanador); } else{if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}}}} else{ if(rondasGanador < rondasMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); } else{if(rondasGanador == rondasMasAlta2){ if(puntajeGanador > puntajeMasAlta2){ rondasMasAlta2 = rondasGanador; puntajeMasAlta2 = puntajeGanador; strcpy(nombreMasAlta2, nombreGanador); }}} }} }}} nombreEmpate[0]='-'; break; case 3: break; default:cout<<"Opcion incorrecta"<<endl; break; }} break; case 2: puntuacionAlta (rondasMasAlta, rondasMasAlta1, rondasMasAlta2, puntajeMasAlta, puntajeMasAlta1, puntajeMasAlta2, nombreMasAlta, nombreMasAlta1, nombreMasAlta2); ///variable de la puntuacion break; case 3:return 0; break; default:cout<<"OPCION INCORRECTA"<<endl; break; } system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-JUEGO NUEVO"<<endl; rlutil::setColor(rlutil::LIGHTGREEN); rlutil::locate(30,18); cout<<"2-PUNTUACION MAS ALTA"<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-CERRAR"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion; while((opcion != 1) && (opcion != 2) && (opcion != 3)){ rlutil::locate(30,23); cout<<"OPCION INCORRECTA"; rlutil::setColor(rlutil::BLACK); system("pause"); system("cls"); titulo(); rlutil::locate(30,15); rlutil::setColor(rlutil::LIGHTCYAN); cout<<"1-JUEGO NUEVO"<<endl; rlutil::setColor(rlutil::LIGHTGREEN); rlutil::locate(30,18); cout<<"2-PUNTUACION MAS ALTA"<<endl; rlutil::locate(30,21); rlutil::setColor(rlutil::LIGHTMAGENTA); cout<<"3-CERRAR"<<endl; rlutil::locate(30,23); rlutil::setColor(rlutil::WHITE); cin>>opcion; } } return 0; }
true
6928331c9fedc11c61a18b896243f34e196372c4
C++
admirf/StreamCapture
/StreamCapture/main.cpp
UTF-8
2,458
2.59375
3
[]
no_license
#include <IPv4Layer.h> #include <Packet.h> #include <PcapLiveDeviceList.h> #include <SSLLayer.h> #include <PlatformSpecificUtils.h> #include <iostream> #include "NetflixHandler.h" using namespace std; string getProtocolTypeAsString(pcpp::ProtocolType); static void onPacketArrives(pcpp::RawPacket*, pcpp::PcapLiveDevice*, void*); int main() { std::string interfaceIPAddr = "192.168.0.13"; pcpp::PcapLiveDevice* dev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIPAddr.c_str()); if (dev == nullptr) { cout << "Cannot find interface with IPv4 address of " << interfaceIPAddr << endl; return 1; } if (!dev->open()) { cout << "Cannot open device\n"; return 1; } cout << "Starting capture on: " << interfaceIPAddr << endl; vector<strcap::IPacketHandler*> handlers; handlers.push_back(new strcap::NetflixHandler()); dev->startCapture(onPacketArrives, &handlers); PCAP_SLEEP(60); dev->stopCapture(); for (auto& handler : handlers) { delete handler; } return 0; } void onPacketArrives(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie) { auto handlers = static_cast<vector<strcap::IPacketHandler*>*>(cookie); pcpp::Packet parsedPacket(packet); for (auto& handler : *handlers) { handler->handle(parsedPacket); } /* for (auto curLayer = parsedPacket.getFirstLayer(); curLayer != nullptr; curLayer = curLayer->getNextLayer()) { auto type = getProtocolTypeAsString(curLayer->getProtocol()); if (type == "SSL") { auto ssl = parsedPacket.getLayerOfType<pcpp::SSLLayer>(); if (ssl->getRecordType() == pcpp::SSL_HANDSHAKE) { cout << "Test\n"; auto handshake = dynamic_cast<pcpp::SSLHandshakeLayer*>(ssl); auto clientMessage = handshake->getHandshakeMessageOfType<pcpp::SSLClientHelloMessage>(); if (clientMessage != nullptr) { for (short i = 0; i < clientMessage->getExtensionCount(); ++i) { auto ext = clientMessage->getExtension(i); auto ptr = ext->getData(); for (short j = 0; j < ext->getLength(); ++j) cout << (char) * (ptr + j); cout << endl; } } } } }*/ } std::string getProtocolTypeAsString(pcpp::ProtocolType protocolType) { switch (protocolType) { case pcpp::Ethernet: return "Ethernet"; case pcpp::IPv4: return "IPv4"; case pcpp::TCP: return "TCP"; case pcpp::HTTPRequest: case pcpp::SSL: return "SSL"; case pcpp::HTTPResponse: return "HTTP"; default: return "Unknown"; } }
true
f972a3bf031f2864aae0daf4f46408e82b660192
C++
lesharris/chipbit
/src/loaders/ShaderLoader.cpp
UTF-8
1,243
2.75
3
[]
no_license
#include "ShaderLoader.h" #include <string> #include <fstream> #include <sstream> #include "../core/Log.h" std::shared_ptr<Chipbit::Shader> Chipbit::ShaderLoader::load(const std::string& vertexPath, const std::string& fragmentPath) { auto shader = std::make_shared<Shader>(); std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { // open files vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // read file's buffer contents into streams vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); // close file handlers vShaderFile.close(); fShaderFile.close(); // convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (std::ifstream::failure &e) { CB_ERROR("ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ"); } shader->SetVertexSource(vertexCode); shader->SetFragmentSource(fragmentCode); shader->Compile(); return shader; }
true
9704b9b429e4ecd4eb0ae6b2009302c078b38dd7
C++
UniqueCoff/Homework1
/3 week/Tabylirovanie 2n.cpp
UTF-8
585
3.171875
3
[]
no_license
#include <iostream> #include <iomanip> int main() { int a, b; std::cout << "Enter Interval" << std::endl; std::cin >> a; std::cin >> b; float X; std::cout << "Solve function. \nEnter X: "; std::cin >> X; std::cout << "\tx\t\ty" << std::endl; float x = a; std::cout.precision(5); while (x < b) { float f = sqrt(2+3*x)+ 72*x+tan(4*x+31); std::cout << "\t" << x << "\t\t" << f << std::endl; x += X; } return 0; }
true
7c4415114d2ccc2890aa6610772a2e66273740f4
C++
jpbream/3D-Engine
/3DEngine/Mat.h
UTF-8
1,049
3.03125
3
[]
no_license
#pragma once #include <iostream> #include "Vec2.h" #include "Vec3.h" #include "Vec4.h" class Mat { private: int rows; int cols; double* data; public: Mat(int r, int c); Mat(Mat&&); Mat& operator=(Mat&&); ~Mat(); int NumRows() const { return rows; } int NumCols() const { return cols; } double operator()(int r, int c) const; double& operator()(int r, int c); Mat operator*(double s); Mat& operator*=(double s); Mat operator*(const Mat& m) const; Vec2 operator*(const Vec2&) const; Vec3 operator*(const Vec3&) const; Vec4 operator*(const Vec4&) const; Mat Transpose(); static Mat RotX(double theta); static Mat RotY(double theta); static Mat RotZ(double theta); static Mat Translation(const Vec4& v); //static Mat Frustum(double n, double f, double l, double r, double t, double b); static Mat Frustum(double n, double f, double fov, double ar); static Mat Orthographic(double n, double f, double t, double b, double l, double r); friend std::ostream& operator<<(std::ostream& os, const Mat& m); };
true
2e6e2c8947ab81d81db639323dab67f287c71568
C++
zhzc1202/CppLearning
/Cpp/Day1/无所谓叫什么名字的main.cpp
UTF-8
1,031
2.59375
3
[]
no_license
// // main.cpp // Day1 // // Created by Jason's Macbook on 8/21/19. // Copyright © 2019 Jason's Macbook. All rights reserved. // #include <iostream> //不是每个程序都必须写 //C语言所有的函数要求先声明再使用 int main() //入口函数,一个程序只能有一个 { printf("hello world!!!\n"); //打印函数 return 0; } void func() { } void foo() { } //三角号代表warring 和 error //IDE:integrated development environment 集成开发环境,一般引入了一个概念,叫工程 //主要文件就是.c,其余的是工程文件,可以更好的管理工程 //Qt 读作 Cute //从源文件到可执行文件,经历了什么? //linux --- main.c a.out //windows --- main.c xxx.exe //gcc -E main.x -o main.i 预处理 //gcc -S main.i -o main.s 编译 //gcc -c main.s -o main.o 汇编 //gcc main.o -o hello 链接 //单行注释 /*多行注释,不支持嵌套 asdasd asdasd */ // 用条件编译的方式实现多行注释 #if 0 asdfsadf sadfsdafsdaf #endif
true
bd7971bd20bf010cc5429d7b4e8417aff6bc0670
C++
rnburn/portfolio
/nearby.cpp
UTF-8
21,249
2.859375
3
[]
no_license
#include <iostream> #include <vector> #include <cassert> #include <memory> #include <cmath> #include <set> #include <algorithm> #include <limits> typedef uint32_t id_type; typedef id_type index_type; typedef std::vector<index_type> IndexMap; typedef std::vector<id_type> OrderedQuestionList; typedef std::vector<OrderedQuestionList> TopicQuestionMap; const size_t MAX_ID = 1e5; const size_t MAX_QUESTIONS = 1e3; const double EQUALITY_THRESHOLD = .001; const size_t MAX_RESULTS_PER_QUERY=100; struct Topic { id_type id; double x,y; }; struct QuoraData { QuoraData(id_type ntopics, id_type nquestions, id_type nqueries_) : topics(ntopics), topic_index_map(MAX_ID+1), question_index_map(MAX_ID+1), topic_question_map(ntopics), nqueries(nqueries_), num_question_linked_topics(0) {} std::vector<Topic> topics; IndexMap topic_index_map; IndexMap question_index_map; TopicQuestionMap topic_question_map; size_t nqueries, num_question_linked_topics; }; inline bool return_first(double d1sq, id_type id1, double d2sq, id_type id2) { return d1sq < d2sq || (!(d2sq<d1sq) && id1>id2); } typedef std::pair<double, id_type> Resultant; struct ResultantComparison { bool operator()(const Resultant& lhs, const Resultant& rhs) const { return return_first(rhs.first, rhs.second, lhs.first, lhs.second); } }; struct ResultantIdComparison { bool operator()(const Resultant& lhs, const Resultant& rhs) const { return lhs.second < rhs.second; } }; typedef std::multiset<Resultant, ResultantComparison> OrderedResultList; /** * Returns the lowest ranked entity in <results> */ inline OrderedResultList::iterator find_worst(OrderedResultList& results, double greatest_distance) { double bound = std::max(greatest_distance - EQUALITY_THRESHOLD, 0.0); bound *= bound; auto i = results.begin(); auto last = results.end(); id_type worst_id = i->second; auto worst_iter = i; ++i; for(; i!=last; ++i) { if(i->first >= bound) { id_type id = i->second; if(id < worst_id) { worst_id = id; worst_iter = i; } } else { break; } } return worst_iter; } inline double compute_distancesq(double x1, double y1, double x2, double y2) { double deltax = x2 - x1; double deltay = y2 - y1; return deltax*deltax+deltay*deltay; } /****************************************************************************** * Reading Input *****************************************************************************/ double read_position() { double res; std::cin >> res; return res; } void read_counts(size_t& ntopics, size_t& nquestions, size_t& nqueries) { std::cin >> ntopics >> nquestions >> nqueries; assert(nquestions <= MAX_QUESTIONS); } void read_topics(std::vector<Topic>& topics, IndexMap& index_map) { for(id_type i=0; i<topics.size(); ++i) { Topic& topic = topics[i]; std::cin >> topic.id; assert(topic.id <= MAX_ID); topic.x = read_position(); topic.y = read_position(); index_map[topic.id] = i; } } void read_questions(size_t nquestions, const IndexMap& topic_index_map, IndexMap& question_index_map, TopicQuestionMap& topic_question_map, size_t& num_question_linked_topics) { for(index_type i=0; i<nquestions; ++i) { id_type qid; size_t ntopics; std::cin >> qid; std::cin >> ntopics; assert(ntopics <= 10); assert(qid <= MAX_ID); question_index_map[qid] = i; for(size_t j=0; j<ntopics; ++j) { id_type tid; std::cin >> tid; TopicQuestionMap::value_type& qset = topic_question_map[topic_index_map[tid]]; if(qset.empty()) ++num_question_linked_topics; qset.push_back(qid); } } // Since the questions will be iterated through repeatedly, it's best to use a sorted // vector for storage since it's elements can be traversed much faster than a set for(auto& qset : topic_question_map) std::sort(qset.begin(), qset.end(), std::greater<id_type>()); } QuoraData read_quora_data() { size_t ntopics, nquestions, nqueries; read_counts(ntopics, nquestions, nqueries); QuoraData qdata(ntopics, nquestions, nqueries); read_topics(qdata.topics, qdata.topic_index_map); read_questions(nquestions, qdata.topic_index_map, qdata.question_index_map, qdata.topic_question_map, qdata.num_question_linked_topics); return qdata; } /****************************************************************************** * K-D Tree Data Structure / Algorithms *****************************************************************************/ class KDTree { /** * The k-d tree makes use of templated doubly recursive functions that are * specific to each axis orientation. This allows us to avoid storing and * conditioning on the axis orientation for each node. */ public: template<class RandomAccessIterator> KDTree(RandomAccessIterator first, RandomAccessIterator last); template<class Visitor> void branch_and_bound(Visitor& v, double x, double y) const; private: KDTree(const KDTree&); //no copy KDTree& operator=(const KDTree&); //no assignment static const int X_AXIS=0; enum class_t { LEAF=0, LEFT_CHILD, RIGHT_CHILD, BOTH_CHILDREN }; struct Node { Topic point; class_t type; std::unique_ptr<Node> left, right; }; std::unique_ptr<Node> root; static constexpr int other_axis(int axis) { return (axis+1) % 2; } template<int> struct Comparison { bool operator()(const Topic& lhs, const Topic& rhs); }; template<class Visitor> void examine(Visitor& v, const Topic& t, double x, double y) const; template<class RandomAccessIterator, int Axis> std::unique_ptr<Node> create_kd_tree(RandomAccessIterator first, RandomAccessIterator last); template<class Visitor, int Axis> void branch_and_bound(const Node* node, Visitor& v, double x, double y) const; template<class Visitor, int Axis> void branch_and_bound_both(const Node* node, Visitor& v, double x, double y) const; }; /*** Comparison */ template<> struct KDTree::Comparison<0> { bool operator()(const Topic& lhs, const Topic& rhs) { return lhs.x < rhs.x; } }; template<> struct KDTree::Comparison<1> { bool operator()(const Topic& lhs, const Topic& rhs) { return lhs.y < rhs.y; } }; /*** compute_delta */ template<int Axis> inline double compute_delta(double x1, double y1, double x2, double y2); template<> inline double compute_delta<0>(double x1, double y1, double x2, double y2) { return x2 - x1; } template<> inline double compute_delta<1>(double x1, double y1, double x2, double y2) { return y2 - y1; } /*** create_kd_tree */ template<class RandomAccessIterator> KDTree::KDTree(RandomAccessIterator first, RandomAccessIterator last) { root = create_kd_tree<RandomAccessIterator, X_AXIS>(first, last); } template<class RandomAccessIterator, int Axis> std::unique_ptr<KDTree::Node> KDTree::create_kd_tree(RandomAccessIterator first, RandomAccessIterator last) { if(first == last) return std::unique_ptr<Node>(); std::unique_ptr<Node> tree(new Node()); size_t n = last - first; if(n == 1) { tree->point = *first; tree->type=LEAF; return tree; } RandomAccessIterator median = first+n / 2; assert(first < median && median < last); nth_element(first, median, last, Comparison<Axis>()); tree->point = *median; tree->left = create_kd_tree<RandomAccessIterator, other_axis(Axis)>(first, median); tree->right = create_kd_tree<RandomAccessIterator, other_axis(Axis)>(median+1, last); if(!tree->left.get()) tree->type = RIGHT_CHILD; else if(!tree->right.get()) tree->type = LEFT_CHILD; else tree->type = BOTH_CHILDREN; return tree; } /*** branch_and_bound */ template<class Visitor, int Axis> inline void KDTree::branch_and_bound_both(const Node* node, Visitor& v, double x, double y) const { double delta1 = compute_delta<Axis>(node->point.x, node->point.y, x, y); double delta1sq = delta1*delta1; if(delta1 > 0) { branch_and_bound<Visitor, other_axis(Axis)>(node->right.get(), v, x, y); if(v.bound_check(delta1sq)) { double delta2 = compute_delta<other_axis(Axis)>(node->point.x, node->point.y, x, y); double dsq = delta1sq+delta2*delta2; v.examine(dsq, node->point.id); branch_and_bound<Visitor, other_axis(Axis)>(node->left.get(), v, x, y); } } else { branch_and_bound<Visitor, other_axis(Axis)>(node->left.get(), v, x, y); if(v.bound_check(delta1sq)) { double delta2 = compute_delta<other_axis(Axis)>(node->point.x, node->point.y, x, y); double dsq = delta1sq+delta2*delta2; v.examine(dsq, node->point.id); branch_and_bound<Visitor, other_axis(Axis)>(node->right.get(), v, x, y); } } } template<class Visitor> inline void KDTree::examine(Visitor& v, const Topic& t, double x, double y) const { double dsq = compute_distancesq(t.x, t.y, x, y); v.examine(dsq, t.id); } template<class Visitor, int Axis> void KDTree::branch_and_bound(const Node* node, Visitor& v, double x, double y) const { switch(node->type) { case LEAF: examine(v, node->point, x, y); break; case LEFT_CHILD: examine(v, node->left->point, x, y); examine(v, node->point, x, y); break; case RIGHT_CHILD: examine(v, node->right->point, x, y); examine(v, node->point, x, y); break; case BOTH_CHILDREN: branch_and_bound_both<Visitor, Axis>(node, v, x, y); break; } } template<class Visitor> inline void KDTree::branch_and_bound(Visitor& v, double x, double y) const { if(root.get()) branch_and_bound<Visitor, X_AXIS>(root.get(), v, x, y); } /****************************************************************************** * Outputing Results *****************************************************************************/ inline bool output_first(double d1, id_type id1, double d2, id_type id2) { return (d1-d2 <= EQUALITY_THRESHOLD) && (id1 > id2); } inline void insert_resultant(Resultant* xs, size_t i, double dsq, id_type id) { double d = std::sqrt(dsq); xs[i].first = d; xs[i].second = id; while(i > 0 && output_first(d, id, xs[i-1].first, xs[i-1].second)) { std::swap(xs[i-1], xs[i]); --i; } } /** * If the location data is uniformly random, then it's unlikely that * the output order will differ from the ordering used in the visitor * classes, so I can safely use insertion which runs efficiently for * already sorted data. * * I assume that the ranking order is transitive for all input given * (this isn't true in general) so that each query will have a unique, * correct solution. */ template<class RandomAccessIterator> void output_results(RandomAccessIterator first, RandomAccessIterator last) { if(first == last) { std::cout << std::endl; return; } Resultant xs[MAX_RESULTS_PER_QUERY]; size_t nresults=0; for(; first!=last; ++first) { insert_resultant(xs, nresults++, first->first, first->second); } std::cout << xs[0].second; for(size_t i=1; i<nresults; ++i) std::cout << " " << xs[i].second; std::cout << std::endl; } /****************************************************************************** * Topic Visitor *****************************************************************************/ class TopicVisitor { public: TopicVisitor(size_t nresults_) : nresults(0), max_results(nresults_), distancesq_bound(std::numeric_limits<double>::max()), greatest_distance(std::numeric_limits<double>::max()), greatest_distancesq(std::numeric_limits<double>::max()) {} bool bound_check(double bound) const; void examine(const Topic& t); void examine(double dsq, id_type id); void write_output(); private: void set_bound(); void pop_worst(); OrderedResultList results; size_t nresults; size_t max_results; double distancesq_bound, greatest_distance, greatest_distancesq; }; inline void TopicVisitor::write_output() { output_results(results.rbegin(), results.rend()); } inline bool TopicVisitor::bound_check(double bound) const { return bound <= distancesq_bound; } inline void TopicVisitor::set_bound() { double new_greatest_distancesq = results.begin()->first; if(new_greatest_distancesq == greatest_distancesq) return; else greatest_distancesq = new_greatest_distancesq; greatest_distance = std::sqrt(greatest_distancesq); double x = greatest_distance + EQUALITY_THRESHOLD; distancesq_bound = x*x; } inline void TopicVisitor::pop_worst() { OrderedResultList::iterator i = find_worst(results, greatest_distance); results.erase(i); set_bound(); } inline void TopicVisitor::examine(double dsq, id_type id) { if(nresults < max_results) { Resultant elem(dsq, id); results.insert(elem); ++nresults; if(nresults == max_results) set_bound(); } else if(dsq <= distancesq_bound) { Resultant elem(dsq, id); results.insert(elem); pop_worst(); } } /****************************************************************************** * Question Visitor *****************************************************************************/ class QuestionVisitor { public: QuestionVisitor(const IndexMap& tindex_, const IndexMap& qindex_, const TopicQuestionMap& qlist_, size_t max_results_) : tindex(tindex_), qindex(qindex_), qlist(qlist_), nresults(0), max_results(max_results_), qiter_map(MAX_QUESTIONS, results.end()), distancesq_bound(std::numeric_limits<double>::max()), greatest_distance(std::numeric_limits<double>::max()), greatest_distancesq(std::numeric_limits<double>::max()) {} bool bound_check(double dsq) const; void examine(double dsq, id_type id); void write_output(); private: const IndexMap& tindex; const IndexMap& qindex; const TopicQuestionMap& qlist; typedef std::vector<OrderedResultList::iterator> QuestionMap; OrderedResultList results; QuestionMap qiter_map; size_t nresults; size_t max_results; double distancesq_bound, greatest_distance, greatest_distancesq; void insert_element(double dsq, id_type id); bool insert_remove_element(double dsq, id_type id); void insert_range(double dsq, OrderedQuestionList::const_iterator first, OrderedQuestionList::const_iterator last); void insert_remove_range(double dsq, OrderedQuestionList::const_iterator first, OrderedQuestionList::const_iterator last); void set_bound(); id_type pop_worst(); }; inline bool QuestionVisitor::bound_check(double bound) const { return bound <= distancesq_bound; } inline void QuestionVisitor::set_bound() { double new_greatest_distancesq = results.begin()->first; if(new_greatest_distancesq == greatest_distancesq) return; else greatest_distancesq = new_greatest_distancesq; greatest_distance = std::sqrt(greatest_distancesq); double x = greatest_distance + EQUALITY_THRESHOLD; distancesq_bound = x*x; } inline id_type QuestionVisitor::pop_worst() { OrderedResultList::iterator i = find_worst(results, greatest_distance); id_type id = i->second; results.erase(i); qiter_map[qindex[id]] = results.end(); return id; } inline void QuestionVisitor::insert_element(double dsq, id_type id) { OrderedResultList::iterator& i = qiter_map[qindex[id]]; Resultant elem(dsq, id); if(i != results.end()) { if(i->first < dsq) return; results.erase(i); i = results.insert(elem); } else { ++nresults; i = results.insert(elem); } } inline bool QuestionVisitor::insert_remove_element(double dsq, id_type id) { OrderedResultList::iterator& i = qiter_map[qindex[id]]; Resultant elem(dsq, id); if(i != results.end()) { if(i->first < dsq) return true; results.erase(i); i = results.insert(elem); return true; } else { i = results.insert(elem); if(pop_worst() == id) return false; else return true; } } inline void QuestionVisitor::insert_range(double dsq, OrderedQuestionList::const_iterator first, OrderedQuestionList::const_iterator last) { for(; first!=last; ++first) { insert_element(dsq, *first); if(nresults == max_results) { ++first; insert_remove_range(dsq, first, last); return; } } } inline void QuestionVisitor::insert_remove_range(double dsq, OrderedQuestionList::const_iterator first, OrderedQuestionList::const_iterator last) { for(; first!=last; ++first) { if(!insert_remove_element(dsq, *first)) { return; } } } inline void QuestionVisitor::examine(double dsq, id_type id) { if(nresults < max_results) { const TopicQuestionMap::value_type& qset = qlist[tindex[id]]; insert_range(dsq, qset.begin(), qset.end()); if(nresults == max_results) { set_bound(); } } else if(dsq <= distancesq_bound) { const TopicQuestionMap::value_type& qset = qlist[tindex[id]]; insert_remove_range(dsq, qset.begin(), qset.end()); set_bound(); } } inline void QuestionVisitor::write_output() { output_results(results.rbegin(), results.rend()); } /****************************************************************************** * Query Processor *****************************************************************************/ void process_topic_query(const KDTree& kdtree, size_t nresults, double x, double y) { TopicVisitor v(nresults); kdtree.branch_and_bound(v, x, y); v.write_output(); } void process_question_query(const QuoraData& qdata, const KDTree& kdtree, size_t nresults, double x, double y) { QuestionVisitor v(qdata.topic_index_map, qdata.question_index_map, qdata.topic_question_map, nresults); kdtree.branch_and_bound(v, x, y); v.write_output(); } inline void process_query(const QuoraData& qdata, const KDTree& topic_tree, const KDTree& question_tree) { char c; size_t nresults; double x,y; std::cin >> c >> nresults; x = read_position(); y = read_position(); assert(nresults <= 100); if(nresults == 0) { std::cout << std::endl; return; } if(c == 't') process_topic_query(topic_tree, nresults, x, y); if(c == 'q') process_question_query(qdata, question_tree, nresults, x, y); } inline void process_queries(const QuoraData& qdata, const KDTree& topic_tree, const KDTree& question_tree, size_t nqueries) { for(size_t i=0; i<qdata.nqueries; ++i) process_query(qdata, topic_tree, question_tree); } /****************************************************************************** * Main *****************************************************************************/ inline std::vector<Topic> filter_topics(const std::vector<Topic>& topics, const IndexMap& topic_index_map, const TopicQuestionMap& topic_question_map, size_t num_question_linked_topics) { std::vector<Topic> res; res.reserve(num_question_linked_topics); auto filter = [&](const Topic& t) { index_type index = topic_index_map[t.id]; return !topic_question_map[index].empty(); }; std::copy_if(topics.begin(), topics.end(), std::back_inserter(res), filter); return res; } int main() { QuoraData qdata = read_quora_data(); KDTree topic_tree(qdata.topics.begin(), qdata.topics.end()); // for question queries, a k-d tree indexed on all topics will // perform poorly if most topics are not associated with questions; // hence, i create a separate k-d tree of only question linked topics // for this case if(qdata.num_question_linked_topics == qdata.topics.size()) { process_queries(qdata, topic_tree, topic_tree, qdata.nqueries); } else { std::vector<Topic> filtered_topics = filter_topics(qdata.topics, qdata.topic_index_map, qdata.topic_question_map, qdata.num_question_linked_topics); KDTree question_tree(filtered_topics.begin(), filtered_topics.end()); process_queries(qdata, topic_tree, question_tree, qdata.nqueries); } return 0; }
true
425cc326984b37d6aa882e7227ad9ed080b6c530
C++
akrabulislam/UVA
/10006.cpp
UTF-8
1,023
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool mark[70000]; #define lli long long int inline lli bigmod(lli a,lli b,lli m) {if(b==0)return 1%m;lli x=bigmod(a,b/2,m);x=(x*x)%m;if(b%2==1){x=(x*a)%m;}return x;} void sieve(int n){ memset(mark,true,sizeof(mark)); mark[1]=mark[0]=false; for(int i=2; i*i<=n; i++){ if(mark[i]==true){ for(int j=i+i; j<=n; j+=i){ mark[j]=false; } } } } int main(){ sieve(70000); int n; while(scanf("%d",&n)&&n){ if(mark[n]){ printf("%d is normal.\n",n); continue; } bool ok=true; for(int i=2; i<n; i++){ if(bigmod(i,n,n)!=i){ ok=false; break; } } if(ok){ printf("The number %d is a Carmichael number.\n",n); } else{ printf("%d is normal.\n",n); } } return 0; }
true
6a3572fe0570f0824cefe34e9fbfecdd2b805d44
C++
alexandraback/datacollection
/solutions_5630113748090880_1/C++/HowardChung/B.cpp
UTF-8
656
2.515625
3
[]
no_license
#include <stdio.h> #include <string.h> int main() { freopen("B-large.in","r",stdin); freopen("aout.txt","w",stdout); int T; scanf("%d",&T); for(int cases = 1; cases <= T; cases++) { int cnt[2510]; memset(cnt,0,sizeof(cnt)); int n; scanf("%d",&n); for(int i = 0; i < (2*n-1)*n; i++) { int x; scanf("%d",&x); cnt[x]++; } printf("Case #%d:",cases); for(int i = 1; i <= 2500; i++) if( cnt[i]%2 != 0 ) printf(" %d",i); puts(""); } return 0; }
true