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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
6f91ed28b0e95b3260c72cc1b02529f5ec528d75 | C++ | Xewar313/Wizardly | /Project1/Barrier.cpp | UTF-8 | 434 | 2.671875 | 3 | [] | no_license | #include "Barrier.h"
#include "Board.h"
#include "Projectile.h"
#include "BarrierEntity.h"
Barrier::Barrier()
{
avaliable = false;
cooldown = 100;
weaponColor = Color(230, 230, 0);
minCooldown = 50;
}
void Barrier::attack(Board& board, Entity& src)
{
if (board.getTime() - src.getLastShootTime() >= std::max(cooldown - src.getAttackSpeed(), 10))
{
board.addEntity(new BarrierEntity(src, &board));
src.startCooldown();
}
} | true |
98ac09e70357cb27c2c5ea88497ab317d6308955 | C++ | ishubhoshaha/Programming-Interview | /Backtracking/sudoku.cpp | UTF-8 | 2,776 | 3.375 | 3 | [] | no_license | /*
*Find empty cell
* If there are no empty cells, return true, problem solved.
* For every empty cell try digit from 1 to 9
* a) If the cell is safe for digit at grid[row][col]
* grid[row][col]=number and recursively try and fill in rest of the grid
* b) If recursion successful, return true
* c) Else, undo the selection, cell[row][col]=0 and try another
* If all numbers are tried and solution not found, return false
*/
#include<bits/stdc++.h>
using namespace std;
bool isempty(int grid[][9],int row,int col){
if (grid[row][col]==0){
return true;
}
else
return false;
}
pair<int,int> EmptyCell(int grid[][9]){
for(int i = 0;i<9;i++){
for(int j = 0;j<9;j++){
if(isempty(grid,i,j)){
return make_pair(i,j);
}
}
}
return make_pair(-1,-1);
}
bool isUsedinRow(int grid[][9],int row,int item){
for(int i = 0;i<9;i++){
if(grid[row][i]==item)
return true;
}
return false;
}
bool isUsedinColumn(int grid[][9],int col,int item){
for(int i = 0;i<9;i++){
if(grid[i][col]==item)
return true;
}
return false;
}
bool isUsedinGrid(int grid[][9],int row, int col,int item){ ///tricky of this problem is to select this start row and col
for(int i = row;i<row+3;i++){
for(int j = col;j<col+3;j++)
if(grid[i][j]==item)
return true;
}
return false;
}
bool solve(int grid[][9]){
pair<int,int>emptycell = EmptyCell(grid);
int r = emptycell.first,c = emptycell.second;
if(r==-1) return true;
for(int i = 1;i<=9;i++){
int item = i;
// if(r==0 and c = 8)
if(!isUsedinColumn(grid,c,item) and !isUsedinRow(grid,r,item) and !isUsedinGrid(grid,r-r%3,c-c%3,item)){
//cout<<r<<" "<<c<<" "<<item<<endl;
grid[r][c] = item;
if(solve(grid))
return true;
grid[r][c] = 0;
}
}
return false;
}
int main(){
int grid[][9] = {
{ 5, 3, 0, 0, 7, 0, 0, 0, 0 },
{ 6, 0, 0, 1, 9, 5, 0, 0, 0 },
{ 0, 9, 8, 0, 0, 0, 0, 6, 0 },
{ 8, 0, 0, 0, 6, 0, 0, 0, 3 },
{ 4, 0, 0, 8, 0, 3, 0, 0, 1 },
{ 7, 0, 0, 0, 2, 0, 0, 0, 6 },
{ 0, 6, 0, 0, 0, 0, 2, 8, 0 },
{ 0, 0, 0, 4, 1, 9, 0, 0, 5 },
{ 0, 0, 0, 0, 8, 0, 0, 7, 9 } };
if(solve(grid)){
cout<<"bingo! got solution"<<endl;
for(int i = 0;i<9;i++){
for(int j = 0;j<9;j++){
cout<<grid[i][j]<<" ";
}
cout<<endl;
}
}
else{
cout<<"No solution found";
}
}
| true |
ac254a411400c958a77e91f5ce7420e5b6310db4 | C++ | zgjstudy/DataStructures | /common/hashsim.cpp | UTF-8 | 2,111 | 3.375 | 3 | [] | no_license | // From the software distribution accompanying the textbook
// "A Practical Introduction to Data Structures and Algorithm Analysis,
// Third Edition (C++)" by Clifford A. Shaffer.
// Source code Copyright (C) 2007-2011 by Clifford A. Shaffer.
#include "book.h"
int main(int argc, char** argv)
{
if (argc != 3)
{
cout << "Usage: hashsim <#_of_records> <#_of_iterations>\n";
return -1;
}
int recs = atoi(argv[1]);
int iterations = atoi(argv[2]);
srand(1);
int hashtable[2 * recs]; // This is the pseudo hash table, twice the # of records
// Data collecting variables
int maxlen = 0; // Maximum length of any chain, ever
int avglen = 0; // Average for the maximum (per iteration) chain length
int minslots = (2 * recs); // Minimum slots used by any interation
int avgslots = 0; // Average number of slots used per iteration
for (int i = 0; i < iterations; i++)
{
int j;
int slots = 0;
int len = 0;
// Intialize the table for this iteration
for (j = 0; j < (2 * recs); j++)
hashtable[j] = 0;
// "insert" records into the hash table
for (j = 0; j < recs; j++)
{
int homeslot = rand() % (2 * recs);
if (homeslot > (2 * recs)) cout << "ERROR\n";
hashtable[homeslot]++; // Imagine that we are inserting here, bump the count
}
// Update the statistics
for (j = 0; j < (2 * recs); j++)
{
if (hashtable[j] > maxlen) maxlen = hashtable[j]; // longest chain ever
if (hashtable[j] > len) len = hashtable[j]; // longest chain this iteration
if (hashtable[j] > 0) slots++; // Something hit this slot
}
if (slots < minslots)
minslots = slots;
avglen += len;
avgslots += slots;
}
// Calculate the final statistics
cout << "For " << iterations << " iterations on " << recs << " records\n";
cout << "The longest chain ever generated was " << maxlen << endl;
cout << "The average length for the maximum chain was "
<< ((double)avglen) / ((double)iterations) << endl;
cout << "The minimum number of slots ever used was " << minslots << endl;
cout << "The average number of slots used was "
<< ((double)avgslots) / ((double)iterations) << endl;
return 0;
}
| true |
e0efdd74db0d857f80864156b57b3fb713b69bf1 | C++ | lgc13/LucasCosta_portfolio | /c++/practice/intermediate_examples(assignments)/hamming_sort_on_files.cpp | UTF-8 | 7,147 | 4 | 4 | [] | no_license | /* Assignment 8 for COP 3014. Created by Lucas Costa */
/* "Cheesecake assignment" */
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
/* Prototypes */
string OpenAndCheckFile(ifstream &file); //passing in a copy (with &)
int CountLines(ifstream &file, string FileName);
int ReadInArray(ifstream &file, struct Roster * RosterArray, int LineRecords);
int HammingSort(struct Roster * RosterArray, int LineRecords);
void InfoSummary(struct Roster * RosterArray ,int LineRecords, int PieCounter, int CakeCounter);
struct Roster
{
string LName;
string FName;
char Cheesecake;
};
int main(void)
{
// PART 1 -Ask the user for the name of the input file.You must make
// sure it is a valid file and that it can be opened.
// If not, you need to continually ask the user for a valid file.
ifstream file;
string FileName = OpenAndCheckFile(file); //run function, and set it = to FileName
cout << FileName << endl;
// Part 2. Open the file and read the contents only counting the number
// of records in the file.
int LineRecords = CountLines(file, FileName); //sets nr of lines to LineRecords
//Part 3. Close file...Done in Step 2
cout << LineRecords << endl;
// Part 4. Dynamically allocate an array to store the data. make sure that
// you only allocate enough storage to hold exactly the number
// of records needed.
struct Roster * RosterArray = new struct Roster[LineRecords]; //a struct router
//pointer named “records” is assigned a
//new array of Rosters the size
//of LineRecords
// Part 5 Open the file and read the file into the array.
file.open(FileName);
int PieCounter = ReadInArray(file, RosterArray, LineRecords);
file.close();
// Part 6: Sort the Array on Last Name in ascending order.
file.open(FileName);
int CakeCounter = HammingSort(RosterArray, LineRecords);
file.close();
//Part 7. Print out the information (to standard output)
// Part 8: Print out at the end of the summary of information (i.e. how many
// people said that Cheesecake is a Cake and how many said it was a Pie).
//Part 9. Also print out the number of participants. Be sure that the
// number of people who said Cheesecake is a Cake + Cheesecake is Pie
// is equal to the total number participants.
InfoSummary(RosterArray, LineRecords, PieCounter, CakeCounter);
return 0;
}
/* Function: OpenAndCheckFile */
/* Ask the user for the name of the input file. Make */
/* sure it is a valid file and that it can be opened. */
/* If not, you need to continually ask the user for a valid file. */
string OpenAndCheckFile(ifstream &file) //
{
string filename;
cout << "Enter a valide filename please: ";
cin >> filename;
file.open(filename); //opens the file
while(!file.is_open()) //continually check "while filename is not open, ask for another"
{
cout << "Invalid filename. Please put in another: ";
cin >> filename;
file.open(filename);
}
file.close(); //we now have a valid filename, so close it since we are aware it works
return filename;
}
/* Function: CountLines */
/* Open the file and read the contents only counting the number */
/* of records in the file. */
/* Once that is done, it closes the file */
/* */
int CountLines(ifstream &file, string FileName)
{
file.open(FileName); //open the file
int count = 0;
string line;
while(getline(file, line)) //while the file is open, go line by line until
//you reach the end of the file, getting lines
{
count++;
}
file.close(); //close the file
return count;
}
/* Function: ReadInArray */
/* The file is already opened, so you read each part of the file */
/* directly into the array (first, last name and cheesecake type) */
/* Also, return a PieCounter which keeps track of how many people said P */
int ReadInArray(ifstream &file, struct Roster * RosterArray, int LineRecords)
{
string lname, fname;
char cheese;
int PieCounter = 0;
for(int i = 0; i < LineRecords; i++)
{
file >> lname >> fname >> cheese; //sets fist word to lname, second to fname, third char to cheese
RosterArray[i].LName = lname; //read into array
RosterArray[i].FName = fname;
RosterArray[i].Cheesecake = cheese;
if (RosterArray[i].Cheesecake == 'P') //PieCounter checks how many people said P
PieCounter++;
}
return PieCounter;
}
/* Function: HammingSort */
/* This sorst all the lines of the file by the first word in each line */
/* once that is done, it rearranges the array */
/* This function also has a CakeCounter */
int HammingSort(struct Roster * RosterArray, int LineRecords) //sort all names in ascending order
{
int CakeCounter = 0;
for (int i = 0; i < LineRecords; i++)
{
if (RosterArray[i].Cheesecake == 'C') //CakeCounter which is returned
CakeCounter++;
}
for (int i = 0; i < LineRecords - 1; i++) //HammingSort
{
if (RosterArray[i].LName > RosterArray[i + 1].LName)
{
struct Roster temp = RosterArray[i];
RosterArray[i] = RosterArray[i + 1];
RosterArray[i + 1] = temp;
for (int k = i; k >= 1; k--)
{
if (RosterArray[k - 1].LName > RosterArray[k].LName)
{
struct Roster temp2 = RosterArray[k - 1];
RosterArray[k - 1] = RosterArray[k];
RosterArray[k] = temp2;
}
}
}
}
return CakeCounter;
}
/* Function: InfoSummary */
/* Prints out all the info requested */
/* Goes line by line printing l, f names and cheesecake type from array */
/* also prints out all the counts */
void InfoSummary(struct Roster * RosterArray ,int LineRecords, int PieCounter, int CakeCounter)
{
cout << " The Cheesecake Report " << endl;
cout << "Last Name First Name Cake or Pie " << endl;
cout << "_________ __________ ___________ " << endl;
for (int i = 0; i < LineRecords; i++)
{
cout << left << setw(15) << RosterArray[i].LName;
cout << left << setw(15) << RosterArray[i].FName;
cout << left << setw(15) << RosterArray[i].Cheesecake;
cout << endl;
}
cout << "Number of records: " << LineRecords << endl;
cout << "Number of people who believe cheesecake is pie: " << PieCounter << endl;
cout << "Number of people who believe cheesecake is cake: " << CakeCounter << endl;
}
| true |
3ebe0ced008bea0c2f0d37ef680da0a710a74b45 | C++ | anagorko/zpk2015 | /grupa3/alebilas/pd2/kol.cpp | UTF-8 | 291 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main(){
double r;
double pole;
double obwod;
cin >> r;
pole = M_PI * pow(r,2);
obwod = 2 * M_PI * r;
cout << setprecision(3) << fixed << pole << endl;
cout << setprecision(3) << fixed << obwod << endl;
}
| true |
1d12613b9ea83e01bbf9b097ca7b383bf70e6ee9 | C++ | Stephenhua/CPP | /interview_Code/Code/Dp-18-LeetCode-offer-42-maxSubArray.cc | UTF-8 | 2,009 | 3.609375 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <cmath>
#include <map>
#include <algorithm>
#include <string.h>
using namespace std;
/*
面试题42. 连续子数组的最大和
输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
示例1:
输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
提示:
1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
*/
//动态规划;
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int size = nums.size();
if( size == 0){
return 0;
}
if( size == 1){
return nums[0];
}
int res =nums[0];
int temp = 0 ;
for(int i =0 ;i <size ; i++){
if(temp >= 0){
temp += nums[i];
}else{
temp = nums[i];
}
res = max( res,temp);
}
return res;
}
};
/*
动态规划的步骤:
1) 状态: dp[i]表示元素 nums[i]结尾的连续子数组的和;
2)状态转移策略:
dp[i-1] < 0 ,对dp[i]没有贡献;
dpi-1] >= 0 ,对dp[i]的和有贡献;
3)状态转移方程:
当dp[i-1] <0 ; dp[i] = nums[i];
当dp[i-1] > 0,则dp[i] = dp[i-1] +nums[i];
4) 设计dp数组,保存子问题,避免重复计算;
5)进行压缩空间;
*/
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int size = nums.size();
if( size == 0){
return 0;
}
if( size == 1){
return nums[0];
}
int dp[size];
int res =nums[0];
dp[0] = nums[0];
for(int i =1 ;i<size ;i++){
dp[i] = max( dp[i-1]+nums[i] , nums[i]);
res = max( dp[i] , res);
}
return res;
}
}; | true |
4970c850dfd06326e05e68e95745e1bd6fa3736f | C++ | austinschneider/schneider_PHYS401 | /HW05/3/main.cc | UTF-8 | 678 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
#include "../Pre/integrate.h"
template <class T>
T I(T x) {
return 1/(((T)1.0)+x);
}
int main() {
double I_actual = 0.6931471805599453094172321;
double epsilon = 0.0000000001;
double I_result = 0;
double error = 0;
std::cout << std::endl;
std::fstream f_romberg("romberg.dat", std::ios_base::out);
std::cout << "---Testing Romberg's Method---" << std::endl;
I_result = romberg<double>(I<double>,epsilon,0.0,1.0);
error = std::abs(I_result-I_actual);
std::cout << "Result: " << std::setprecision(15) << I_result << std::endl;
std::cout << "Error: " << std::setprecision(15) << error << std::endl;
}
| true |
e5a331144de292718810656b412b06d8862fee82 | C++ | serg-bloim/srvmgr | /this_call.cpp | UTF-8 | 770 | 2.515625 | 3 | [] | no_license | int __declspec(naked) __stdcall this_call_impl()
{
__asm
{
pop eax // pop esp
pop eax // pop eax from the wrapper
pop edx // pop method ptr
pop ecx // pop this
push eax // restore esp from call to the wrapper
jmp edx // jump to the method
}
}
int __declspec(naked) __stdcall this_call(int func, void* thisPtr)
{
__asm
{
call this_call_impl
}
}
int __declspec(naked) __stdcall this_call(int func, void* thisPtr, void* a1, void* a2)
{
__asm
{
call this_call_impl
}
}
int __declspec(naked) __stdcall this_call(int func, void* thisPtr, void* a1, void* a2, void* a3)
{
__asm
{
call this_call_impl
}
} | true |
fdbcc975701331e9adf27118f6ac0675d3c41118 | C++ | aNamelessMan/ChatServer | /include/server/model/usermodel.hpp | UTF-8 | 377 | 2.546875 | 3 | [] | no_license | #ifndef UERMODEL_H
#define UERMODEL_H
#include "user.hpp"
// User表的数据操作类
class UserModel{
public:
// User表的插入方法
bool insert(User &user);
// 根据用户id查询用户信息
User query(int id);
// 更新用户的状态信息
bool updateState(User &user);
// 重置用户的状态信息
void resetState();
};
#endif | true |
35a9d29cdd794e29964701b2b816ab81aaeb8bd3 | C++ | dgouyette/arduino | /Blink4Attiny85/Blink4Attiny85.ino | UTF-8 | 701 | 3.078125 | 3 | [] | no_license | #include <VirtualWire.h> // On inclue la librairie VirtualWire
int led = 0;
char *msg = "0"; // Tableau qui contient notre message
void setup() {
pinMode(led, OUTPUT);
vw_setup(2400); // Initialisation de la librairie VirtualWire à 2400 bauds (maximum de mon module)
vw_set_tx_pin(3); // On indique que l'on veut utiliser la pin 10 de l'Arduino pour reçevoir
}
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(200);
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
msg[0]++;
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(200); // wait for a second
}
| true |
2e124b29e4593cb102130e67127ca923811d830b | C++ | t-po/ECE-ProjetGit | /classSB.cpp | ISO-8859-1 | 6,143 | 2.765625 | 3 | [] | no_license | #include "classSB.h"
#include "interfaceSB.h"
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Methodes et constructeurs de Astre
Astre::Astre()
{
system("cls");
double _x,_y;
std::cout<<"Saisir le nom de l'astre : ";
std::cin>>nom;
blindage(_x, 0, 2000, "Saisir x : ");
coordSphere.set_x(_x);
blindage(_y, 0, 2000, "Saisir y : ");
coordSphere.set_y(_y);
blindage(masse, 0, 1000000000, "Saisir la masse : ");
blindage(rayon, 0, 500, "Saisir le rayon : ");
switch(menu(MENU_COULEUR))
{
case 1 :
couleur = "blueball";
break;
case 2 :
couleur = "redball";
break;
case 3 :
couleur = "yellowball";
break;
case 4 :
couleur = "greenball";
break;
case 5 :
couleur = "greyball";
break;
}
switch(menu(MENU_ROTATION))
{
case 1 :
tourne = false;
break;
case 2 :
tourne = true;
break;
}
}
Astre::Astre(std::string _nom, double _x, double _y, double _masse, double _rayon, std::string _couleur)
{
nom = _nom;
coordSphere.set_x(_x);
coordSphere.set_y(_y);
masse = _masse;
rayon = _rayon;
couleur = _couleur;
tourne = false;
}
void Astre::displayAstre()
{
std::cout << " - "
<< nom
<< " : {"
<< coordSphere.get_x() << ","
<< coordSphere.get_y() << ","
<< masse << ","
<< rayon << ","
<< couleur
<< "}"
<<std::endl;
}
void Astre::dessiner(Svgfile &f)
{
//f.annimation(coordSphere.get_x(), coordSphere.get_y(), rayon, couleur, nom);
f.addAnimatedDisk(coordSphere.get_x(), coordSphere.get_y(), rayon, couleur, nom, tourne);
}
double Astre::get_x()
{
return coordSphere.get_x();
}
double Astre::get_y()
{
return coordSphere.get_y();
}
double Astre::get_m()
{
return masse;
}
bool Astre::get_t()
{
return tourne;
}
void Astre::modifier(int champs)
{
system("cls");
switch(champs)
{
case 1:
std::cout<<"Saisir le nouveau nom de l'astre"<<std::endl ;
std::cin>>nom;
break;
case 2:
double _x;
blindage(_x, 0, 2000, "Saisir la nouvelle abscisse de l'astre : ");
coordSphere.set_x(_x);
break;
case 3:
double _y;
blindage(_y, 0, 2000, "Saisir la nouvelle ordonne de l'astre : ");
coordSphere.set_y(_y);
break;
case 4:
blindage(masse, 0, 1000000000, "Saisir la nouvelle masse de l'astre : ");
break;
case 5:
blindage(rayon, 0, 500, "Saisir le nouveau rayon de l'astre : ");
break;
case 6:
switch(menu(MENU_COULEUR))
{
case 1 :
couleur = "blueball";
break;
case 2 :
couleur = "redball";
break;
case 3 :
couleur = "yellowball";
break;
case 4 :
couleur = "greenball";
break;
case 5 :
couleur = "greyball";
break;
}
break;
case 7:
switch(menu(MENU_ROTATION))
{
case 1 :
tourne = false;
break;
case 2 :
tourne = true;
break;
}
}
}
/// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Methodes et constructeurs de SystemeAstral
void SystemeAstral::dessinerBarycentre(Svgfile &f)
{
double croix_x = 0, croix_y = 0;
size_t i = 0, masseTotal = 0;
for(i = 0 ; i < systeme.size() ; i++)
{
if(systeme[i].get_t() == true)
{
croix_x += (systeme[i].get_x()*systeme[i].get_m());
croix_y += (systeme[i].get_y()*systeme[i].get_m());
masseTotal += systeme[i].get_m();
}
}
croix_x /= masseTotal;
croix_y /= masseTotal;
f.addCross(croix_x, croix_y, 10);
}
void SystemeAstral::modifier(size_t bitocu)
{
bitocu -= 2;
systeme[bitocu].modifier(menu(MENU_MODIF));
}
void SystemeAstral::supprimer(size_t i)
{
systeme.erase(systeme.begin() + i-1-1);
}
void SystemeAstral::ajouter(Astre a)
{
systeme.push_back(a);
}
void SystemeAstral::initSolaire()
{
Astre soleil("Soleil",1000,1000,MASSE_SOLEIL,30,"yellowball");
Astre mercure("Mercure",1000 + 60*(2/3.0),1000,MASSE_SOLEIL*0.166/1000000,DIAMETRE_MARS*0.7,"greyball");
Astre venus("Venus",1000 + 110*(2/3.0),1000,MASSE_SOLEIL*2.45/1000000,DIAMETRE_MARS*1.7,"greyball");
Astre terre("Terre",1000 + 150*(2/3.0),1000,MASSE_SOLEIL*3.00/1000000,DIAMETRE_MARS*1.8,"blueball");
Astre mars("Mars",1000 + 230*(2/3.0),1000,MASSE_SOLEIL*0.322/1000000,DIAMETRE_MARS,"redball");
Astre jupiter("Jupiter",1000 + 780*(2/3.0),1000,MASSE_SOLEIL*954.6/1000000,DIAMETRE_MARS*20,"yellowball");
Astre saturne("Saturne",1000 + 1420*(2/3.0),1000,MASSE_SOLEIL*285.8/1000000,DIAMETRE_MARS*17.1,"yellowball");
ajouter(soleil);
ajouter(mercure);
ajouter(venus);
ajouter(terre);
ajouter(mars);
ajouter(jupiter);
ajouter(saturne);
}
void SystemeAstral::dessiner()
{
size_t i = 0;
Svgfile svgout;
svgout.addGrid();
for(i = 0 ; i < systeme.size(); i++)
{
systeme[i].dessiner(svgout); //On dessine chaques astres
}
dessinerBarycentre(svgout);
}
void SystemeAstral::display()
{
size_t i = 0;
for(i = 0 ; i < systeme.size() ; i++)
{
systeme[i].displayAstre();
}
}
size_t SystemeAstral::size()
{
return systeme.size();
}
/// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// Methodes et constructeurs de Coord
Coord::Coord(double _x, double _y)
{
x = _x;
y = _y;
}
double Coord::get_x()
{
return x;
}
double Coord::get_y()
{
return y;
}
void Coord::set_x(double _x)
{
x =_x;
}
void Coord::set_y(double _y)
{
y =_y;
}
| true |
a3dedc5ea52ce1eda9ed3a77eb4a8abc4e4ebce4 | C++ | 1468362286/Algorithm | /CodeForces/919A/14276639_AC_30ms_12kB.cpp | UTF-8 | 359 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
const double inf=0x3f3f3f3f;
double min(double a,double b){return a>b?b:a;}
int main()
{
// freopen("in.txt","r",stdin);
int n,m;
while(cin>>n>>m)
{
double a,b;
double ans=inf;
for(int i = 0 ; i < n ; i++)
{
cin>>a>>b;
ans=min(ans,a/b);
}
printf("%.8lf\n",ans*m);
}
return 0;
} | true |
45ffa7ab687e31b6e5b5caf4b3a8ae449c467637 | C++ | hydrogen602/Research1 | /state.cpp | UTF-8 | 7,821 | 2.984375 | 3 | [] | no_license | #include <vector>
#include <iostream>
#include <cstdio>
#include <cmath>
#include "state.h"
#include "data/vector3.h"
#define square(x) ((x) * (x))
State::State(double hVal, double maxXArg, double maxYArg, double kArg, double dragCoeff): h{hVal}, maxX{maxXArg}, maxY{maxYArg}, k{kArg}, drag{dragCoeff} {
std::cout << "k = " << k << "\n";
std::cerr << "maxX = " << maxX << "; maxY = " << maxY << '\n';
}
// State::State(double hVal): h{hVal} {}
void State::addBody(double x, double y, double z, double vx, double vy, double vz, double m, double sz) {
data.addBody(x, y, z, vx, vy, vz);
masses.push_back(m);
sizes.push_back(sz);
if (masses.size() * 6 != data.size() || masses.size() != sizes.size()) {
throw ERR_VECTOR_SIZE_MISMATCH;
}
}
unsigned int State::size() const {
return masses.size();
}
void State::printOut() const {
std::cout << "[\n";
for (unsigned int i = 0; i < data.size(); i += 6) {
printf(" ");
data.printOut(i);
}
std::cout << "]\n";
}
double State::computeKineticEnergy() const {
// 1/2 m v^2
double energy = 0;
for (unsigned int i = 0; i < data.size(); i += 6) {
// v^2 = vx^2 + vy^2 + vz^2
double vSq = square(data[i + 3]) + square(data[i + 4]) + square(data[i + 5]);
energy += 0.5 * masses[i / 6] * vSq;
//printf("KE[%d] = %e\n", i / 6, 0.5 * masses[i / 6] * vSq);
}
//printf("K = %e\n", energy);
return energy;
}
double State::computePotentialEnergy() const {
// -G (mM) / R
double energy = 0;
for (unsigned int i = 0; i < data.size(); i += 6)
{
for (unsigned int j = i + 6; j < data.size(); j += 6)
{
// compute R
double dSq = square(data[i] - data[j]) + square(data[i+1] - data[j+1]) + square(data[i+2] - data[j+2]);
double r = sqrt(dSq);
// G is 1
energy += - (masses[i / 6] * masses[j / 6] / r);
//printf("PE[%d] on [%d] = %e\n", i / 6, j / 6, - (masses[i / 6] * masses[j / 6] / r));
}
}
//printf("U = %e\n", energy);
return energy;
}
double State::computeEnergy() const {
double K = computeKineticEnergy();
double U = computePotentialEnergy();
//std::cerr << "> K, U = " << K << ", " << U << '\n';
return K + U;
}
vector3 State::getPosition(int objNum) const {
int i = objNum * 6;
vector3 p = {data[i+0], data[i+1], data[i+2]};
return p;
}
vector3 State::getVelocity(int objNum) const {
int i = objNum * 6;
vector3 v = {data[i+3], data[i+4], data[i+5]};
return v;
}
double State::getSize(int objNum) const {
return sizes[objNum];
}
void State::derivative(Vector& d) const {
if (d.size() != data.size()) {
d.resize(data.size(), 0);
}
/* [ x ] [ vx ]
* [ y ] [ vy ]
* [ z ] ==> [ vz ]
* [ vx ] ==> [ ax ]
* [ vy ] [ ay ]
* [ vz ] [ az ]
*/
for (unsigned int i = 0; i < data.size(); i += 6) {
d[i + 0] = data[i + 3];
d[i + 1] = data[i + 4];
d[i + 2] = data[i + 5];
// find acceleration
vector3 accVector(0, 0, 0);
for (unsigned int j = 0; j < data.size(); j += 6) {
if (i != j) {
double dSq = square(data[i] - data[j]) + square(data[i+1] - data[j+1]) + square(data[i+2] - data[j+2]);
// a = g * m / r^2
// g = 1
// m = in solar masses
double accScalar = masses[j / 6] / dSq; // magnitude of a
// vect3 dirUnitVec = system[i].unitVectTo(system[j]); // dir of a
double d = sqrt(dSq); // length of vector
// and distance between objects
vector3 c(data[j] - data[i], data[j+1] - data[i+1], data[j+2] - data[i+2]);
// now c is a vector pointing to b from this
c /= d;
// c is displacement unit vector
vector3 acc = c; // make a copy
// c is now a unit vector pointing to object j
acc *= accScalar;
//fprintf(stderr, "<%e, %e, %e>\n", acc.x, acc.y, acc.z);
accVector += acc;
// i and j forces get calculated twice
// deal with collisions
double deltaX = d - (sizes[j / 6] + sizes[i / 6]);
if (deltaX < 0) {
// intersection!
//std::cerr << "intersection " << fabs(deltaX / (sizes[j / 6] + sizes[i / 6])) * 100 << "%\n";
vector3 vI = {data[i+3], data[i+4], data[i+5]};
vector3 vJ = {data[j+3], data[j+4], data[j+5]};
vector3 rel = vJ - vI;
double vMag = rel.dot(c);
// in dir -c (away from other object)
double a = (-k * -deltaX + drag * vMag) / masses[i / 6];
accVector += (c * a);
//fprintf(stderr, "object %d\n", i);
//fprintf(stderr, "deltaX = %e\n", deltaX);
//fprintf(stderr, "<%e, %e, %e>\n", c.x, c.y, c.z);
//fprintf(stderr, "<%e, %e, %e>\n", accVector.x, accVector.y, accVector.z);
}
}
}
// accVector is acceleration
d[i + 3] = accVector.x;
d[i + 4] = accVector.y;
d[i + 5] = accVector.z;
}
}
void State::euler1() {
// y_n+1 = y_n + k
// k = h * F(x, y)
Vector k;
derivative(k);
k *= h;
// advance
(*this) += k;
}
void State::kickStep1() {
// first integrate acc to vel, then vel to position
Vector k;
derivative(k);
// kick
for (unsigned int i = 0; i < data.size(); i += 6) {
k[i + 0] += k[i + 3] * h;
k[i + 1] += k[i + 4] * h;
k[i + 2] += k[i + 5] * h;
}
// step
k *= h;
(*this) += k;
}
void State::rk4() {
/*
* Runge-Kutta
*
* y' = F(x, y)
*
* y_n+1 = y_n + 1/6 * (k1 + 2k2 + 2k3 + k4) + O(h^5)
*
* k1 = hF(xn, yn)
* k2 = hF(xn + h/2, yn + k1/2)
* k3 = hF(xn + h/2, yn + k2/2)
* k4 = hF(xn + h, yn + k3)
*
* y is position & velocity
* y' is velocity & acceleration
*
* idk what to do with x for now
*/
Vector oldState(data);
// k1 = hF(xn, yn)
Vector k1;
derivative(k1);
k1 *= h;
// k2 = hF(xn + h/2, yn + k1/2)
(*this) += k1 / 2;
Vector k2;
derivative(k2);
k2 *= h;
data = oldState;
// k3 = hF(xn + h/2, yn + k2/2)
(*this) += k2 / 2;
Vector k3;
derivative(k3);
k3 *= h;
data = oldState;
// k4 = hF(xn + h, yn + k3)
(*this) += k3;
Vector k4;
derivative(k4);
k4 *= h;
data = oldState;
// 1/6 * (k1 + 2k2 + 2k3 + k4)
Vector K(data.size());
K += k1;
k2 *= 2;
K += k2;
k3 *= 2;
K += k3;
K += k4;
K *= 1.0/6;
(*this) += K;
}
double& State::operator[](unsigned int i) {
return data[i];
}
State State::operator+=(Vector delta) {
if (data.size() != delta.size()) {
throw ERR_VECTOR_SIZE_MISMATCH;
}
// boundary conditions!
for (unsigned int i = 0; i < data.size(); i += 6) {
data[i] += delta[i];
data[i + 1] += delta[i + 1];
data[i + 2] += delta[i + 2];
data[i + 3] += delta[i + 3];
data[i + 4] += delta[i + 4];
data[i + 5] += delta[i + 5];
// if (data[i] < -maxX || data[i] > maxX) {
// data[i] *= -1;
// std::cerr << "flipped\n";
// }
// if (data[i + 1] < -maxY || data[i + 1] > maxY) {
// data[i + 1] *= -1;
// }
}
return *this;
}
| true |
82133105a967089db94176edb321b0a4de0374ad | C++ | LichProject/RecastManaged | /Recast/CompactCell.cpp | UTF-8 | 1,049 | 2.53125 | 3 | [] | no_license | #include "../Unmanaged/Recast/Recast.h"
#include "CompactCell.h"
RecastManaged::Recast::CompactCell::CompactCell(rcCompactCell* cell, bool* destructWithMe)
{
this->_cell = cell;
this->_destructWithMe = destructWithMe;
this->_disposed = false;
}
RecastManaged::Recast::CompactCell::~CompactCell()
{
this->!CompactCell();
}
RecastManaged::Recast::CompactCell::!CompactCell()
{
if (!this->_disposed && this->_destructWithMe)
{
delete _cell;
_cell = nullptr;
this->_disposed = true;
}
}
rcCompactCell* RecastManaged::Recast::CompactCell::GetPointer()
{
return this->_cell;
}
#pragma region Index
unsigned int RecastManaged::Recast::CompactCell::Index::get()
{
return _cell->index;
}
void RecastManaged::Recast::CompactCell::Index::set(unsigned int value)
{
_cell->index = value;
}
#pragma endregion
#pragma region Count
unsigned int RecastManaged::Recast::CompactCell::Count::get()
{
return _cell->count;
}
void RecastManaged::Recast::CompactCell::Count::set(unsigned int value)
{
_cell->count = value;
}
#pragma endregion
| true |
eca26d324e04d2e70fbd46239cf5abfdf3987076 | C++ | girishprb/Sorting | /BubbleSort.cpp | UTF-8 | 452 | 2.90625 | 3 | [] | no_license | /*
* BubbleSort.cpp
*
* Created on: Apr 13, 2014
* Author: Girish Prabhu
*/
#include <stdlib.h>
#include <iostream>
#include "BubbleSort.h"
using namespace std;
//Default constructor
BubbleSort::BubbleSort()
{
}
BubbleSort::BubbleSort(int size):SortingBase(size)
{
}
BubbleSort::~BubbleSort()
{
}
void BubbleSort::DoSort()
{
int tmp;
for(int i=0; i <size-1; i++)
for(int j=i+1; j<size; j++)
if(arr[i]>arr[j])
SwapArray(i,j);
}
| true |
feb5af4a5114e19471988e62b220a17c328dfcad | C++ | MichaelTiernan/qvge | /src/3rdParty/ogdf-2020/src/ogdf/fileformats/GEXF.cpp | UTF-8 | 2,127 | 2.765625 | 3 | [
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-unknown-license-reference",
"GPL-3.0-only",
"LGPL-2.1-or-later",
"LGPL-2.0-or-later",
"EPL-1.0",
"LicenseRef-scancode-generic-exception",
"GPL-1.0-or-later",
"BSL-1.0",
"LGPL-2.0-only",
"BSD-2-Clause"
] | permissive | /** \file
* \brief Implementation of GEXF string conversion functions.
*
* \author Łukasz Hanuszczak
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/fileformats/GEXF.h>
#include <ogdf/fileformats/Utils.h>
namespace ogdf {
namespace gexf {
std::string toString(const Shape &shape)
{
switch(shape) {
case Shape::Rect: return "square";
case Shape::RoundedRect: return "rect"; // Not supported.
case Shape::Ellipse: return "disc";
case Shape::Triangle: return "triangle";
case Shape::Rhomb: return "diamond";
case Shape::Image: return "image";
default: return "disc";
}
}
Shape toShape(const std::string &str)
{
return toEnum(str, toString, Shape::Rect, Shape::Image, Shape::Rect);
}
std::string toGEXFStrokeType(const StrokeType &type)
{
switch(type) {
case StrokeType::Solid: return "solid";
case StrokeType::Dot: return "dotted";
case StrokeType::Dash: return "dashed";
case StrokeType::Dashdot: return "dashdot";
case StrokeType::Dashdotdot: return "dashdotdot";
default: return "";
}
}
StrokeType toStrokeType(const std::string &str)
{
// GEXF supports solid, dotted, dashed, double.
// We don't support double, but dashdot and dashdotdot instead.
return toEnum(str, toGEXFStrokeType, StrokeType::None, StrokeType::Dashdotdot, StrokeType::Solid);
}
}
}
| true |
ee91abaf49d013ffca1d9eec545492a64cc6e8bc | C++ | jasoncustodio/Coursework | /Coursework/C++/Programming Systems/HW2/main.cpp | UTF-8 | 2,986 | 3.765625 | 4 | [] | no_license | /*
Program: Adventure Map
Author: Jason Custodio
Class: CS202
Date: 05/07/2014
Description: This program simulates a math riddle game
There will be a menu class that acts as an interface
Menu has a roster and has a map
A player roster will be implemented in the future
The info class acts as any kind of simple data
A player is derived from the info class
A player has a score, a name, a location, and inventory
The score is only an int, the name is info, the location
is the index of where it is in the map
Inventory is a DLL that holds items found in the map
An item is an info
Info only has a name and points to the next and previous items
The map is implemented using a graph
Each vertex holds a question, location, object, a visit flag, and
a head pointer to a LLL of edges
Each edge holds an answer, index of where it points to, and a pointer
to the next edge
To win the game, you must get to the end
Whoever gets the highest score at the end wins with multiplayer
*/
#include "menu.h"
int main()
{
menu myMenu; //Help with interface
int choice = 0; //Choice for interface
char textOne [SIZE]; //Used to supply external vertex data
char textTwo [SIZE]; //Used to supply external edge data
strcpy(textOne, "vertex.txt"); //Used to supply external vertex data
strcpy(textTwo, "edge.txt"); //Used to supply external edge data
myMenu.load(textOne, textTwo); //Load vertex and edge data
myMenu.welcome(); //Welcomes user
do
{
myMenu.space(SPACE); //Clean output buffer
choice = myMenu.interface(); //Calls interface function to display user interface
myMenu.space(SPACE); //Clean output buffer
switch (choice) //Switch statement with 5 commands
{
case 1: //Move
{
if(!myMenu.move()) //Once player gets to the end, they finish
{
myMenu.win(); //Congratulates player that won
choice = EXIT; //EXIT is constant for exiting program
}
}break;
case 2: //Display Inventory
{
myMenu.displayInventory(); //Displays all items in the inventory
}break;
case 3: //Add Player
{
myMenu.add(); //Adds a player to the roster
}break;
case 4: //Change Player
{
myMenu.setCurrentPlayer(); //Switches player
}break;
default:break;
}
}while (choice!=EXIT); //Exit program
return 0;
}
| true |
d818d14992e40a0402ba205a8ae89694b860120d | C++ | morris821028/hw-HikaruNoGo | /source/TArandom_modify/MCTS.h | UTF-8 | 5,319 | 2.609375 | 3 | [] | no_license | #include "board.h"
#include <vector>
using namespace std;
struct Node {
// record data
int games, wins;
float UCB, sum, sqsum;
mBoard board;
int game_length, turn;
vector<Node*> son;
vector<int> move;
Node *parent;
Node() {
son = vector<Node*>(), move = vector<int>();
games = wins = 0;
UCB = 0.f;
parent = NULL;
}
void updatescore() {
UCB = sum / games;
}
};
struct Result {
int games, wins;
float sum, sqsum;
};
Node _mem[8192];
class MCTS {
public:
Node *root;
int cases, nodesize = 0;
int GameRecord[MAXGAMELENGTH][BOUNDARYSIZE][BOUNDARYSIZE];
struct Pick {
Node* (*pick)(Node*, Node*);
static Node* max(Node *a, Node *b) {
return a->UCB > b->UCB ? a : b;
}
static Node* min(Node *a, Node *b) {
return a->UCB < b->UCB ? a : b;
}
void mount(int turn) {
if (turn == BLACK)
this->pick = Pick::max;
else
this->pick = Pick::min;
}
} decider;
Node* newNode(mBoard board) {
Node *p = &_mem[nodesize++];
*p = Node(), p->board = board;
return p;
}
void init(mBoard init_board, int game_length, int turn, int GR[MAXGAMELENGTH][BOUNDARYSIZE][BOUNDARYSIZE]) {
cases = 0;
nodesize = 0;
root = newNode(init_board);
root->game_length = game_length, root->turn = turn;
for (int i = 0; i <= game_length; i++)
memcpy(GameRecord[i], GR[i], sizeof(int)*BOUNDARYSIZE*BOUNDARYSIZE);
}
int rand_pick_move(int num_legal_moves, int MoveList[HISTORYLENGTH]) {
if (num_legal_moves == 0)
return 0;
int move_id = rand()%num_legal_moves;
return MoveList[move_id];
}
void record(mBoard board, int GameRecord[MAXGAMELENGTH][BOUNDARYSIZE][BOUNDARYSIZE], int game_length) {
memcpy(GameRecord[game_length], board.B, sizeof(int)*BOUNDARYSIZE*BOUNDARYSIZE);
}
void do_move(mBoard &board, int turn, int move) {
int move_x = (move % 100) / 10, move_y = move % 10;
if (move < 100)
board.B[move_x][move_y] = turn;
else
board.update_board(move_x, move_y, turn);
}
int run() {
srand(time(NULL));
const int MAXSIM = 10;
for (int it = 0; it < 20; it++) {
Node *leaf = selection();
int ways = expansion(leaf);
for (int i = 0; i < leaf->son.size(); i++) {
Node *p = leaf->son[i];
float sum = 0, sqsum = 0;
record(p->board, GameRecord, p->game_length+1);
for (int j = 0; j < MAXSIM; j++) {
int score = simulation(p);
sum += score, sqsum += score * score;
}
p->sum = sum, p->sqsum = sqsum;
p->games = MAXSIM;
p->updatescore();
backpropagation(p);
}
}
if (root->son.size() == 0)
return 0;
decider.mount(root->turn);
int move = root->move[0];
Node *best = root->son[0], *tmp;
for (int i = 1; i < root->son.size(); i++) {
tmp = decider.pick(root->son[i], best);
if (tmp != best)
best = tmp, move = root->move[i];
}
return move;
}
Node* selection() {
Node *p = root;
while (true) {
if (p->son.size() == 0)
return p;
decider.mount(p->turn);
Node *q = p->son[0];
for (int i = 1; i < p->son.size(); i++)
q = decider.pick(q, p->son[i]);
q->parent = p;
p = q;
record(p->board, GameRecord, p->game_length+1);
}
return NULL;
}
int expansion(Node *leaf) {
int MoveList[HISTORYLENGTH];
int num_legal_moves = leaf->board.gen_legal_move(leaf->turn, leaf->game_length, GameRecord, MoveList);
int ok = 0;
for (int i = 0; i < num_legal_moves; i++) {
if (leaf->game_length < 12) {
int move = MoveList[i];
int cx = BOUNDARYSIZE/2, cy = BOUNDARYSIZE/2;
int tx = (move%100) / 10, ty = move % 10, dist = max(abs(tx - cx), abs(ty - cy));
if (dist >= BOUNDARYSIZE/2 - 1 || dist <= 1)
continue;
}
Node *t = newNode(leaf->board);
t->game_length = leaf->game_length+1, t->turn = leaf->turn == BLACK ? WHITE : BLACK;
do_move(t->board, leaf->turn, MoveList[i]);
leaf->son.push_back(t), leaf->move.push_back(MoveList[i]);
t->parent = leaf;
ok++;
}
return ok;
}
int simulation(Node *leaf) {
int MoveList[HISTORYLENGTH];
mBoard tmpBoard = leaf->board;
int num_legal_moves = 0, move;
int game_length = leaf->game_length;
int turn = leaf->turn;
num_legal_moves = tmpBoard.gen_legal_move(turn, game_length, GameRecord, MoveList);
int limit = game_length * game_length;
while (true && limit >= 0) {
if (num_legal_moves == 0) {
int score = tmpBoard.score();
return score;
}
move = rand_pick_move(num_legal_moves, MoveList);
if (game_length < 12) {
int cx = BOUNDARYSIZE/2, cy = BOUNDARYSIZE/2;
int tx = (move%100) / 10, ty = move % 10, dist = max(abs(tx - cx), abs(ty - cy));
if (dist >= BOUNDARYSIZE/2 - 1 || dist <= 1)
continue;
}
do_move(tmpBoard, turn, move);
record(tmpBoard, GameRecord, game_length+1);
game_length++;
turn = turn == BLACK ? WHITE : BLACK;
num_legal_moves = tmpBoard.gen_legal_move(turn, game_length, GameRecord, MoveList);
limit--;
}
int score = tmpBoard.score();
return score;
}
void backpropagation(Node *leaf) {
Node *p = leaf->parent;
int games = leaf->games;
float sum = leaf->sum, sqsum = leaf->sqsum;
while (p != NULL) {
p->sum += sum, p->sqsum += sqsum;
p->games += games;
p->updatescore();
p = p->parent;
}
}
};
| true |
731e0eabf6836f7a24338356387b45feb2621ddb | C++ | tamaskenez/advent-of-code | /2016/d24.cpp | UTF-8 | 2,707 | 2.640625 | 3 | [] | no_license | #include "common.h"
int solve(AI2 start, AI2 end, const VS& board, const int H, const int W)
{
vector<AI2> front, next_front;
set<AI2> visited;
front.PB(start);
visited.insert(start);
int steps = 0;
for (;; ++steps) {
next_front.clear();
assert(!front.empty());
for (const auto st : front) {
if (st == end) {
return steps;
}
for (auto dir : {AI2{-1, 0}, AI2{1, 0}, AI2{0, 1}, AI2{0, -1}}) {
auto next_loc = st + dir;
if (!is_between_co(next_loc[0], 0, H) || !is_between_co(next_loc[1], 0, W)) {
continue;
}
auto c = board[next_loc[0]][next_loc[1]];
if (c != '.') {
continue;
}
if (contains(visited, next_loc)) {
continue;
}
next_front.PB(next_loc);
visited.insert(next_loc);
}
}
next_front.swap(front);
}
UNREACHABLE;
return INT_MAX;
}
int solve(const vector<AI2>& targets,
const VS& board,
const int H,
const int W,
AI2 start,
bool return_start)
{
AI2 loc = start;
int r = 0;
for (auto t : targets) {
r += solve(loc, t, board, H, W);
loc = t;
}
if (return_start) {
r += solve(loc, start, board, H, W);
}
return r;
}
int main()
{
ifstream f(CMAKE_CURRENT_SOURCE_DIR "/d24_input.txt");
assert(f.good());
auto lines = read_lines(f);
const int W = ~lines[0];
assert(W > 0);
VS board;
vector<AI2> targets;
AI2 start;
for (auto& l : lines) {
if (l.empty()) {
break;
}
assert(~l == W);
auto s = l;
FOR (col, 0, < W) {
auto& c = s[col];
if (c == '0') {
start = AI2{~board, col};
c = '.';
} else if (isdigit(c)) {
targets.PB(AI2{~board, col});
c = '.';
} else {
assert(c == '#' || c == '.');
}
}
board.PB(s);
}
const int H = ~board;
if (0) {
RunningStat<int> steps;
do {
steps.add(solve(targets, board, H, W, start, false));
} while (std::next_permutation(BE(targets)));
printf("part1 %d\n", *steps.lower);
}
{
RunningStat<int> steps;
do {
steps.add(solve(targets, board, H, W, start, true));
} while (std::next_permutation(BE(targets)));
printf("part2 %d\n", *steps.lower);
}
return 0;
}
| true |
aa3d482fa53c075b63cb13bbc593525daddb5f2a | C++ | luuuyi/MyPractise_1 | /dp_solve_maximium_ascend_subset.cpp | UTF-8 | 704 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
int n;
while(cin>>n){
vector<int> datas(n,0);
for(int i=0;i<n;i++) cin >> datas[i];
vector<int> dp(n+1,0);dp[1] = 1;
int max_v = 0x80000000;
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(datas[i]>datas[j]) dp[i+1] = max(dp[j+1] + 1,dp[i+1]);
else if(datas[i]==datas[j]) dp[i+1] = max(dp[j+1],dp[i+1]);
else dp[i+1] = max(1,dp[i+1]);
if(dp[i+1]>max_v) max_v = dp[i+1];
}
}
cout << max_v << endl;
}
return 0;
} | true |
e7c1a09e8a3d28000ab00e901fa3e1301ad578a8 | C++ | shahed-shd/Online-Judge-Solutions | /GeeksforGeeks-Practice/Medium/Full/Sum of Subarrays.cpp | UTF-8 | 663 | 2.71875 | 3 | [] | no_license | // ==================================================
// Problem : Sum of Subarrays
// Run time : 0.087 sec.
// Language : C++11
// ==================================================
#include <cstdio>
using namespace std;
typedef long long LL;
const LL MOD = 1e9+7;
int main()
{
int t;
scanf("%d", &t);
while(t--) {
int n, val;
scanf("%d", &n);
int nn = n;
LL res = 0;
for(int i = 1; i <= n; ++i, --nn) {
scanf("%d", &val);
res += (LL(val % MOD) * ((i * nn) % MOD)) % MOD;
res %= MOD;
}
printf("%lld\n", res);
}
return 0;
}
| true |
b699815f894177a2d960af1878c408703c59cb09 | C++ | adityanjr/code-DS-ALGO | /InterviewBit/Linked Lists/add_two_numbers_as_lists.cpp | UTF-8 | 1,454 | 3.34375 | 3 | [
"MIT"
] | permissive | // https://www.interviewbit.com/problems/add-two-numbers-as-lists/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int findLen(ListNode* A) {
int c = 0;
while(A!=NULL) {
c++;
A = A->next;
}
return c;
}
void swap(int& x, int& y) {
x ^= y;
y ^= x;
x ^= y;
}
ListNode* Solution::addTwoNumbers(ListNode* A, ListNode* B) {
int n = findLen(A);
int m = findLen(B);
if(n==0)
return B;
if(m==0)
return A;
ListNode* temp;
if(m>n) {
temp = A;
A = B;
B = temp;
swap(n, m);
}
int carry = 0;
int d = A->val+B->val;
ListNode* head = new ListNode(d%10);
carry = d/10;
A = A->next;
B = B->next;
temp = head;
while(B!=NULL) {
d = A->val+B->val+carry;
carry = d/10;
ListNode* node = new ListNode(d%10);
temp->next = node;
temp = node;
A = A->next;
B = B->next;
}
while(A!=NULL) {
d = A->val+carry;
carry = d/10;
ListNode* node = new ListNode(d%10);
temp->next = node;
temp = node;
A = A->next;
}
while(carry>0) {
ListNode* node = new ListNode(carry%10);
temp->next = node;
temp = node;
carry /= 10;
}
return head;
}
| true |
22c751fc271ea6dca216049eb9fd1a30be1a50d2 | C++ | hirano567/XLCTextEx | /XLCTextEx/PLib/PGClass.h | SHIFT_JIS | 5,449 | 2.59375 | 3 | [
"MS-PL"
] | permissive | // XLCTextEx_1.0x : PLib
// PGClass.h
//
#pragma once
NS_PLIB_BEGIN
//======================================================================
// PCStrBuffer : p̃obt@ǗNX
//======================================================================
#define BUFFER_SIZE_DEFAULT 256
#define BUFFER_SIZE_MAX_DEFAULT INT_MAX
#define BUFFER_SIZE_MIN_DEFAULT 16
template<
typename T_DATA,
class C_MALLOC = NS_PLIB::PCMAlloc,
size_t BUFFER_SIZE = BUFFER_SIZE_DEFAULT,
size_t BUFFER_SIZE_MAX = BUFFER_SIZE_MAX_DEFAULT,
size_t BUFFER_SIZE_MIN = BUFFER_SIZE_MIN_DEFAULT
>
class PCStrBuffer
{
protected:
typedef T_DATA* T_PDATA;
typedef const T_DATA* T_PCDATA;
T_PDATA pBuffer;
size_t zBuffer;
C_MALLOC ciMAlloc;
public:
//------------------------------------------------------------
// Init
//------------------------------------------------------------
BOOL Init()
{
ciMAlloc.Deallocate<T_DATA>(pBuffer);
zBuffer = BUFFER_SIZE;
if (ciMAlloc.Allocate<T_DATA>(&pBuffer, zBuffer))
{
*pBuffer = NULL;
return TRUE;
}
return FALSE;
}
//------------------------------------------------------------
// PCStrBuffer RXgN^
//------------------------------------------------------------
PCStrBuffer()
: pBuffer(NULL), zBuffer(BUFFER_SIZE)
{
if (zBuffer < BUFFER_SIZE_MIN) zBuffer = BUFFER_SIZE_MIN;
Init();
}
//------------------------------------------------------------
// ~PCStrBuffer fXgN^
//------------------------------------------------------------
~PCStrBuffer()
{
ciMAlloc.Deallocate<T_DATA>(pBuffer);
}
//------------------------------------------------------------
// Buffer
//------------------------------------------------------------
T_PDATA Buffer()
{
return pBuffer;
}
//------------------------------------------------------------
// Size
//------------------------------------------------------------
size_t Size()
{
return zBuffer;
}
//------------------------------------------------------------
// ExtendBuffer
//------------------------------------------------------------
BOOL ExtendBuffer(size_t zRequired)
{
if (zRequired > BUFFER_SIZE_MAX) return FALSE;
while (zBuffer < zRequired) zBuffer += BUFFER_SIZE;
if (zRequired > BUFFER_SIZE_MAX) zRequired = BUFFER_SIZE_MAX;
ciMAlloc.Deallocate<T_DATA>(pBuffer);
if (ciMAlloc.Allocate<T_DATA>(&pBuffer, zBuffer)) return TRUE;
return FALSE;
}
//------------------------------------------------------------
// Read
//------------------------------------------------------------
BOOL Read(T_PCDATA* ppBuffer, size_t* pzBuffer)
{
if (pBuffer != NULL)
{
*ppBuffer = (T_PCDATA)pBuffer;
*pzBuffer = zBuffer;
return TRUE;
}
return FALSE;
}
//------------------------------------------------------------
// Write
//
// Ô߁AI[ NULL ljB
//------------------------------------------------------------
BOOL Write(T_PCDATA pData, size_t zData)
{
T_PCDATA ps, pe;
T_PDATA pd;
size_t zReq;
zReq = zData + 1;
if (zReq > zBuffer)
{
if (!ExtendBuffer(zReq)) return FALSE;
}
pe = pData + zData;
for (ps = pData, pd = pBuffer; ps < pe; ++ps, ++pd) *pd = *ps;
*pd = NULL;
return TRUE;
}
};
//======================================================================
// class PCIteratorStack : q̃X^bNǗ邽߂̃NX
//======================================================================
template<class C_CONTAINER, class C_MALLOC = PLib::PCInstanceSet<typename C_CONTAINER::iterator> >
class PCIteratorStack
{
private:
typedef typename C_CONTAINER::iterator ITERATOR, *PITERATOR;
typedef std::list<PITERATOR> ITRSTACK;
typedef typename ITRSTACK::iterator ITR_ITRSTACK;
//------------------------------------------------------------
// f[^o
//------------------------------------------------------------
ITRSTACK ciItrStack;
C_MALLOC ciMAlloc;
//------------------------------------------------------------
// o
//------------------------------------------------------------
private:
void Clear()
{
ITR_ITRSTACK i;
for (i = ciItrStack.begin(); i != ciItrStack.end(); ++i)
{
ciMAlloc.Deallocate(*i);
}
ciItrStack.clear();
ciMAlloc.Clear();
}
public:
size_t Size()
{
return (size_t)ciItrStack.size();
}
void PushNew()
{
ITR_ITRSTACK itr;
PITERATOR p;
p = ciMAlloc.Allocate();
if (!ciItrStack.empty())
{
itr = ciItrStack.begin();
*p = **itr;
}
ciItrStack.push_front(p);
}
void Pop()
{
PITERATOR pi;
if (ciItrStack.empty()) THROWPE_LOGIC_ERROR("PCIteratorStack::Pop");
pi = *(ciItrStack.begin());
ciItrStack.pop_front();
if (ciItrStack.empty()) THROWPE_LOGIC_ERROR("PCIteratorStack::Pop");
ciMAlloc.Deallocate(pi);
}
void PopAndUpdate()
{
PITERATOR pi;
if (ciItrStack.empty()) THROWPE_LOGIC_ERROR("PCIteratorStack::PopAndUpdate");
pi = *(ciItrStack.begin());
ciItrStack.pop_front();
if (ciItrStack.empty()) THROWPE_LOGIC_ERROR("PCIteratorStack::PopAndUpdate");
**(ciItrStack.begin()) = *pi;
ciMAlloc.Deallocate(pi);
}
PITERATOR pIterator()
{
if (!ciItrStack.empty())
{
return *(ciItrStack.begin());
}
return NULL;
}
void Init()
{
Clear();
ciMAlloc.Init();
PushNew();
}
PCIteratorStack()
{
Init();
}
~PCIteratorStack()
{
Clear();
}
};
NS_PLIB_END
| true |
05a588ca87696374b4287b500a1af5d9b4bd37f9 | C++ | SPReddy224/C-Advance | /submission-c++-arif/17th.cpp | UTF-8 | 300 | 2.859375 | 3 | [] | no_license | /*#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int num;
cout << "Enter a number : " << endl;
cin >> num;
if (num % 2 == 0)
cout << " the given number is even number" << endl;
else
cout << " the given number is odd number" << endl;
system("pause");
return 0;
}*/ | true |
a59d65d4bec3ad4769ed048c27409c4d11d14438 | C++ | MARI0sGitHub/MAZE_WTIH_FILE_I-O | /game.cpp | UHC | 5,593 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <time.h>
#include <conio.h>
using namespace std;
struct _Position { //ǥ ϱ ü
int x;
int y;
};
typedef _Position P; //ü Ī ü P Īμ ϴ.
typedef _Position* PP;//ü !! Ī ü PP Īμ ϴ.
/*
0.
1.
2.
3.
*/
//̷θ ϱ Լ̴.
void runMiro(char maze[21][21], PP player) {
for (int i = 0; i < 20; i++) {
for (int j = 0; j < 20; j++) {
if (maze[i][j] == '0')
cout << "";
else if (player->x == j&&player->y == i)
cout << "";
else if (maze[i][j] == '1')
cout << " ";
else if (maze[i][j] == '2')
cout << "";
else if (maze[i][j] == '3')
cout << "";
}
cout << endl;
}
}
//÷̾ ̵ִ Լ
void moveUp(char maze[21][21], PP player) {
if (player->y - 1 >= 0) {//÷̾ ̵ġ yǥ 0 ̻϶ ۵
if (maze[player->y - 1][player->x] != '0')//÷̾ġ ĭ ̾ƴ϶
--player->y; // ÷̾ yǥ
}
return;
}
//÷̾ Ʒ ̵ִ Լ
void moveDown(char maze[21][21], PP player) {
if (player->y + 1 <= 19) {//÷̾ Ʒ̵ ġ yǥ19 ϶۵
if (maze[player->y + 1][player->x] != '0')//÷̾ ġ ĭƷ ̾ƴ϶
++player->y;//÷̾ yǥ Ų
}
return;
}
//÷̾ ̵ִ Լ
void moveLeft(char maze[21][21], PP player) {
if (player->x - 1 >= 0) {//÷̾ ̵ ġ xǥ0̻϶ ۵
if (maze[player->y][player->x - 1] != '0')//÷̾ ġ ٷο ƴ϶
--player->x; //÷̾ xǥ ҽŲ.
}
return;
}
//÷̾ ̵ִ Լ
void moveRight(char maze[21][21], PP player) {
if (player->x + 1 <= 19) {//÷̾ ̵ ġ xǥ19϶ ۵
if (maze[player->y][player->x + 1] != '0')//÷̾ ġ ٷ ƴ϶
++player->x; //÷̾ xǥ Ų
}
return;
}
int main() {
char strMiro[21][21] = {};
P player; //÷̾ǥϱ ü
P stp; // ǥ ϱ ü
P endp; // ǥ ϱ ü
stp.x = 0;// xǥ
stp.y = 0;// yǥ
endp.x = 19;// xǥ
endp.y = 19;// yǥ
player = stp;//ó ÷̾ x,yǥ x,y ǥ
//* ̷θƮ о´
FILE* pFile = NULL;
fopen_s(&pFile, "MazeList.txt", "rt");
char** pMazeList = NULL; //*
//* ⼭ ̷ Ƽ ش.
if (pFile) {
char cCount;
fread(&cCount, 1, 1, pFile);//*ڿ 3 о
int iMazeCount = atoi(&cCount);//*ڸ 3 ٲִ Լ
fread(&cCount, 1, 1, pFile);//* \n о
pMazeList = new char*[iMazeCount];//* 迭 Ҵ
for (int i = 0; i < iMazeCount; ++i) {
int iNameCount = 0;
pMazeList[i] = new char[256]; //*2 迭
while (true) {
fread(&cCount, 1, 1, pFile);//*ϳо̱
if (cCount != '\n') {//*ٵ ƴ϶
pMazeList[i][iNameCount] = cCount;//*о¹ڸ ϳо
++iNameCount;//*ϳо ؾ߰
}
else//*\n ȴٸ
break;//*while
}
pMazeList[i][iNameCount] = 0;//* Ǹ0 ν ڿ ˸
}
fclose(pFile);
int select;
while (1) {
system("cls");
for (int i = 0; i < iMazeCount; i++) {
cout << i + 1 << "." << pMazeList[i] << endl;
}
cout << "̷θ ϳ ϼ:";
cin >> select;
if (cin.fail()) {
cin.clear();
cin.ignore(1024, '\n');
select = INT_MAX;
}
if (select < 1 || select>3 || select == INT_MAX) {
continue;
}
else
break;
}
fopen_s(&pFile, pMazeList[select - 1], "rt");
if (pFile) {
char pText;
for (int i = 0; i < 20; i++) {
fread(strMiro[i], 1, 20, pFile);
fread(&cCount, 1, 1, pFile);
}
fclose(pFile);
}
}
while (true)
{
system("cls");
//̷θ ش.
runMiro(strMiro, &player);
if (player.x == endp.x && player.y == endp.y) {
cout << "̷θ Żعȴ" << endl;
break;
}
cout << "W: S: A: D: Q:";
cout << endl;
int cInput = _getch(); //ܼâ Էޱ Լ cin ٸ enter ٷ Էµ
if (cInput == 'q' || cInput == 'Q')
break;
switch (cInput)
{
case 'w':
case 'W':
moveUp(strMiro, &player);//
break;
case 's':
case 'S':
moveDown(strMiro, &player);//
break;
case 'a':
case 'A':
moveLeft(strMiro, &player);//
break;
case 'd':
case 'D':
moveRight(strMiro, &player);//
break;
}
}
} | true |
1936209d0da552e3ad8c620eca9b0f2c11f05518 | C++ | chiragrathi24/compilationcode1212 | /Basic Calculator.cpp | UTF-8 | 276 | 3.6875 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a, b, sum;
cout<<"This is a basic calculator program"<<endl;
cout<<"Enter the two numbers to find their sum:"<<endl;
cin>>a>>b;
sum=a+b;
cout<<"The sum of the two numbers is:"<<sum<<endl;
return 0;
}
| true |
5152ad64e3f41c4afe50e2a1a36ff18de951e3b6 | C++ | mitchdowd/native | /src/core/common/conditionvariable.cpp | UTF-8 | 629 | 2.78125 | 3 | [
"MIT"
] | permissive | // Local Dependencies
#include "../include/conditionvariable.h"
namespace native
{
ConditionVariable::ConditionVariable(ILockable& lock) : _waiters(0), _lock(lock), _waitCount(0)
{
}
ConditionVariable::~ConditionVariable()
{
}
void ConditionVariable::wait()
{
Atomic::increment(_waitCount);
_lock.release();
_waiters.acquire();
_lock.lock();
Atomic::decrement(_waitCount);
}
void ConditionVariable::signalOne()
{
if (_waitCount > 0)
_waiters.release();
}
void ConditionVariable::signalAll()
{
int toRelease = _waitCount;
for (int i = 0; i < toRelease; i++)
_waiters.release();
}
}
| true |
d7e3ceec641beb6d645c6994df671f3b7576ff44 | C++ | BITERP/PinkRabbitMQ | /src/amqpcpp/libboostasio.h | UTF-8 | 19,772 | 2.546875 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | /**
* LibBoostAsio.h
*
* Implementation for the AMQP::TcpHandler for boost::asio. You can use this class
* instead of a AMQP::TcpHandler class, just pass the boost asio service to the
* constructor and you're all set. See tests/libboostasio.cpp for example.
*
* Watch out: this class was not implemented or reviewed by the original author of
* AMQP-CPP. However, we do get a lot of questions and issues from users of this class,
* so we cannot guarantee its quality. If you run into such issues too, it might be
* better to implement your own handler that interact with boost.
*
*
* @author Gavin Smith <gavin.smith@coralbay.tv>
*/
/**
* Include guard
*/
#pragma once
/**
* Dependencies
*/
#include <memory>
#include <boost/asio/io_context.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/bind/bind.hpp>
#include <boost/function.hpp>
#include "amqpcpp/linux_tcp.h"
// C++17 has 'weak_from_this()' support.
#if __cplusplus >= 201701L
#define PTR_FROM_THIS(T) weak_from_this()
#else
#define PTR_FROM_THIS(T) std::weak_ptr<T>(shared_from_this())
#endif
/**
* Set up namespace
*/
namespace AMQP {
/**
* Class definition
* @note Because of a limitation on Windows, this will only work on POSIX based systems - see https://github.com/chriskohlhoff/asio/issues/70
*/
class LibBoostAsioHandler : public virtual TcpHandler
{
protected:
/**
* Helper class that wraps a boost io_context socket monitor.
*/
class Watcher : public virtual std::enable_shared_from_this<Watcher>
{
private:
/**
* The boost asio io_context which is responsible for detecting events.
* @var class boost::asio::io_context&
*/
boost::asio::io_context & _iocontext;
using strand_weak_ptr = std::weak_ptr<boost::asio::io_context::strand>;
/**
* The boost asio io_context::strand managed pointer.
* @var class std::shared_ptr<boost::asio::io_context>
*/
strand_weak_ptr _wpstrand;
/**
* The boost tcp socket.
* @var class boost::asio::ip::tcp::socket
* @note https://stackoverflow.com/questions/38906711/destroying-boost-asio-socket-without-closing-native-handler
*/
boost::asio::posix::stream_descriptor _socket;
/**
* A boolean that indicates if the watcher is monitoring for read events.
* @var _read True if reads are being monitored else false.
*/
bool _read{false};
/**
* A boolean that indicates if the watcher has a pending read event.
* @var _read True if read is pending else false.
*/
bool _read_pending{false};
/**
* A boolean that indicates if the watcher is monitoring for write events.
* @var _read True if writes are being monitored else false.
*/
bool _write{false};
/**
* A boolean that indicates if the watcher has a pending write event.
* @var _read True if read is pending else false.
*/
bool _write_pending{false};
using handler_cb = boost::function<void(boost::system::error_code,std::size_t)>;
using io_handler = boost::function<void(const boost::system::error_code&, const std::size_t)>;
/**
* Builds a io handler callback that executes the io callback in a strand.
* @param io_handler The handler callback to dispatch
* @return handler_cb A function wrapping the execution of the handler function in a io_context::strand.
*/
handler_cb get_dispatch_wrapper(io_handler fn)
{
const strand_weak_ptr wpstrand = _wpstrand;
return [fn, wpstrand](const boost::system::error_code &ec, const std::size_t bytes_transferred)
{
const strand_shared_ptr strand = wpstrand.lock();
if (!strand)
{
fn(boost::system::errc::make_error_code(boost::system::errc::operation_canceled), std::size_t{0});
return;
}
boost::asio::dispatch(strand->context().get_executor(), boost::bind(fn, ec, bytes_transferred));
};
}
/**
* Binds and returns a read handler for the io operation.
* @param connection The connection being watched.
* @param fd The file descripter being watched.
* @return handler callback
*/
handler_cb get_read_handler(TcpConnection *const connection, const int fd)
{
auto fn = boost::bind(&Watcher::read_handler,
this,
boost::placeholders::_1,
boost::placeholders::_2,
PTR_FROM_THIS(Watcher),
connection,
fd);
return get_dispatch_wrapper(fn);
}
/**
* Binds and returns a read handler for the io operation.
* @param connection The connection being watched.
* @param fd The file descripter being watched.
* @return handler callback
*/
handler_cb get_write_handler(TcpConnection *const connection, const int fd)
{
auto fn = boost::bind(&Watcher::write_handler,
this,
boost::placeholders::_1,
boost::placeholders::_2,
PTR_FROM_THIS(Watcher),
connection,
fd);
return get_dispatch_wrapper(fn);
}
/**
* Handler method that is called by boost's io_context when the socket pumps a read event.
* @param ec The status of the callback.
* @param bytes_transferred The number of bytes transferred.
* @param awpWatcher A weak pointer to this object.
* @param connection The connection being watched.
* @param fd The file descriptor being watched.
* @note The handler will get called if a read is cancelled.
*/
void read_handler(const boost::system::error_code &ec,
const std::size_t bytes_transferred,
const std::weak_ptr<Watcher> awpWatcher,
TcpConnection *const connection,
const int fd)
{
// Resolve any potential problems with dangling pointers
// (remember we are using async).
const std::shared_ptr<Watcher> apWatcher = awpWatcher.lock();
if (!apWatcher) { return; }
_read_pending = false;
if ((!ec || ec == boost::asio::error::would_block) && _read)
{
connection->process(fd, AMQP::readable);
_read_pending = true;
_socket.async_read_some(
boost::asio::null_buffers(),
get_read_handler(connection, fd));
}
}
/**
* Handler method that is called by boost's io_context when the socket pumps a write event.
* @param ec The status of the callback.
* @param bytes_transferred The number of bytes transferred.
* @param awpWatcher A weak pointer to this object.
* @param connection The connection being watched.
* @param fd The file descriptor being watched.
* @note The handler will get called if a write is cancelled.
*/
void write_handler(const boost::system::error_code ec,
const std::size_t bytes_transferred,
const std::weak_ptr<Watcher> awpWatcher,
TcpConnection *const connection,
const int fd)
{
// Resolve any potential problems with dangling pointers
// (remember we are using async).
const std::shared_ptr<Watcher> apWatcher = awpWatcher.lock();
if (!apWatcher) { return; }
_write_pending = false;
if ((!ec || ec == boost::asio::error::would_block) && _write)
{
connection->process(fd, AMQP::writable);
_write_pending = true;
_socket.async_write_some(
boost::asio::null_buffers(),
get_write_handler(connection, fd));
}
}
public:
/**
* Constructor- initialises the watcher and assigns the filedescriptor to
* a boost socket for monitoring.
* @param io_context The boost io_context
* @param wpstrand A weak pointer to a io_context::strand instance.
* @param fd The filedescriptor being watched
*/
Watcher(boost::asio::io_context &io_context,
const strand_weak_ptr wpstrand,
const int fd) :
_iocontext(io_context),
_wpstrand(wpstrand),
_socket(io_context)
{
_socket.assign(fd);
_socket.non_blocking(true);
}
/**
* Watchers cannot be copied or moved
*
* @param that The object to not move or copy
*/
Watcher(Watcher &&that) = delete;
Watcher(const Watcher &that) = delete;
/**
* Destructor
*/
~Watcher()
{
_read = false;
_write = false;
_socket.release();
}
/**
* Change the events for which the filedescriptor is monitored
* @param events
*/
void events(TcpConnection *connection, int fd, int events)
{
// 1. Handle reads?
_read = ((events & AMQP::readable) != 0);
// Read requsted but no read pending?
if (_read && !_read_pending)
{
_read_pending = true;
_socket.async_read_some(
boost::asio::null_buffers(),
get_read_handler(connection, fd));
}
// 2. Handle writes?
_write = ((events & AMQP::writable) != 0);
// Write requested but no write pending?
if (_write && !_write_pending)
{
_write_pending = true;
_socket.async_write_some(
boost::asio::null_buffers(),
get_write_handler(connection, fd));
}
}
};
/**
* Timer class to periodically fire a heartbeat
*/
class Timer : public std::enable_shared_from_this<Timer>
{
private:
/**
* The boost asio io_context which is responsible for detecting events.
* @var class boost::asio::io_context&
*/
boost::asio::io_context & _iocontext;
using strand_weak_ptr = std::weak_ptr<boost::asio::io_context::strand>;
/**
* The boost asio io_context::strand managed pointer.
* @var class std::shared_ptr<boost::asio::io_context>
*/
strand_weak_ptr _wpstrand;
/**
* The boost asynchronous deadline timer.
* @var class boost::asio::deadline_timer
*/
boost::asio::deadline_timer _timer;
using handler_fn = boost::function<void(boost::system::error_code)>;
/**
* Binds and returns a lamba function handler for the io operation.
* @param connection The connection being watched.
* @param timeout The file descripter being watched.
* @return handler callback
*/
handler_fn get_handler(TcpConnection *const connection, const uint16_t timeout)
{
const auto fn = boost::bind(&Timer::timeout,
this,
boost::placeholders::_1,
PTR_FROM_THIS(Timer),
connection,
timeout);
const strand_weak_ptr wpstrand = _wpstrand;
return [fn, wpstrand](const boost::system::error_code &ec)
{
const strand_shared_ptr strand = wpstrand.lock();
if (!strand)
{
fn(boost::system::errc::make_error_code(boost::system::errc::operation_canceled));
return;
}
boost::asio::dispatch(strand->context().get_executor(), boost::bind(fn, ec));
};
}
/**
* Callback method that is called by libev when the timer expires
* @param ec error code returned from loop
* @param loop The loop in which the event was triggered
* @param connection
* @param timeout
*/
void timeout(const boost::system::error_code &ec,
std::weak_ptr<Timer> awpThis,
TcpConnection *const connection,
const uint16_t timeout)
{
// Resolve any potential problems with dangling pointers
// (remember we are using async).
const std::shared_ptr<Timer> apTimer = awpThis.lock();
if (!apTimer) { return; }
if (!ec)
{
if (connection)
{
// send the heartbeat
connection->heartbeat();
}
// Reschedule the timer for the future:
_timer.expires_at(_timer.expires_at() + boost::posix_time::seconds(timeout));
// Posts the timer event
_timer.async_wait(get_handler(connection, timeout));
}
}
/**
* Stop the timer
*/
void stop()
{
// do nothing if it was never set
_timer.cancel();
}
public:
/**
* Constructor
* @param io_context The boost asio io_context.
* @param wpstrand A weak pointer to a io_context::strand instance.
*/
Timer(boost::asio::io_context &io_context,
const strand_weak_ptr wpstrand) :
_iocontext(io_context),
_wpstrand(wpstrand),
_timer(io_context)
{
}
/**
* Timers cannot be copied or moved
*
* @param that The object to not move or copy
*/
Timer(Timer &&that) = delete;
Timer(const Timer &that) = delete;
/**
* Destructor
*/
~Timer()
{
// stop the timer
stop();
}
/**
* Change the expire time
* @param connection
* @param timeout
*/
void set(TcpConnection *connection, uint16_t timeout)
{
// stop timer in case it was already set
stop();
// Reschedule the timer for the future:
_timer.expires_from_now(boost::posix_time::seconds(timeout));
// Posts the timer event
_timer.async_wait(get_handler(connection, timeout));
}
};
/**
* The boost asio io_context.
* @var class boost::asio::io_context&
*/
boost::asio::io_context & _iocontext;
using strand_shared_ptr = std::shared_ptr<boost::asio::io_context::strand>;
/**
* The boost asio io_context::strand managed pointer.
* @var class std::shared_ptr<boost::asio::io_context>
*/
strand_shared_ptr _strand;
/**
* All I/O watchers that are active, indexed by their filedescriptor
* @var std::map<int,Watcher>
*/
std::map<int, std::shared_ptr<Watcher> > _watchers;
/**
* The boost asio io_context::deadline_timer managed pointer.
* THIS IS DISABLED FOR NOW BECAUSE THIS BREAKS IF THERE IS MORE THAN ONE CONNECTION
* @var class std::shared_ptr<Timer>
*/
//std::shared_ptr<Timer> _timer;
/**
* Method that is called by AMQP-CPP to register a filedescriptor for readability or writability
* @param connection The TCP connection object that is reporting
* @param fd The filedescriptor to be monitored
* @param flags Should the object be monitored for readability or writability?
*/
void monitor(TcpConnection *const connection,
const int fd,
const int flags) override
{
// do we already have this filedescriptor
auto iter = _watchers.find(fd);
// was it found?
if (iter == _watchers.end())
{
// we did not yet have this watcher - but that is ok if no filedescriptor was registered
if (flags == 0){ return; }
// construct a new pair (watcher/timer), and put it in the map
const std::shared_ptr<Watcher> apWatcher =
std::make_shared<Watcher>(_iocontext, _strand, fd);
_watchers[fd] = apWatcher;
// explicitly set the events to monitor
apWatcher->events(connection, fd, flags);
}
else if (flags == 0)
{
// the watcher does already exist, but we no longer have to watch this watcher
_watchers.erase(iter);
}
else
{
// Change the events on which to act.
iter->second->events(connection,fd,flags);
}
}
protected:
/**
* Method that is called when the heartbeat frequency is negotiated between the server and the client.
* @param connection The connection that suggested a heartbeat interval
* @param interval The suggested interval from the server
* @return uint16_t The interval to use
*/
/* THIS IS DISABLED FOR NOW BECAUSE THIS BREAKS IF THERE IS MORE THAN ONE CONNECTION */
/*
virtual uint16_t onNegotiate(TcpConnection *connection, uint16_t interval) override
{
// skip if no heartbeats are needed
if (interval == 0) return 0;
// set the timer
_timer->set(connection, interval);
// we agree with the interval
return interval;
}
*/
public:
/**
* Handler cannot be default constructed.
*
* @param that The object to not move or copy
*/
LibBoostAsioHandler() = delete;
/**
* Constructor
* @param io_context The boost io_context to wrap
*/
explicit LibBoostAsioHandler(boost::asio::io_context &io_context) :
_iocontext(io_context),
_strand(std::make_shared<boost::asio::io_context::strand>(_iocontext))
//_timer(std::make_shared<Timer>(_iocontext,_strand))
{
}
/**
* Handler cannot be copied or moved
*
* @param that The object to not move or copy
*/
LibBoostAsioHandler(LibBoostAsioHandler &&that) = delete;
LibBoostAsioHandler(const LibBoostAsioHandler &that) = delete;
/**
* Returns a reference to the boost io_context object that is being used.
* @return The boost io_context object.
*/
boost::asio::io_context &service()
{
return _iocontext;
}
/**
* Destructor
*/
~LibBoostAsioHandler() override = default;
};
/**
* End of namespace
*/
}
| true |
c6d2cf5a6ab6f53c937441d3491549cb3f1c2166 | C++ | pawREP/ZHM5A_TraceSink | /src/FileLogger.cpp | UTF-8 | 979 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "FileLogger.h"
#include <filesystem>
std::filesystem::path FileLogger::getLogFile() const {
const auto logDir = std::filesystem::current_path() / "TraceSink/";
if (!std::filesystem::exists(logDir))
std::filesystem::create_directory(logDir);
int id = 0;
std::filesystem::path logFilePath;
do {
logFilePath = logDir / std::filesystem::path("trace_" + std::to_string(id) + ".log");
++id;
} while (std::filesystem::exists(logFilePath));
return logFilePath;
}
FileLogger::FileLogger() {
path_ = getLogFile();
ofs.open(path_);
}
FileLogger::~FileLogger() {
if (ofs.is_open())
ofs.close();
}
void FileLogger::write(const char* data, int dataLength) const {
if (dataLength == 0)
return;
ofs.write(data, dataLength);
ofs.write("\n", 1);
}
bool FileLogger::isOpen() const {
return ofs.is_open();
}
const std::filesystem::path& FileLogger::path() const {
return path_;
}
| true |
1ca23a2fadfa380bcf9d54c363425eca8a551e1f | C++ | makisto/AVS | /АВС/avs.cpp | UTF-8 | 1,171 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <intrin.h>
#include <sys/time.h>
struct timeval tv1,tv2,dtv;
struct timezone tz;
void time_start()
{
gettimeofday(&tv1, &tz);
}
long time_stop()
{
gettimeofday(&tv2, &tz);
dtv.tv_sec= tv2.tv_sec -tv1.tv_sec;
dtv.tv_usec=tv2.tv_usec-tv1.tv_usec;
if(dtv.tv_usec<0)
{
dtv.tv_sec--;
dtv.tv_usec+=1000000;
}
return dtv.tv_sec*1000+dtv.tv_usec/1000;
}
using namespace std;
unsigned long long pow(unsigned long long x, unsigned long long n)
{
unsigned long long p = 1;
for(int i = 0; i < n; i++)
{
p *= x;
}
return p;
}
unsigned long long factorial(unsigned long long n)
{
unsigned long long p = 1;
for(int i = 1; i <= n; i++)
{
p *= i;
}
return p;
}
int main()
{
unsigned long long a = 20, c = 6000000;
unsigned __int64 i, j, sum = 0;
while(a--)
{
//int start_time = clock();
i = __rdtsc();
//time_start();
factorial(c);
/*j = time_stop();
printf("%ld\n", j);*/
j = __rdtsc();
printf("%I64d\n", j - i);
/*sum += j - i;
int end_time = clock();
printf("%f\n", ((end_time - start_time) / 1000.0) * 1000);*/
}
}
| true |
1b32d2fa0621baaba35ef9b959d00f36473a4c74 | C++ | kolhammer/Psybrus | /Engine/Source/Shared/System/SysFence.h | UTF-8 | 808 | 2.625 | 3 | [] | no_license | /**************************************************************************
*
* File: SysFence.h
* Author: Neil Richardson
* Ver/Date: 15/12/11
* Description:
* Fence for synchronisation of jobs.
*
*
*
*
**************************************************************************/
#ifndef __SYSFENCE_H__
#define __SYSFENCE_H__
#include "Base/BcAtomic.h"
////////////////////////////////////////////////////////////////////////////////
// SysFence
class SysFence
{
public:
SysFence();
~SysFence();
/**
* Increment fence.
*/
void increment();
/**
* Decrement fence.
*/
void decrement();
/**
* Queue up a fence job.
*/
void queue( BcU32 WorkerMask );
/**
* Wait for fence to reach a certain value.
*/
void wait( BcU32 Value = 0 );
private:
BcAtomic< BcU32 > Count_;
};
#endif
| true |
57be5ae2f8064fab7ac5766786392afff067ca3e | C++ | dylan-meiners/gps | /cpp/guidance.cpp | UTF-8 | 15,646 | 2.625 | 3 | [
"MIT"
] | permissive | #include "guidance.h"
extern FILE* fp;
extern bool executing;
GPRMC_STRUCT GPRMC;
Waypoint** waypoints = (Waypoint**)malloc(NUM_INITIAL_WAYPOINT * sizeof(Waypoint*)); //array of Waypoint pointers
Waypoint** next_open = waypoints; //pointer to next open slot
Waypoint** last_waypoint_slot = waypoints + NUM_INITIAL_WAYPOINT - 1; //pointer to last slot in array
double* distances = nullptr;
double* last_distance_slot = nullptr;
wchar_t dbg_buf[256] = { 0 };
bool guidance_init() {
if (waypoints == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING waypoints!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
for (uint i = 0; i < NUM_INITIAL_WAYPOINT; i++) waypoints[i] = NULL;
Position lat_init;
Position long_init;
lat_init.deg = -1;
lat_init.min = -1.0;
lat_init.dir = 63;
long_init.deg = -1;
long_init.min = -1.0;
long_init.dir = 63;
GPRMC.t_h = -1;
GPRMC.t_m = -1;
GPRMC.t_s = -1;
GPRMC.active = 63;
GPRMC.latitude = long_init;
GPRMC.longitude = long_init;
GPRMC.v = -1.0;
GPRMC.ta = -1.0;
GPRMC.d_d = -1;
GPRMC.d_m = -1;
GPRMC.d_y = -1;
GPRMC.mv = -1.0;
GPRMC.mv_dir = 63;
GPRMC.mode = 63;
return true;
}
void guidance_cleanup() {
free(waypoints);
}
bool add_waypoint() {
#ifndef USE_FAKE_DATA
fprintf(fp, "[%s] Attempting to create a new waypoint...\n", current_time().c_str());
if (GPRMC.latitude.deg != -1 && GPRMC.latitude.min != -1 && GPRMC.latitude.dir != 63 &&
GPRMC.longitude.deg != -1 && GPRMC.longitude.min != -1 && GPRMC.longitude.dir != 63) {
if (next_open == last_waypoint_slot) {
uint num_new_slots = last_waypoint_slot - waypoints + NUM_INITIAL_WAYPOINT + 1;
Waypoint** new_waypoints = (Waypoint**)malloc(num_new_slots * sizeof(Waypoint*));
if (new_waypoints == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING new_waypoints!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
for (uint i = 0; i < num_new_slots; i++) new_waypoints[i] = NULL;
for (uint i = 0; i < num_new_slots - NUM_INITIAL_WAYPOINT - 1; i++) new_waypoints[i] = waypoints[i];
free(waypoints);
waypoints = new_waypoints;
last_waypoint_slot = waypoints + num_new_slots - 1;
next_open = waypoints + num_new_slots - NUM_INITIAL_WAYPOINT - 1;
}
if (next_open == nullptr) fprintf(fp, "[%s] Route already built, cannot add current position.\n", current_time().c_str());
else {
Waypoint* w = new_current_waypoint();
if (w == nullptr) fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | COULD NOT CREATE A NEW WAYPOINT\n", current_time().c_str(), __FUNCTION__, __LINE__);
else {
//if there is at least one point
if (waypoints[0] != NULL) {
bool same_exists = false;
for (uint i = 0; i < next_open - waypoints && !same_exists; i++) {
same_exists =
(waypoints[i]->latitude->deg == w->latitude->deg && waypoints[i]->latitude->min == w->latitude->min && waypoints[i]->latitude->dir == w->latitude->dir) &&
(waypoints[i]->longitude->deg == w->longitude->deg && waypoints[i]->longitude->min == w->longitude->min && waypoints[i]->longitude->dir == w->longitude->dir);
}
if (same_exists) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | COULD NOT CREATE A NEW WAYPOINT BECUASE IT ALREADY EXISTS!\n", current_time().c_str(), __FUNCTION__, __LINE__);
free(w);
w = nullptr;
}
}
if (w != nullptr) {
*next_open = w;
next_open++;
fprintf(fp,
"[%s] Successfully created a new waypoint at curent location: %d %f %c %d %f %c\n",
current_time().c_str(),
w->latitude->deg, w->latitude->min, w->latitude->dir,
w->longitude->deg, w->longitude->min, w->longitude->dir
);
}
}
}
}
else fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | CANNOT CREATE NEW WAYPOINT BECAUSE THERE IS NO CURRENT DATA!\n", current_time().c_str(), __FUNCTION__, __LINE__);
fprintf(fp, "[%s] Finished attempting to create a new waypoint.\n", current_time().c_str());
#else
fprintf(fp, "[%s] Attempting to create new waypoints from fake data...\n", current_time().c_str());
if (waypoints[0] == NULL) {
Position* la1 = (Position*)malloc(sizeof(Position));
Position* lo1 = (Position*)malloc(sizeof(Position));
Position* la2 = (Position*)malloc(sizeof(Position));
Position* lo2 = (Position*)malloc(sizeof(Position));
Position* la3 = (Position*)malloc(sizeof(Position));
Position* lo3 = (Position*)malloc(sizeof(Position));
Position* la4 = (Position*)malloc(sizeof(Position));
Position* lo4 = (Position*)malloc(sizeof(Position));
if (la1 == NULL || lo1 == NULL || la2 == NULL || lo2 == NULL || la3 == NULL || lo3 == NULL || la4 == NULL || lo4 == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING a fake Position!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
la1->deg = 46;
la1->min = 0.197166667;
la1->dir = 'N';
lo1->deg = 91;
lo1->min = 18.225333333;
lo1->dir = 'W';
la2->deg = 46;
la2->min = 1.587;
//la2->min = 0.826166667;
la2->dir = 'N';
lo2->deg = 91;
lo2->min = 18.281166667;
//lo2->min = 10.797666667;
lo2->dir = 'W';
la3->deg = 46;
la3->min = 0.826166667;
la3->dir = 'N';
lo3->deg = 91;
lo3->min = 19.053;
lo3->dir = 'W';
la4->deg = 46;
la4->min = 0.105833333;
la4->dir = 'N';
lo4->deg = 91;
lo4->min = 18.854333333;
lo4->dir = 'W';
Waypoint* w1 = (Waypoint*)malloc(sizeof(Waypoint));
Waypoint* w2 = (Waypoint*)malloc(sizeof(Waypoint));
Waypoint* w3 = (Waypoint*)malloc(sizeof(Waypoint));
Waypoint* w4 = (Waypoint*)malloc(sizeof(Waypoint));
if (w1 == NULL || w2 == NULL || w3 == NULL || w4 == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING a fake Position!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
w1->latitude = la1;
w1->longitude = lo1;
w1->global_rel_x = 0;
w1->global_rel_y = 0;
w1->local_rel_x = 0;
w1->local_rel_y = 0;
w2->latitude = la2;
w2->longitude = lo2;
w2->global_rel_x = 0;
w2->global_rel_y = 0;
w2->local_rel_x = 0;
w2->local_rel_y = 0;
w3->latitude = la3;
w3->longitude = lo3;
w3->global_rel_x = 0;
w3->global_rel_y = 0;
w3->local_rel_x = 0;
w3->local_rel_y = 0;
w4->latitude = la4;
w4->longitude = lo4;
w4->global_rel_x = 0;
w4->global_rel_y = 0;
w4->local_rel_x = 0;
w4->local_rel_y = 0;
waypoints[0] = w1;
waypoints[1] = w2;
waypoints[2] = w3;
waypoints[3] = w4;
next_open += 4;
fprintf(fp, "[%s] Finished attempting to create new waypoints from fake data.\n", current_time().c_str());
printWaypoints();
}
else fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | COULD NOT CREATE FAKE WAYPOINTS BECUASE THEY ALREADY EXIST!\n", current_time().c_str(), __FUNCTION__, __LINE__);
#endif
return true;
}
bool build() {
fprintf(fp, "[%s] Building route...\n", current_time().c_str());
if (next_open - waypoints == 0) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | Cannot build route if there are no waypoints!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
//first, shave nulls
uint acc = 0; //find number of open slots
for (int i = 0; i < last_waypoint_slot - waypoints; i++) if (waypoints[i] == NULL) acc++;
uint num_new_slots = last_waypoint_slot - waypoints - acc; //shave off NULLs
Waypoint** new_waypoints = (Waypoint**)malloc(num_new_slots * sizeof(Waypoint*));
if (new_waypoints == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING new_waypoints!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
for (uint i = 0; i < num_new_slots; i++) new_waypoints[i] = waypoints[i];
free(waypoints);
waypoints = new_waypoints;
last_waypoint_slot = waypoints + num_new_slots;
next_open = nullptr;
fprintf(fp, "[%s] Shaved off NULLs.\n", current_time().c_str());
fprintf(fp, "[%s] You can no longer add waypoints, unless they are fake, in which case they will reset.\n", current_time().c_str());
fprintf(fp, "[%s] Calculating distances...\n", current_time().c_str());
for (uint i = 0; i < num_new_slots; i++) { //find relative distances for the waypoints, based on the first one being (0, 0)
waypoints[i]->global_rel_x = (double)waypoints[i]->longitude->deg * LONG_DEG_FEET + waypoints[i]->longitude->min * LONG_MIN_TO_FEET_MULTIPLIER;
waypoints[i]->global_rel_y = (double)waypoints[i]->latitude->deg * LAT_DEG_FEET + waypoints[i]->latitude->min * LAT_MIN_TO_FEET_MULTIPLIER;
}
//then, find the global relative values
for (uint i = num_new_slots - 1; i > 0; i--) {
waypoints[i]->global_rel_x -= waypoints[0]->global_rel_x;
waypoints[i]->global_rel_y -= waypoints[0]->global_rel_y;
}
waypoints[0]->global_rel_x = 0.0;
waypoints[0]->global_rel_y = 0.0;
//lastly, find the local relative values
for (uint i = num_new_slots - 1; i > 0; i--) {
waypoints[i]->local_rel_x = waypoints[i]->global_rel_x - waypoints[i - 1]->global_rel_x;
waypoints[i]->local_rel_y = waypoints[i]->global_rel_y - waypoints[i - 1]->global_rel_y;
}
distances = (double*)malloc(num_new_slots * sizeof(double)); //now, create an array of distances in between the waypoints
for (uint i = 0; i < num_new_slots; i++) distances[i] = 0.0;
if (distances == NULL) {
fprintf(fp, "[%s] FATAL: ERROR | At function: \"%s\", line: %d | MALLOC FAILED CREATING distances!\n", current_time().c_str(), __FUNCTION__, __LINE__);
return false;
}
for (uint i = 0; i < num_new_slots; i++) {
distances[i] = sqrt(
sq(waypoints[(i + 1 != num_new_slots) ? i + 1 : 0]->global_rel_x - waypoints[i]->global_rel_x) +
sq(waypoints[(i + 1 != num_new_slots) ? i + 1 : 0]->global_rel_y - waypoints[i]->global_rel_y)
);
}
last_distance_slot = distances + num_new_slots - 1;
fprintf(fp, "[%s] Calculated distances.\n", current_time().c_str());
fprintf(fp, "[%s] Route built! Waypoints are:\n", current_time().c_str());
printWaypoints();
double total_dist = 0.0;
for (uint i = 0; i < num_new_slots; i++) total_dist += distances[i];
fprintf(fp, "[%s] Total distance is %f miles\n", current_time().c_str(), total_dist / 5280);
return true;
}
double slope(Waypoint* one, Waypoint* two) {
/*int index_of_next = (i + 1 != last_waypoint_slot - waypoints) ? i + 1 : 0;
x_diff = waypoints[index_of_next]->global_rel_x - waypoints[i]->global_rel_x;
y_diff = waypoints[index_of_next]->global_rel_y - waypoints[i]->global_rel_y;
return x_diff / y_diff;*/
return -1.0;
}
//this f() is the big one
//TODO: CHECK IF NO DATA
void step() {
static double distance = 0.0;
double dist_to_path = 0.0;
uint index_of_distance = 0;
uint index_of_next_distance = 0;
#ifndef USE_FAKE_DATA
Waypoint* current = new_current_waypoint();
#else
Waypoint* current = (Waypoint*)malloc(sizeof(Waypoint));
Position* lat = (Position*)malloc(sizeof(Position));
Position* lon = (Position*)malloc(sizeof(Position));
if (current == NULL || lat == NULL || lon == NULL) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | MALLOC FAILED WHEN CREATING WAYPOINT STRUCT, OR POSITION STRUCT\n", current_time().c_str(), __FUNCTION__, __LINE__);
}
lat->deg = 46;
lat->min = 0.217666667;
lat->dir = 'N';
lon->deg = 91;
lon->min = 18.224666667;
lon->dir = 'W';
current->latitude = lat;
current->longitude = lon;
#endif
current->global_rel_x =
((double)current->longitude->deg * LONG_DEG_FEET + current->longitude->min * LONG_MIN_TO_FEET_MULTIPLIER)
-
((double)waypoints[0]->longitude->deg * LONG_DEG_FEET + waypoints[0]->longitude->min * LONG_MIN_TO_FEET_MULTIPLIER);
current->global_rel_y =
((double)current->latitude->deg * LAT_DEG_FEET + current->latitude->min * LAT_MIN_TO_FEET_MULTIPLIER)
-
((double)waypoints[0]->latitude->deg * LAT_DEG_FEET + waypoints[0]->latitude->min * LAT_MIN_TO_FEET_MULTIPLIER);
bool searching = true;
double total_dist = 0.0;
for (uint i = 0; i < last_distance_slot - distances && searching; i++) {
total_dist += distances[i];
if (distance < total_dist) {
index_of_distance = i;
index_of_next_distance = i < last_distance_slot - distances - 1 ? i + 1 : 0;
searching = false;
}
}
double slope =
(waypoints[index_of_next_distance]->global_rel_y - waypoints[index_of_distance]->global_rel_y)
/
(waypoints[index_of_next_distance]->global_rel_x - waypoints[index_of_distance]->global_rel_x);
double int_x = 0.0;
double int_y = 0.0;
//I solved a system of equations for the equation of the path, and the equation of the current waypoint with slope perpendicular to the path.
//The equation of the current wayopint is solved for x then substituded into the path's equation
int_y =
(-slope * waypoints[index_of_distance]->global_rel_x + waypoints[index_of_distance]->global_rel_y + slope * current->global_rel_x + sq(slope) * current->global_rel_y)
/
(sq(slope) + 1);
int_x = (int_y + slope * waypoints[index_of_distance]->global_rel_x - waypoints[index_of_distance]->global_rel_y) / slope;
//we then find the distance between the current point and the path
dist_to_path = sqrt(sq(int_x - current->global_rel_x) + sq(int_y - current->global_rel_y));
double target_distance = 0.0;
if (dist_to_path <= HANDS_OFF_ZONE) {
searching = true;
total_dist = 0.0;
target_distance = distance + THROW_DISTANCE;
}
for (uint i = 0; i < last_distance_slot - distances && searching; i++) {
total_dist += distances[i];
if (target_distance < total_dist) {
index_of_distance = i;
searching = false;
}
}
slope =
(waypoints[index_of_next_distance]->global_rel_y - waypoints[index_of_distance]->global_rel_y)
/
(waypoints[index_of_next_distance]->global_rel_x - waypoints[index_of_distance]->global_rel_x);
double target_x = 0.0;
double target_y = 0.0;
double angle = atan(slope);
target_x = (target_distance - (index_of_distance != 0 ? distances[index_of_distance] : 0)) * cos(angle) + waypoints[index_of_distance]->global_rel_x;
target_y = (target_distance - (index_of_distance != 0 ? distances[index_of_distance] : 0)) * sin(angle) + waypoints[index_of_distance]->global_rel_y;
angle = atan((current->global_rel_y - target_y) / (current->global_rel_x - target_x)) * 180.0 / M_PI;
}
Waypoint* new_current_waypoint() {
Waypoint* w = (Waypoint*)malloc(sizeof(Waypoint));
if (w == NULL) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | MALLOC FAILED WHEN CREATING WAYPOINT STRUCT\n", current_time().c_str(), __FUNCTION__, __LINE__);
return nullptr;
}
Position* latitude = (Position*)malloc(sizeof(Position));
if (latitude == NULL) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | MALLOC FAILED WHEN CREATING LATITUDE STRUCT\n", current_time().c_str(), __FUNCTION__, __LINE__);
return nullptr;
}
else {
latitude->deg = GPRMC.latitude.deg;
latitude->min = GPRMC.latitude.min;
latitude->dir = GPRMC.latitude.dir;
}
Position* longitude = (Position*)malloc(sizeof(Position));
if (longitude == NULL) {
fprintf(fp, "[%s] ERROR | At function: \"%s\", line: %d | MALLOC FAILED WHEN CREATING LONGITUDE STRUCT\n", current_time().c_str(), __FUNCTION__, __LINE__);
return nullptr;
}
else {
longitude->deg = GPRMC.longitude.deg;
longitude->min = GPRMC.longitude.min;
longitude->dir = GPRMC.longitude.dir;
}
w->latitude = latitude;
w->longitude = longitude;
w->global_rel_x = 0;
w->global_rel_y = 0;
w->local_rel_x = 0;
w->local_rel_y = 0;
return w;
}
double sq(double x) { return x * x; } | true |
6a22464afc4edcdb815fa6e822427f79d21fbf39 | C++ | Liuguanli/ModelReuse | /include/PGM.h | UTF-8 | 1,177 | 2.578125 | 3 | [] | no_license | #ifndef PGM_
#define PGM_
#include <vector>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include "pgm_index.hpp"
#include "pgm_index_dynamic.hpp"
template<int error>
class PGMX
{
public:
DynamicPGMIndex<uint64_t, uint64_t, PGMIndex<uint64_t, error>> pgm_;
void build(const std::vector<uint64_t> &data)
{
std::vector<std::pair<uint64_t, uint64_t>> reformatted_data;
reformatted_data.reserve(data.size());
uint64_t length = data.size();
for (uint64_t i = 0; i < length; i++)
{
reformatted_data.emplace_back(data[i], i);
}
auto start = std::chrono::high_resolution_clock::now();
pgm_ = decltype(pgm_)(reformatted_data.begin(), reformatted_data.end());
auto end = std::chrono::high_resolution_clock::now();
std::cout<< "build time: " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count() << std::endl;
}
void find(const uint64_t lookup_key)
{
auto index = pgm_.find(lookup_key);
}
void insert(const uint64_t insert_key, const uint64_t index)
{
pgm_.insert(insert_key, index);
}
};
#endif | true |
ad5634443c0fc2d849dea82794e50b2fb11ce55d | C++ | xlCh/leetcode | /A 228 Summary Ranges.cpp | UTF-8 | 617 | 3.5 | 4 | [] | no_license | //https://leetcode.com/problems/summary-ranges/
//输出一串数字的范围,例如给出[0,1,2,4,5,7],返回["0->2","4->5","7"]
vector<string> summaryRanges(vector<int>& nums) {
int i = 0;
vector<string> rangeV;
while(i<nums.size()) {
int start = i;
stringstream s;
while(i != nums.size()-1 && nums[i+1] == nums[i]+1)
i++;
if(i-start == 0)
s << nums[i++];
else
s << nums[start] << "->" << nums[i++];
rangeV.push_back(s.str());
}
return rangeV;
}
| true |
40d7c4dd78a7c7f0013a276bbc6913a5c448f4f0 | C++ | Twice22/acceleratedcpp | /Chapter7/chapter7.3/chapter7.3/xreftable.cpp | UTF-8 | 1,241 | 3.25 | 3 | [] | no_license | #include "stdafx.h"
#include "xreftable.h"
#include "split.h"
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// find all the lines that refer to each word in the input
map<string, vector<int> > xref(istream& in, vector<string> find_words(const string&)) {
string wl;
int line = 0;
map<string, vector<int> > ret;
while (getline(cin, wl)) {
++line;
vector<string> word_vec = find_words(wl);
for (vector<string>::const_iterator it = word_vec.begin(); it != word_vec.end(); it++) {
// Answer to Q7.3
// if we don't find the line in ret[*it] then add that line
if (find(ret[*it].begin(), ret[*it].end(), line) == ret[*it].end()) {
ret[*it].push_back(line);
}
}
}
return ret;
}
// display word along with the lines in which they occur.
void display_xref(const map<string, vector<int> >& xtable) {
for (map<string, vector<int> >::const_iterator it = xtable.begin();
it != xtable.end(); ++it) {
cout << "word " << it->first << " appears on line(s): ";
vector<int>::const_iterator iter = it->second.begin();
cout << *iter;
++iter;
while ( iter != it->second.end()) {
cout << ", " << *iter;
++iter;
}
cout << endl;
}
} | true |
aec62eed82b9b4718c626d39bc8bc40585a190cb | C++ | strange-hawk/data_structure_algorithms | /linkedlist/middle_linked_list.cpp | UTF-8 | 895 | 3.703125 | 4 | [] | no_license | #include<iostream>
using namespace std;
struct Node
{
int key;
Node *next;
Node(int key){
this->key = key;
this->next = NULL;
}
};
// naive solution
void printNode(Node *head){
if(head==NULL){
cout<<'empty'<<endl;
return;
}
int count =0;
Node *count_nodes = head ;
while(count_nodes!=NULL){
count++;
count_nodes = count_nodes -> next;
}
Node * act_node = head;
for(int i=0;i<count/2;i++){
act_node = act_node->next;
}
cout<<act_node->key<<endl;
}
// optimised way
void printNode(Node *head){
if(head==NULL){
cout<<'empty'<<endl;
return;
}
Node *cur = head;
Node *cur_nextnext = head;
while(cur_nextnext!=NULL && cur_nextnext->next != NULL){
cur_nextnext=cur_nextnext->next->next;
cur=cur->next;
}
cout<<cur->key<<endl;
} | true |
c1cba60ef26298bf78d0dbbfc52bd023c32e75df | C++ | My-Cpp-projects/Tetris-SDL-v1.2 | /Tetris SDL v1.2/src/model/Figure.cpp | UTF-8 | 590 | 2.90625 | 3 | [] | no_license |
#include "../../include/factory/FigureFactory.h"
tetris::Figure::Figure(int** figureMatrix, FigureType type)
: mType(type)
{
for (int i = 0; i < FIGURE_WIDTH; ++i)
{
for (int j = 0; j < FIGURE_HEIGHT; ++j)
{
mFigureMatrix[i][j] = figureMatrix[i][j];
}
}
}
void tetris::Figure::setCoordinates(int x, int y)
{
setCoordinateX(x);
setCoordinateY(y);
}
void tetris::Figure::setCoordinateX(int x)
{
mX = x;
}
void tetris::Figure::setCoordinateY(int y)
{
mY = y;
}
int tetris::Figure::getXCoordinate()
{
return mX;
}
int tetris::Figure::getYCoordinate()
{
return mY;
}
| true |
612d14274e447bd028c1e31b4e4c8988642f51a4 | C++ | AhriHaran/Unity | /Game_Girls_AutoChess_2019_06_04/Lib/TimeManager.cpp | UTF-8 | 582 | 2.59375 | 3 | [
"Unlicense"
] | permissive | #include "TimeManager.h"
namespace JEngine
{
TimeManager::TimeManager()
{
m_bUseFPS = false;
m_nFPS = 30;
m_dwLastTime = GetTickCount();
m_dwCurTime = GetTickCount();
}
TimeManager::~TimeManager()
{
}
void TimeManager::init(bool useFPS, int FPS)
{
m_bUseFPS = useFPS;
m_nFPS = FPS;
}
bool TimeManager::Update()
{
m_dwCurTime = GetTickCount();
if (m_bUseFPS)
{
if (m_dwCurTime - m_dwLastTime < 1000 / m_nFPS)
return false;
}
m_fElapseTime = (m_dwCurTime - m_dwLastTime) / 1000.0f;
m_dwLastTime = m_dwCurTime;
return true;
}
} | true |
986cad37c5b26cc87b17c3ec2177d6a14687311a | C++ | Milswanca/OpenGL_FINAL | /OpenGL/Engine/Source/Public/Core/InputSystem.h | UTF-8 | 1,097 | 2.6875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Actor.h"
#include "DataTypes.h"
#define NUM_KEYS 256
class InputSystem : public Actor
{
public:
InputSystem(const ObjectInitData& _OI);
public:
virtual void PostUpdate(const float _deltaTime) override;
bool IsKeyJustPressed(unsigned char _key) const;
bool IsKeyJustReleased(unsigned char _key) const;
bool IsKeyDown(unsigned char _key) const;
bool IsMouseButtonJustPressed(MouseButtons _key) const;
bool IsMouseButtonJustReleased(MouseButtons _key) const;
bool IsMouseButtonDown(MouseButtons _key) const;
Vector3 GetMousePosition() const;
Vector3 GetMouseDelta() const;
protected:
void KeyPressed(unsigned char _key);
void KeyReleased(unsigned char _key);
void MouseMoved(unsigned int _x, unsigned int _y);
void MouseButtonPressed(unsigned char _button);
void MouseButtonReleased(unsigned char _button);
private:
// Keystates of all keys
// 1st byte = last frame value
// 2nd byte = this frame value
// 3rd & 4th are unused
char m_keyStates[NUM_KEYS];
char m_mouseStates[3];
Vector3 m_mouseLast;
Vector3 m_mouseLocation;
friend Window;
}; | true |
fff4d02902ac8cc519c181a64a786b60126b01cc | C++ | Dishu5588/liverpool | /student data using static data member.cpp | UTF-8 | 494 | 3.59375 | 4 | [] | no_license | #include<iostream>
using namespace std;
class student
{
public:
int roll;
string name;
static int addno;
student(string n)
{
addno++;
roll=addno;
name=n;
}
void display()
{
cout<<" name "<<name<<endl<<" roll "<<roll<<endl;
}
};
int student::addno=0;
int main()
{
student s1("john");
student s2("ravi");
student s3("khan");
s1.display();
s2.display();
s3.display();
cout<<"number of addmission "<<s3.addno<<endl;
return 0;
}
| true |
e68b07a1fe94a1703f531aea40eb55008b1c7173 | C++ | plzrobbob/CSE461_FileSystem | /CSE461Labs/Sdisk.h | UTF-8 | 1,996 | 3.640625 | 4 | [] | no_license | /*
Cameron Maclean
CSUSB
November 11th, 2019
lab3/4
*/
#ifndef SDISK_H
#define SDISK_H
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class Sdisk
{
public:
Sdisk(string _diskname, int _numberofblocks, int _blocksize);
int getblock(int blocknumber, string& buffer);
int putblock(int blocknumber, string buffer);
int getnumberofblocks(); //accessor function
int getblocksize(); //accessor function
private:
string diskname;
int numberofblocks;
int blocksize;
};
Sdisk::Sdisk(string _diskname, int _numberofblocks, int _blocksize)
{
diskname = _diskname;
numberofblocks = _numberofblocks;
blocksize = _blocksize;
ifstream infile;
infile.open(diskname.c_str());
if (!infile.good())
{
cout << "Disk file not found, creating..." << endl;
ofstream outfile;
outfile.open(diskname.c_str());
for (int i = 0; i < numberofblocks * blocksize; ++i)
{
outfile << "#";
}
}
else
{
cout << "Disk file opened." << endl;
}
}
int Sdisk::getblock(int blocknumber, string& buffer)
{
// Find file to read from
fstream iofile;
iofile.open(this->diskname.c_str(), ios::in); // Ready for input
// Check if file failed to open to read
if (iofile.fail())
{
// For failure
return 0;
}
// Start at blocknumber k starts at k * blocksize
iofile.seekg(blocknumber * this->blocksize);
buffer = ""; // char c;
// Iterate through entire block to initialize buffer
for (int i = 0; i < this->blocksize; i++)
{
buffer += iofile.get();
}
// Close the file after reading it.
iofile.close();
// For success
return 1;
}
int Sdisk::putblock(int blocknumber, string buffer)
{
fstream iofile;
iofile.open(diskname.c_str(), ios::in | ios::out);
if (!iofile.good())
{
return 0;
}
iofile.seekp(blocknumber*blocksize);
iofile.write(buffer.c_str(), buffer.length());
return 1;
}
int Sdisk::getnumberofblocks()
{
return numberofblocks;
}
int Sdisk::getblocksize()
{
return blocksize;
}
#endif
| true |
271423ea2ce15fe82121b345ad3a3a26809fe00b | C++ | ibas2020/Programming-Labs | /Practice_07.09/Task_1/main.cpp | UTF-8 | 1,093 | 3.625 | 4 | [] | no_license | // Задача 1. Даны 2 перменные, ввод с клавиатуры, Поменять местами значения переменных 2-мя способами
// 1) с использованием вспомогательной перменной. 2) без использований вспомогательных переменных
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cout << "Введите значения a и b: "; // вводим перменные
cin >> a >> b;
c = a; // 1 способ
a = b;
b = c;
cout << "Первый способ: a = " << a << ", b = " << b << endl;
b = a; // вернем переменным их исходные значения для 2-ого способа
a = c;
b = b + a; // второй способ (без переменной)
a = b - a;
b = b - a;
cout << "Второй способ: a = " << a << ", b = " << b;
return 0;
}
| true |
33885f7984210a050818c0e3025cb7aba97e1483 | C++ | fbdp1202/AlgorithmParty | /BOJ/2000/2553.cpp | UTF-8 | 562 | 2.75 | 3 | [] | no_license | // baekjoon 2553 yechan
#include <cstdio>
#include <algorithm>
using namespace std;
int N;
int main()
{
scanf("%d", &N);
int ret = 1;
int count2 = 0, count5 = 0;
int tmp;
for (int i=1; i<=N; i++) {
tmp = i;
while (tmp % 10 == 0) tmp /= 10;
while (tmp % 2 == 0) tmp /= 2, count2++;
while (tmp % 5 == 0) tmp /= 5, count5++;
ret *= tmp;
ret %= 10;
}
count2 -= min(count2, count5);
count5 -= min(count2, count5);
while (count2--) {
ret *= 2;
ret %= 10;
}
while (count5--) {
ret *= 5;
ret %= 10;
}
printf("%d\n", ret);
return 0;
} | true |
59314631a2f76628847134aaddb546ba6b2dffb7 | C++ | huhumeng/algorithm | /leetcode/371.两整数之和.cpp | UTF-8 | 967 | 3.40625 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=371 lang=cpp
*
* [371] 两整数之和
*
* https://leetcode-cn.com/problems/sum-of-two-integers/description/
*
* algorithms
* Easy (51.62%)
* Total Accepted: 13.8K
* Total Submissions: 26.7K
* Testcase Example: '1\n2'
*
* 不使用运算符 + 和 - ,计算两整数 a 、b 之和。
*
* 示例 1:
*
* 输入: a = 1, b = 2
* 输出: 3
*
*
* 示例 2:
*
* 输入: a = -2, b = 3
* 输出: 1
*
*/
#if (__GNUC__ == 7 || __GNUC__ == 4)
#include "common.h"
#endif
class Solution {
public:
int getSum(int a, int b) {
int c;
for(;b != 0;){
c = ((unsigned int)(a & b)) << 1;
a = a ^ b;
b = c;
}
return a;
}
};
#if (__GNUC__ == 7 || __GNUC__ == 4)
int main(){
int a, b;
cin >> a >> b;
cout << Solution().getSum(a, b) << endl;
return 0;
}
#endif
| true |
960fdc8b6a6bae26afa4cddf6b35ac1e593dd834 | C++ | refatmonjur/CSC212 | /p1/deque.cpp | UTF-8 | 3,300 | 3.578125 | 4 | [] | no_license | /* This is the implementation file for the deque, where you will define how the
* abstract functionality (described in the header file interface) is going to
* be accomplished in terms of explicit sequences of C++ statements. */
#include "deque.h"
#include <stdio.h>
#include <cassert>
/* NOTE:
* We will use the following "class invariants" for our data members:
* 1. data points to a buffer of size cap.
* 2. data[front_index,...,next_back_index-1] are the valid members of the
* deque, where the indexing is *circular*, and works modulo cap.
* 3. the deque is empty iff front_index == next_back_index, and so we must
* resize the buffer *before* size == cap. */
#ifndef INIT_CAP
#define INIT_CAP 4
#endif
deque::deque()
{
/* setup a valid, empty deque */
this->cap = INIT_CAP;
this->data = new int[cap];
this->front_index = 0;
this->next_back_index = 0;
/* NOTE: the choice of 0 is arbitrary; any valid index works. */
}
/* range constructor */
deque::deque(int* first, int* last)
{
if (last <= first) return;
this->cap = last - first + 1;
this->data = new int[this->cap];
this->front_index = 0;
this->next_back_index = this->cap-1;
for (size_t i = 0; i < this->cap-1; i++) {
this->data[i] = first[i];
}
}
/* l-value copy constructor */
deque::deque(const deque& D)
{
/* TODO: write me. */
}
/* r-value copy constructor */
deque::deque(deque&& D)
{
/* steal data from D */
this->data = D.data;
this->front_index = D.front_index;
this->next_back_index = D.next_back_index;
this->cap = D.cap;
D.data = NULL;
}
deque& deque::operator=(deque RHS)
{
/* TODO: write me. See the r-value copy constructor for inspiration. */
return *this;
}
deque::~deque()
{
/* NOTE: to make the r-value copy more efficient, we allowed for the
* possibility of data being NULL. */
if (this->data != NULL) delete[] this->data;
}
int deque::back() const
{
/* for debug builds, make sure deque is nonempty */
assert(!empty());
/* TODO: write me. */
return 0; /* prevent compiler error. */
}
int deque::front() const
{
/* for debug builds, make sure deque is nonempty */
assert(!empty());
/* TODO: write me. */
return 0; /* prevent compiler error. */
}
size_t deque::capacity() const
{
return this->cap - 1;
}
int& deque::operator[](size_t i) const
{
assert(i < this->size());
return this->data[(front_index + i) % this->cap];
}
size_t deque::size() const
{
/* just compute number of elements between front and back, wrapping
* around modulo the size of the data array. */
/* TODO: write me. */
return 0; /* prevent compiler error. */
}
bool deque::empty() const
{
return (next_back_index == front_index);
}
bool deque::needs_realloc()
{
return ((next_back_index + 1) % cap == front_index);
}
void deque::push_front(int x)
{
/* TODO: write me. */
}
void deque::push_back(int x)
{
/* TODO: write me. */
}
int deque::pop_front()
{
assert(!empty());
/* TODO: write me. */
return 0; /* prevent compiler error. */
}
int deque::pop_back()
{
assert(!empty());
/* TODO: write me. */
return 0; /* prevent compiler error. */
}
void deque::clear()
{
/* TODO: write me. */
}
void deque::print(FILE* f) const
{
for(size_t i=this->front_index; i!=this->next_back_index;
i=(i+1) % this->cap)
fprintf(f, "%i ",this->data[i]);
fprintf(f, "\n");
}
| true |
40bcf6ebb7cf0e71c080372066b0e26b39e8f09b | C++ | ruguangyou/ossu-cs | /Core CS/core theory/Data Structure and Algorithm/problem set/TSP/tsp_3.cpp | UTF-8 | 2,411 | 2.765625 | 3 | [] | no_license | #include <cstdio>
// #include "vector.h"
using namespace std;
#define DEFAULT_CAPACITY 10
template <typename T> class Vector {
protected:
int _size; int _capacity; T* _elem;
void expand() {
if (_size < _capacity) return;
if (_capacity < DEFAULT_CAPACITY) _capacity = DEFAULT_CAPACITY;
T* oldElem = _elem; _elem = new T[_capacity <<= 1];
for (int i = 0; i < _size; i++)
_elem[i] = oldElem[i];
delete [] oldElem;
}
public:
Vector (int c = DEFAULT_CAPACITY, int s = 0, T v = 0) {
_elem = new T[_capacity = c];
for (_size = 0; _size < s; _elem[_size++] = v) ;
}
~Vector() { delete [] _elem; }
int size() { return _size; }
int capacity() { return _capacity; }
bool empty() { return !_size; }
bool full() { return _size == _capacity; }
T& operator [] (int r) const { return _elem[r]; }
int insert (int r, T const& e) {
expand();
int n = _size++;
while (n > r) _elem[n] = _elem[--n];
_elem[r] = e;
return r;
}
int insert (T const& e) { return insert(_size, e); }
T remove (int r) {
T e = _elem[r];
_size--;
while (r < _size) _elem[r] = _elem[++r];
return e;
}
};
typedef enum { UNDISCOVERED, DISCOVERED } VStatus;
struct Node {
int data; int depth;
Node* next;
VStatus status;
Node(int d = 0) : data(d), depth(0), next(NULL), status(UNDISCOVERED) {}
};
int DFS(Vector<Node*> const& V, int j) {
int local_max = 1; int temp;
if (!V[j]) return local_max;
V[j]->status = DISCOVERED;
Node* p = V[j]->next;
while (p) {
int d = p->data;
if (V[d-1] && V[d-1]->status == DISCOVERED) temp = 1 + V[d-1]->depth;
else temp = 1 + DFS(V, d-1);
if (local_max < temp) local_max = temp;
p = p->next;
}
V[j]->depth = local_max;
return local_max;
}
int main() {
setvbuf(stdin, new char[1<<20], _IOFBF, 1<<20);
setvbuf(stdout, new char[1<<20], _IOFBF, 1<<20);
int n, m; int u, v; int max = 1, temp;
scanf("%d%d", &n, &m);
Vector<Node*> V(n, n, NULL);
for (int i = 0; i < m; i++) {
scanf("%d%d", &u, &v);
if (!V[u-1]) { V[u-1] = new Node(u); V[u-1]->next = new Node(v); }
else { Node* temp = new Node(v); temp->next = V[u-1]->next; V[u-1]->next = temp; }
}
for (int j = 0; j < n; j++) {
if (V[j] && V[j]->status == UNDISCOVERED) {
temp = DFS(V, j);
if (max < temp) max = temp;
}
}
printf("%d\n", max);
return 0;
} | true |
80243002792e4bc6a69ff392ba565af3d50832d1 | C++ | MrFreelax/Projet-A1-groupe-6 | /Module 1 et 2/coeur/coeur.ino | UTF-8 | 2,684 | 2.84375 | 3 | [] | no_license | #include "param.h"
#include "coeur.h"
#include "cardio.h"
int tpsDer; //On inclut une variable globale prennant le dernier temps calculé du pouls
void setup()
{
tpsDer = millis(); //On donne le temps depuis lequelle a démaré l'arduino à la variable globale
for (int i = 0; i < 10; i++) //Boucle allant de 0 à 9
{ //Cette boucle permet d'initialiser
pinMode(pinLed[i], OUTPUT); //Les sorties digital en sortie
digitalWrite(pinLed[i], LOW); //Et ne pas mettre de courant dans ses sorties
}
Serial.begin(9600); //On initialise le port série à 9600 baud (bit/s)
}
void loop()
{
while (millis() < 100000) //Boucle qui permet de de donner un temps de 100s au programme
{ //Pour calculé le pouls
if (analogRead(A0) > 640) //Si la sortie A0 est supérieur a 640 la boucle peut être effectué
{
Complet(); //Ses quatres fonctions sont initialisé ici car grâce au fichier param.h
chenille(); //Il permet de gerer l'affichage des LEDs
UnDeux(); //Il y a seulement une seul de ses fonctions qui pourra être définis
UnTrois(); //Donc on met dans cette boucle les quatres fonctions
Random();
Choix();
//Pour afficher le résultat dans le fichier .csv
//On utilise processing qui récupère les informations au port série
//Pour être sure que processing prenne toutes les valeurs, on lui donne
//Une lettre pour le début et une lettre pour la fin
Serial.print("D"); //On affiche la lettre du début
Serial.print(temps()); //On affiche la fonction temps situé dans le fichier cardio.ino
Serial.print(";"); //On affiche le point virgule pour le fichier csv
//Qui sépare les valeurs dans 2 colones différentes
Serial.print(pouls(tpsDer)); //On affiche la fonction pouls situé dans le fichier cardio.ino
Serial.println("F"); //On affiche la lttre de la fin
tpsDer = millis(); //On donne la valeur le nombre de millisecondes depuis le démarrage du programme
//pour le dernier temps du pouls calculé
}
}
}
| true |
d625e9c2e1feec0222e9267dfd800852688ff862 | C++ | jwnwilson/nw_game | /NSGame/NSGame/BasicInput.cpp | UTF-8 | 3,185 | 2.671875 | 3 | [] | no_license | #include "StdAfx.h"
#include "BasicInput.h"
#define BUFFER_SIZE 16
BasicInput::BasicInput(void)
{
key=&keys[0];
mouse=&mouse_state;
m_diObject=NULL;
m_diKeyboardDevice=NULL;
m_diMouse=NULL;
}
BasicInput::BasicInput(HINSTANCE hInstance,HWND hWnd)
{
initalise(hInstance,hWnd);
key=&keys[0];
}
BasicInput::~BasicInput(void)
{
if(m_diKeyboardDevice)
{
m_diKeyboardDevice->Unacquire();
m_diKeyboardDevice->Release();
m_diKeyboardDevice=NULL;
}
if(m_diMouse)
{
m_diMouse->Unacquire();
m_diMouse->Release();
m_diMouse = NULL;
}
if(m_diObject)
{
m_diObject->Release();
}
}
bool BasicInput::initalise(HINSTANCE hInstance, HWND hWnd)
{
winHandle = hWnd;
HRESULT hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION,
IID_IDirectInput8, (void**)&m_diObject, NULL);
if(FAILED(hr = m_diObject->CreateDevice(GUID_SysKeyboard, &m_diKeyboardDevice, NULL)))
return false;
if(FAILED(hr=m_diKeyboardDevice->SetDataFormat( &c_dfDIKeyboard )))
return false;
if(FAILED(hr = m_diKeyboardDevice->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
return false;
if(FAILED(hr = m_diObject->CreateDevice(GUID_SysMouse, &m_diMouse, NULL)))
return false;
if(FAILED(hr = m_diMouse->SetDataFormat(&c_dfDIMouse)))
return false;
if(FAILED(hr = m_diMouse->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
return false;
if (FAILED(m_diMouse->SetDataFormat(&c_dfDIMouse)))
return false;
m_diMouse->Acquire();
return true;
}
bool BasicInput::updateInput()
{
// If input is lost then acquire and keep trying until we get it back
bool error=true;
HRESULT hr=m_diKeyboardDevice->Acquire();
while( hr == DIERR_INPUTLOST )
{
hr = m_diKeyboardDevice->Acquire();
}
// Now read the state again
if(!m_diKeyboardDevice->GetDeviceState( sizeof(keys), keys ))
{
error=false;
}
if (FAILED(m_diMouse->Acquire()))
if(error==false)
return false;
if(FAILED(hr=(m_diMouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mouse_state))))
if(error==false)
return false;
return true;
}
bool BasicInput::keyPressed(int keyIndice)
{
if (key[keyIndice] & 0x80)
{
return true;
}
else
{
return false;
}
}
/*
bool BasicInput::escKey()
{
if (key[DIK_ESCAPE] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Dkey()
{
if (key[DIK_D] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Wkey()
{
if (key[DIK_W] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Akey()
{
if (key[DIK_A] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Skey()
{
if (key[DIK_S] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Spacekey()
{
if (key[DIK_SPACE] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::Shiftkey()
{
if (key[DIK_LSHIFT] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::mouseR()
{
if (mouse_state.rgbButtons[1] & 0x80)
{
return true;
}
else
{
return false;
}
}
bool BasicInput::mouseL()
{
if (mouse_state.rgbButtons[0] & 0x80)
{
return true;
}
else
{
return false;
}
}*/ | true |
16ca786c3b674e6559a14cff900cbd9750c8fe29 | C++ | sue-chun/OOP345 | /Workshops/OOP345lab4/Notifications.cpp | UTF-8 | 1,780 | 2.890625 | 3 | [] | no_license | // Name: Sue Ming Chun
// Seneca Student ID: 032343154
// Seneca email: smchun@myseneca.ca
// Date of completion:
//
// I confirm that the contents of this file is created by me,
// with the exception of the parts provided to me by my professor.
#include <iostream>
//#include <fstream>
#include "Notifications.h"
#include "Message.h"
using namespace std;
namespace w4 {
Notifications::Notifications() {
count = 0;
this->msg = new Message[max];
}
Notifications::Notifications(const Notifications& src) { // copy constructor
*this = src;
}
Notifications& Notifications::operator = (const Notifications& src) { // copy assignment
if (this != &src) {
delete[]this->msg;
this->count = src.count;
this->msg = new Message[max];
for (int i = 0; i < count; ++i)
this->msg[i] = src.msg[i];
}
return *this;
}
Notifications::Notifications(Notifications&& src) { // move constructor
*this = move(src);
}
Notifications& Notifications::operator=(Notifications&& src) { // move assignment
if (this != &src) {
this->count = src.count;
src.count = 0;
delete [] this->msg;
this->msg = src.msg;
src.msg = nullptr;
}
return *this;
}
Notifications::~Notifications() {
delete[]this->msg;
}
void Notifications::operator+=(const Message& src) {
// cout << "called +=" << endl;
if (count < max) {
msg[count] = src;
count++;
}
}
void Notifications::display(ostream& os) const {
for (int i = 0; i < count; ++i)
msg[i].display(os);
}
}
| true |
225bd23cd1a16b659d52e930c9a840e5a873d849 | C++ | tonycao/CodeSnippets | /C-CPP/Algorithm/RandomNumber.h | UTF-8 | 540 | 2.953125 | 3 | [] | no_license | // RandomNumber.h
const unsigned long maxshort = 65535L;
const unsigned long multiplier = 1194211693L;
const unsigned long adder = 12345L;
#ifndef RANDOMNUMBER_H
#define RANDOMNUMBER_H
class RandomNumber{
private:
// 当前种子
unsigned long randSeed;
public:
// 构造函数,默认值0表示由系统自动产生种子
RandomNumber(unsigned long s = 0);
// 产生0 ~ n-1之间的随机整数
unsigned short Random(unsigned long n);
// 产生[0, 1) 之间的随机实数
double fRandom();
};
#endif | true |
0a3035ed5f91f50a9dc4267b61ec30e0617fe5b8 | C++ | pvgupta24/Advanced-Data-Structures | /Heaps/includes/BinaryHeap.h | UTF-8 | 2,157 | 3.546875 | 4 | [
"MIT"
] | permissive | #ifndef _BINARY_HEAP
#define _BINARY_HEAP
#include "Heap.h"
template <class T>
class BinaryHeap : public virtual Heap<T>
{
public:
T *data;
BinaryHeap()
{
data = new T[MAX_NODE_COUNT];
}
~BinaryHeap()
{
delete data;
}
void min_heapify(int i)
{
int l = 2 * i + 1;
int r = 2 * i + 2;
int smallest;
if (l <= this->node_count && data[l] < data[i])
{
smallest = l;
}
else
{
smallest = i;
}
if (r <= this->node_count && data[r] < data[smallest])
{
smallest = r;
}
if (smallest != i)
{
T temp = data[i];
data[i] = data[smallest];
data[smallest] = temp;
min_heapify(smallest);
}
}
T get_min()
{
if (this->node_count == 0)
return T();
return data[0];
}
T extract_min()
{
if (this->node_count == 0)
return T();
T min = data[0];
data[0] = data[this->node_count - 1];
this->node_count--;
min_heapify(0);
return min;
}
void insert(T element)
{
this->node_count++;
data[this->node_count - 1] = element;
int i = this->node_count - 1;
while (i != 0 && data[(i - 1) / 2] > data[i])
{
T temp = data[i];
data[i] = data[(i - 1) / 2];
data[(i - 1) / 2] = temp;
i = (i - 1) / 2;
}
}
void swap(T *x, T *y)
{
T temp = *x;
*x = *y;
*y = temp;
}
void decrease_key(T elem, T new_val)
{
int i = -1;
for (int k = 0; k < this->node_count; k++)
{
if (data[k] == elem)
{
i = k;
break;
}
}
if (i == -1 || data[i] <= new_val)
return;
data[i] = new_val;
while (i != 0 && data[(i - 1) / 2] > data[i])
{
swap(&data[i], &data[(i - 1) / 2]);
i = (i - 1) / 2;
}
}
};
#endif | true |
86839179a9fa6c6a7a58b118ef60b28c41fb404d | C++ | amsraman/Competitive_Programming | /Facebook Hacker Cup/2021/Qualification Round/A1.cpp | UTF-8 | 868 | 2.78125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int t, n;
string s;
bool vowel(char c) {
return (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
}
int main() {
freopen("consistency_chapter_1_input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> t;
for(int _ = 1; _ <= t; _++) {
cin >> s;
n = s.length();
int ans = 0x3f3f3f3f;
for(int i = 0; i < 26; i++) {
int cnt = 0;
for(int j = 0; j < n; j++) {
if(s[j] == char('A' + i)) {
continue;
}
if(vowel(s[j]) ^ vowel(char('A' + i))) {
++cnt;
} else {
cnt += 2;
}
}
ans = min(ans, cnt);
}
cout << "Case #" << _ << ": " << ans << endl;
}
} | true |
c642dfbae7509d1ac0de5cdc7982f972432838cf | C++ | dmkz/competitive-programming | /codeforces.com/Codeforces Ladder 1500-1599 (extra)/0486A.cpp | UTF-8 | 383 | 2.78125 | 3 | [] | no_license | /*
Problem: 486A. Calculating Function
Solution: implementation, math, O(1)
Author: Dmitry Kozyrev, github: dmkz, e-mail: dmkozyrev@rambler.ru
*/
#include <iostream>
#include <string>
#include <algorithm>
typedef long long ll;
int main() {
ll n; std::cin >> n;
if (n % 2 == 0) {
std::cout << n / 2;
} else {
std::cout << n / 2 - n;
}
return 0;
} | true |
9d03c02b65a6b1187dc273c2635f560bed5606f2 | C++ | Evildea/DinosaurGame | /TheGame/T2.h | UTF-8 | 936 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Renderer2D.h"
#include "Global.h"
#include <math.h>
#include "V2.h"
#include "M3.h"
// The function of the T2 (Target Vector2) is to provide a target in 2D space to look towards or travel towards.
// This is primarily used to ensure that head of the dinosaur rotates smoothly between targets.
class T2
{
private:
V2<float> m_transform;
V2<float> m_velocity;
V2<float> m_avoid;
public:
T2();
~T2();
// These are custom update and draw functions. The draw function is only used for debugging.
void update(M3<float> a_transform, V2<float> a_target, float a_speed, float a_minDistance, float deltaTime);
void draw(aie::Renderer2D * a_renderer, float r, float g, float b);
// This returns the current position.
V2<float> getPosition();
// This sets the position.
void setPosition(V2<float> a_position);
// This ensures the target avoids a specific point.
void updateAvoid(V2<float> a_avoid);
};
| true |
bbcbe87db46871dab6a02dab03b6ef997e777de8 | C++ | geniusthomas3/practice | /unitsoft/triangle/main.cpp | UTF-8 | 1,639 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
int n;
int arr[100][2];
int max=0;
int main(){
freopen("triangles.in","r",stdin);
freopen("triangles.out","w",stdout);
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d %d",&arr[i][0],&arr[i][1]);
}
int tmp;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
if(arr[i][0]==arr[j][0]){
if(arr[k][1]==arr[j][1]){
tmp=(arr[j][1]-arr[i][1])*(arr[k][0]-arr[j][0]);
}
if(arr[i][1]==arr[k][1]){
tmp=(arr[j][1]-arr[i][1])*(arr[k][0]-arr[i][0]);
}
else continue;
}
if(arr[i][0]==arr[k][0]){
if(arr[k][1]==arr[j][1]){
tmp=(arr[i][1]-arr[k][1])*(arr[k][0]-arr[j][0]);
}
if(arr[i][1]==arr[j][1]){
tmp=(arr[i][1]-arr[k][1])*(arr[i][0]-arr[j][0]);
}
else continue;
}
if(arr[j][0]==arr[k][0]){
if(arr[i][1]==arr[j][1]){
tmp=(arr[j][1]-arr[k][1])*(arr[i][0]-arr[j][0]);
}
if(arr[i][1]==arr[k][1]){
tmp=(arr[k][1]-arr[j][1])*(arr[i][0]-arr[k][0]);
}
else continue;
}
else continue;
if(tmp<0) tmp*=(-1);
if(tmp>max) max=tmp;
}
}
}
printf("%d",max);
}
| true |
034ea6a8ab03c6f13326ca34ee87d7dbbd962c9f | C++ | ninegrafh/perulangan | /materi_4_latihan_1_arif_sidik_permana.cpp | UTF-8 | 508 | 3.453125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i=1,j=1;
for (int i=1;i<5;i++)
{
cout << "menjalankan perulangan dengan for, nilai i = " <<i<< endl;
}
while(i<5)
{
cout << "Perulangan dengan While, nilai i = " <<i<< endl;
i=i+1;
}
do{
cout << "Perulangan dengan Do-While, nilai i = " <<j<< endl;
j=j+1;
}while(j<5);
cout <<endl;
system("pause");
return 0;
}
| true |
40c55c396f409bf1f2663acb4deffadcab6cffa8 | C++ | GreenApple-jsy/Algorithm | /조교의 성적 매기기.cpp | UTF-8 | 1,242 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int T, N, K;
cin >> T;
for (int i = 1; i <= T; ++i) {
vector <pair <int, int> > score; // <총점, 학생 번호>
cin >> N >> K;
for (int j = 1; j <= N; ++j) {
int mid, fin, work;
cin >> mid >> fin >> work;
score.push_back({ ((mid * 35) + (fin * 45) + (work * 20)), j });
}
sort(score.begin(), score.end());
for (int j = 1; j <= N; ++j) {
if (score[j].second == K) {
int rate = (double)j / N * 100;
if (rate < 10)
cout << "#" << i << " " << "D0" << endl;
else if (rate < 20)
cout << "#" << i << " " << "C-" << endl;
else if (rate < 30)
cout << "#" << i << " " << "C0" << endl;
else if (rate < 40)
cout << "#" << i << " " << "C+" << endl;
else if (rate < 50)
cout << "#" << i << " " << "B-" << endl;
else if (rate < 60)
cout << "#" << i << " " << "B0" << endl;
else if (rate < 70)
cout << "#" << i << " " << "B+" << endl;
else if (rate < 80)
cout << "#" << i << " " << "A-" << endl;
else if (rate < 90)
cout << "#" << i << " " << "A0" << endl;
else
cout << "#" << i << " " << "A+" << endl;
break;
}
}
}
return 0;
}
| true |
15e1aad9364b7ee2c66e7295674f2c66aa9493f9 | C++ | alyssais/RadixEngine | /source/env/LegacyEnvironment.cpp | UTF-8 | 1,463 | 2.921875 | 3 | [
"Zlib"
] | permissive | #include <radix/env/LegacyEnvironment.hpp>
#include <iostream>
#include <radix/core/file/Path.hpp>
#include <radix/env/Util.hpp>
#include <radix/env/OperatingSystem.hpp>
namespace radix {
Config LegacyEnvironment::config;
std::string LegacyEnvironment::dataDir = "";
void LegacyEnvironment::Init() {
if (dataDir.empty()) {
std::vector<std::string> dataDirPaths = {
"data"
};
dataDirPaths.push_back("../data");
if(OperatingSystem::IsLinux()){
dataDirPaths.push_back("/usr/local/share/glportal/data");
dataDirPaths.push_back("/usr/share/glportal/data");
}
for (auto & path : dataDirPaths) {
Util::Log(Info, "DataDir") << "Searching data in " << path;
if (Path::DirectoryExist(path)) {
dataDir = path;
Util::Log(Info, "DataDir") << "Found data in " << path;
break;
}
}
}
InitializeConfig();
}
Config& LegacyEnvironment::getConfig() {
return config;
}
void LegacyEnvironment::InitializeConfig() {
config.load();
}
std::string LegacyEnvironment::getDataDir() {
if (dataDir == "") {
Util::Log(Info, "DataDir") << "No data dir set!";
exit(0);
}
return dataDir;
}
void LegacyEnvironment::setDataDir(const std::string &string) {
Util::Log(Info, "DataDir") << "Setting data dir to " << string;
dataDir = string;
if (dataDir[dataDir.size() - 1] == '/') {
dataDir = dataDir.substr(0, dataDir.length() - 1);
}
}
} /* namespace radix */
| true |
cac11105b38d4c7500ef7875887977da89483db8 | C++ | rider0004/Exam2_rider0004 | /pracex2_3.cpp | UTF-8 | 524 | 3.171875 | 3 | [] | no_license | #include<iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
char alphabet[8][8];
void showAlphabet();
void randomAlphabet();
int main(){
srand(time(0));
randomAlphabet();
showAlphabet();
}
void showAlphabet(){
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
cout << alphabet[i][j] << " ";
}
cout << "\n";
}
}
//Write definition of function randomAlphabet() here.
void randomAlphabet()
{
for (int i = 0;i < 8;i++)
for (int j = 0;j < 8;j++)
alphabet[i][j] = rand()%26 + 97;
}
| true |
77379072312f1d183a19731be36ed5f12344842c | C++ | Meantint/Programmers | /Lv3/풍선 터트리기.cpp | UTF-8 | 1,388 | 3.140625 | 3 | [] | no_license | #include <cmath>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int solution(vector<int> a)
{
int answer = 2;
vector<int> left(a.size());
vector<int> right(a.size());
left[0] = a[0];
right.back() = a.back();
for (int i = 1; i < left.size(); ++i) {
if (a[i] < left[i - 1]) {
left[i] = a[i];
}
else {
left[i] = left[i - 1];
}
}
for (int i = right.size() - 2; i >= 0; --i) {
if (a[i] < right[i + 1]) {
right[i] = a[i];
}
else {
right[i] = right[i + 1];
}
}
// cout << '\n';
// for (int i = 0; i < left.size(); ++i) {
// cout << setw(4) << a[i] << ' ';
// }
// cout << '\n';
// for (int i = 0; i < left.size(); ++i) {
// cout << setw(4) << left[i] << ' ';
// }
// cout << '\n';
// for (int i = 0; i < right.size(); ++i) {
// cout << setw(4) << right[i] << ' ';
// }
// cout << '\n';
// cout << '\n';
for (int i = 1; i < a.size() - 1; ++i) {
if (a[i] < left[i - 1] || a[i] < right[i + 1]) ++answer;
}
return answer;
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < arr.size(); ++i) {
cin >> arr[i];
}
cout << solution(arr) << endl;
return 0;
} | true |
a6fd7199695efc1a9794eb48e756a3e7ad45fa6c | C++ | the-night-wing/SP-2 | /rgr/PTOC/ARRAY.H | UTF-8 | 13,926 | 2.875 | 3 | [] | no_license | #ifndef __ARRAY_H__
#define __ARRAY_H__
#ifdef __cplusplus
#define BETWEEN(down, value, up) \
(unsigned(value) - down <= unsigned(up - down))
template<class Type>
class var_conf_array;
template<class Type>
class var_conf_matrix;
template<class Type>
class conf_array {
protected:
integer low_bound, high_bound;
Type *buf;
public:
conf_array(integer l, integer h)
: low_bound(l), high_bound(h)
{
buf = new Type[h-l+1];
}
conf_array(integer l, integer h, const Type* ptr)
: low_bound(l), high_bound(h)
{
buf = new Type[h-l+1];
memcpy(buf, ptr, sizeof(Type)*(h-l+1));
}
conf_array(conf_array const& a)
: low_bound(a.low()), high_bound(a.high())
{
buf = new Type[size()];
memcpy(buf, a.buf, sizeof(Type)*size());
}
conf_array(var_conf_array<Type> const& a);
conf_array(const Type* ptr); // intialization with string
~conf_array() { delete[] buf; }
Type& operator[](integer index) {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
const Type& operator[](integer index) const {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
const integer low() const { return low_bound; }
const integer high() const { return high_bound; }
const integer size() const { return high_bound - low_bound + 1; }
operator Type*() { return buf; }
operator Type const*() const { return buf; }
void operator=(conf_array const& src) {
assert(low_bound == src.low_bound && high_bound == src.high_bound);
memcpy(buf, src.buf, sizeof(Type)*size());
}
void operator=(var_conf_array<Type> const& src);
friend char* lpsz(conf_array const& a) {
return lpsz(a.low_bound, a.high_bound, (char*)a.buf);
}
};
template<class Type>
class var_conf_array {
protected:
integer low_bound, high_bound;
Type *buf;
public:
var_conf_array(integer l, integer h) : low_bound(l), high_bound(h)
{
buf = new Type[h-l+1];
}
var_conf_array(integer l, integer h, Type* ptr)
: low_bound(l), high_bound(h), buf(ptr) {}
var_conf_array(conf_array<Type>& a)
: low_bound(a.low()), high_bound(a.high()), buf((Type*)a) {}
var_conf_array(const Type* ptr); // intialization with string
Type& operator[](integer index) {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
const Type& operator[](integer index) const {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
const integer low() const { return low_bound; }
const integer high() const { return high_bound; }
const integer size() const { return high_bound - low_bound + 1; }
operator Type*() { return buf; }
operator Type const*() const { return buf; }
void operator=(conf_array<Type> const& src) {
assert(low() == src.low() && high() == src.high());
memcpy(buf, (Type const*)src, sizeof(Type)*size());
}
void operator=(var_conf_array const& src) {
assert(low() == src.low() && high() == src.high());
memcpy(buf, (Type const*)src, sizeof(Type)*size());
}
friend char* lpsz(var_conf_array const& a) {
return lpsz(a.low_bound, a.high_bound, (char*)a.buf);
}
};
inline conf_array<char>::conf_array(const char* str)
{
int len = strlen(str);
low_bound = 1;
high_bound = len;
buf = new char[len];
memcpy(buf, str, len);
}
template<class Type>
inline conf_array<Type>::conf_array(var_conf_array<Type> const& a)
: low_bound(a.low()), high_bound(a.high())
{
buf = new Type[size()];
memcpy(buf, (Type const*)a, sizeof(Type)*size());
}
template<class Type>
inline void conf_array<Type>::operator=(var_conf_array<Type> const& src) {
assert(low() == src.low() && high() == src.high());
memcpy(buf, (Type const*)src, sizeof(Type)*size());
}
inline var_conf_array<char>::var_conf_array(const char* str)
{
low_bound = 1;
high_bound = strlen(str);
buf = (char*)str;
}
template<integer low_bound, integer high_bound, class Type>
class array {
public:
Type buf[high_bound-low_bound+1];
const integer low() const { return low_bound; }
const integer high() const { return high_bound; }
const integer size() const { return high_bound - low_bound + 1; }
Type& operator[](integer index) {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
const Type& operator[](integer index) const {
assert(BETWEEN(low_bound, index, high_bound));
return buf[index-low_bound];
}
operator Type*() { return buf; }
operator Type const*() const { return buf; }
Type& operator*() { return *buf; }
operator conf_array<Type>() const { /* Convert to dynamic_array */
return conf_array<Type>(low_bound, high_bound, buf);
}
operator var_conf_array<Type>() { /* Convert to dynamic_array */
return var_conf_array<Type>(low_bound, high_bound, buf);
}
int compare( const Type* ptr) const {
return memcmp(buf, ptr, sizeof(buf));
}
boolean operator>(const array &arr) const {
return compare(arr.buf) > 0;
}
boolean operator >= (const array &arr) const {
return compare(arr.buf) >= 0;
}
boolean operator < (const array &arr) const {
return compare(arr.buf) < 0;
}
boolean operator <= (const array &arr) const {
return compare(arr.buf) <= 0;
}
boolean operator == (const array &arr) const {
return compare(arr.buf) == 0;
}
boolean operator != (const array &arr) const {
return compare(arr.buf) != 0;
}
boolean operator > (const Type* ptr) const {
return compare(ptr) > 0;
}
boolean operator >= (const Type* ptr) const {
return compare(ptr) >= 0;
}
boolean operator < (const Type* ptr) const {
return compare(ptr) < 0;
}
boolean operator <= (const Type* ptr) const {
return compare(ptr) <= 0;
}
boolean operator == (const Type* ptr) const {
return compare(ptr) == 0;
}
boolean operator != (const Type* ptr) const {
return compare(ptr) != 0;
}
boolean operator > (Type elem) const {
return compare(&elem) > 0;
}
boolean operator >= (Type elem) const {
return compare(&elem) >= 0;
}
boolean operator < (Type elem) const {
return compare(&elem) < 0;
}
boolean operator <= (Type elem) const {
return compare(&elem) <= 0;
}
boolean operator == (Type elem) const {
return compare(&elem) == 0;
}
boolean operator != (Type elem) const {
return compare(&elem) != 0;
}
friend text& operator << (text& t, array a)
{
pio_output_string((text_descriptor*)&t, (char*)a.buf,
high_bound-low_bound+1, NULL);
return t;
}
friend text& operator >> (text& t, array& a)
{
pio_input_string((text_descriptor*)&t, (char*)a.buf,
high_bound-low_bound+1);
return t;
}
friend format_string<high_bound-low_bound+1> format(array const& a,
integer width)
{
return format_string<high_bound-low_bound+1>((char*)a.buf, width);
}
#ifndef NO_ARRAY_ASSIGN_OPERATOR
void operator = (const Type* ptr) {
memcpy(buf, ptr, sizeof(buf));
}
void operator = (Type elem) {
buf[0] = elem;
}
#else
void assign(array const& a) {
memcpy(buf, a.buf, sizeof(buf));
}
void assign(const Type* ptr) {
memcpy(buf, ptr, sizeof(buf));
}
void assign(Type elem) {
buf[0] = elem;
}
#endif
// constructor of array from string
static array make(Type const* ptr) {
array a;
memcpy(a.buf, ptr, sizeof(a.buf));
return a;
}
static array make(Type elem1, ...) {
va_list ap;
int argno = 1;
array a;
va_start(ap, elem1);
a.buf[0] = elem1;
while(argno < high_bound-low_bound+1) {
a.buf[argno++] = va_arg(ap, Type);
}
va_end(ap);
return a;
}
friend char* lpsz(array const& a) {
return lpsz(low_bound, high_bound, (char*)a.buf);
}
};
// macro for construction array from string
#define as_array(s) array<1,sizeof(s)-1,char>::make(s)
template<class Type>
class conf_matrix {
protected:
integer low_1, high_1, low_2, high_2;
Type *buf;
public:
conf_matrix(integer l1, integer h1, integer l2, integer h2, Type const* p)
: low_1(l1), high_1(h1), low_2(l2), high_2(h2)
{
buf = new Type[size()];
memcpy(buf, p, sizeof(Type)*size());
}
conf_matrix(integer l1, integer h1, integer l2, integer h2)
: low_1(l1), high_1(h1), low_2(l2), high_2(h2)
{
buf = new Type[size()];
}
conf_matrix(conf_matrix const& m)
: low_1(m.low1()), high_1(m.high1()), low_2(m.low2()), high_2(m.high2())
{
buf = new Type[size()];
memcpy(buf, (Type const*)m, sizeof(Type)*size());
}
conf_matrix(var_conf_matrix<Type> const& m);
var_conf_array<Type> operator[](integer index) {
assert(BETWEEN(low_1, index, high_1));
return var_conf_array<Type>(low_2, high_2,
buf+(index-low_1)*(high_2-low_2+1));
}
const var_conf_array<Type> operator[](integer index) const {
assert(BETWEEN(low_1, index, high_1));
return var_conf_array<Type>(low_2, high_2,
(Type*)buf+(index-low_1)*(high_2-low_2+1));
}
void operator=(const conf_matrix& src) {
assert(low_1 == src.low_1 && high_1 == src.high_1 &&
low_2 == src.low_2 && high_2 == src.high_2);
memcpy(buf, (const Type*)src, size()*sizeof(Type));
}
void operator=(const var_conf_matrix<Type>& src);
const integer low1() const { return low_1; }
const integer low2() const { return low_2; }
const integer high1() const { return high_1; }
const integer high2() const { return high_2; }
const integer size() const { return (high_1 - low_1 + 1)
*(high_2 - low_2 + 1); }
operator Type*() { return buf; }
operator Type const*() const { return buf; }
};
template<class Type>
class var_conf_matrix {
protected:
integer low_1, high_1, low_2, high_2;
Type *buf;
public:
var_conf_matrix(integer l1, integer h1, integer l2, integer h2,
Type* ptr)
: low_1(l1), high_1(h1), low_2(l2), high_2(h2), buf(ptr) {}
var_conf_matrix(integer l1, integer h1, integer l2, integer h2)
: low_1(l1), high_1(h1), low_2(l2), high_2(h2)
{
buf = new Type[size()];
}
var_conf_matrix(conf_matrix<Type>& m)
: low_1(m.low1()), high_1(m.high1()), low_2(m.low2()), high_2(m.high2())
{
buf = (Type*)m;
}
var_conf_array<Type> operator[](integer index) {
assert(BETWEEN(low_1, index, high_1));
return var_conf_array<Type>(low_2, high_2,
buf+(index-low_1)*(high_2-low_2+1));
}
const var_conf_array<Type> operator[](integer index) const {
assert(BETWEEN(low_1, index, high_1));
return var_conf_array<Type>(low_2, high_2,
(Type*)buf+(index-low_1)*(high_2-low_2+1));
}
void operator=(var_conf_matrix const& src) {
assert(low1() == src.low1() && high1() == src.high1() &&
low2() == src.low2() && high2() == src.high2());
memcpy(buf, (Type const*)src, size()*sizeof(Type));
}
void operator=(conf_matrix<Type> const& src) {
assert(low1() == src.low1() && high1() == src.high1() &&
low2() == src.low2() && high2() == src.high2());
memcpy(buf, (Type const*)src, size()*sizeof(Type));
}
const integer low1() const { return low_1; }
const integer low2() const { return low_2; }
const integer high1() const { return high_1; }
const integer high2() const { return high_2; }
const integer size() const { return (high_1 - low_1 + 1)
*(high_2 - low_2 + 1); }
operator Type*() { return buf; }
operator Type const*() const { return buf; }
};
template<class Type>
conf_matrix<Type>::conf_matrix(var_conf_matrix<Type> const& m)
: low_1(m.low1()), high_1(m.high1()), low_2(m.low2()), high_2(m.high2())
{
buf = new Type[size()];
memcpy(buf, (Type const*)m, size()*sizeof(Type));
}
template<class Type>
void conf_matrix<Type>::operator=(const var_conf_matrix<Type>& src)
{
assert(low1() == src.low1() && high1() == src.high1() &&
low2() == src.low2() && high2() == src.high2());
memcpy(buf, (Type const*)src, size()*sizeof(Type));
}
/*
Class matrix describes buf with fixed bounds.
*/
template<integer low_1, integer high_1, integer low_2, integer high_2, class Type>
class matrix {
public:
array<low_2,high_2,Type> buf[high_1-low_1+1];
array<low_2,high_2,Type>& operator[](integer index) {
assert(BETWEEN(low_1, index, high_1));
return buf[index-low_1];
}
array<low_2,high_2,Type> const& operator[](integer index) const {
assert(BETWEEN(low_1, index, high_1));
return buf[index-low_1];
}
operator conf_matrix<Type>() const {
return conf_matrix<Type>(low_1, high_1, low_2, high_2, (Type*)buf);
}
operator var_conf_matrix<Type>() {
return var_conf_matrix<Type>(low_1, high_1, low_2, high_2,
(Type*)buf);
}
const integer low1() const { return low_1; }
const integer high1() const { return high_1; }
const integer low2() const { return low_2; }
const integer high2() const { return high_2; }
const integer size() const { return (high_1 - low_1 + 1)
*(high_2 - low_2 + 1); }
void assign(matrix const& m) {
memcpy(buf, m.buf, sizeof(buf));
}
};
#else /* language C */
/*
* macro for passing string as a function parameter together with bounds
*/
#define array(s) 1, sizeof(s)-1, (s)
#define arrcmp(a,b) memcmp(a, b, sizeof(a))
#define arrcpy(a,b) memcpy(a, b, sizeof(a))
#endif
#endif
| true |
52d7b183807887eb274a42c81204a2bf666f8a29 | C++ | Demorro/AMG_Teaching_Repo | /AMG Teaching/Camera.h | UTF-8 | 1,738 | 2.78125 | 3 | [] | no_license | #pragma once
#include "SFML\Graphics.hpp"
#include <iostream>
#include <sstream>
#include "Assets.h"
#include "pugixml.hpp"
#include "VectorMath.h"
#define DEBUG_CAMERA false
class Camera
{
public:
Camera(void);
Camera(sf::RenderWindow &window,sf::Vector2f startPositionOffset);
~Camera(void);
//You can pass in null and the camera wont follow anything, or you can pass in a position and it will
//CameraOffset Must be divisible by Stepsize otherwise bad things will happen
void Update(sf::Event event, bool eventFired,float deltaTime, sf::Vector2f *followTarget = NULL);
void Move(float xMove, float yMove);
void JumpToPoint(float xPos, float yPos);
void Zoom(float zoom);
sf::Vector2f GetPosition();
sf::Vector2f GetVelocity();
//If you subtract this vector from a position, you get the screenspace position, (ie 300,200 will be 300 pixels down and 200 pixels along on the screen,) regardless of where the camera is. For rendering UI mainly.
sf::Vector2f GetScreenSpaceOffsetVector();
bool GetLocked();
void SetLocked(bool value);
void Reset();
private:
sf::View cameraView;
bool LoadConfigValues(std::string configFilePath);
//Store a reference to the window so you can call setView after every view change
sf::RenderWindow* window;
float zoom;
float ReturnToCenter;
void MoveToPoint(sf::Vector2f Target , sf::Vector2f Start, float deltaTime);
void InitialiseCamera(sf::Vector2f startPositionOffset);
bool locked;
//Updates the window to the new view, need to call after making any changes to the camera
void UpdateView();
// Position of the Center of the Screen
sf::Vector2f Last_Center_Point;
sf::Vector2f Center_Point;
//read only, do not set
sf::Vector2f velocity;
bool simpleCam;
};
| true |
aa49732ec84b1c2fce29b087a3f9c4dda997f358 | C++ | casper-h/Interview | /LeetCode/Medium/1249.cpp | UTF-8 | 1,008 | 3.828125 | 4 | [] | no_license | /*
* 1249. Minimum Remove to Make Valid Parentheses
*/
#include <iostream>
#include <string>
#include <stack>
using std::string;
using std::stack;
class Solution {
public:
string minRemoveToMakeValid(string s) {
// This is similar to checking parentheses in general
stack<int> invalid;
for (int i = 0; i < s.size(); i++) {
// If we see a '('
if (s[i] == '(') {
invalid.push(i);
}
if (s[i] == ')') {
// If we see a ')' and the stack is not empty, as empty means out of place
if (!invalid.empty()) {
invalid.pop();
} else {
s[i] = '*';
}
}
}
// Remaining stack elements are all out of place
while (!invalid.empty()) {
s[invalid.top()] = '*';
invalid.pop();
}
s.erase(remove(s.begin(), s.end(), '*'), s.end());
return s;
}
}; | true |
0f37ef39d66d6a26578a15a28082f7fd43509e4d | C++ | Azrrael-exe/sda-poo | /lib/circular/include/circular.h | UTF-8 | 386 | 2.8125 | 3 | [
"MIT"
] | permissive | #ifndef CIRCULAR
#define CIRCULAR
class CircularBuffer {
protected:
int in_index;
int out_index;
int* list;
int size;
int free_slots;
public:
CircularBuffer(){};
CircularBuffer(int size);
bool add(int value);
int remove();
int inIndex();
int outIndex();
int freeSlots();
int getValueFromIndex(int index);
float mean();
};
#endif | true |
4043e60617a3e8ad38b68e3697b7ca07bda8425d | C++ | Hayden-Allen/COGA | /src/coga/util/indexed_list.h | UTF-8 | 2,197 | 3.03125 | 3 | [] | no_license | #pragma once
#include "pch.h"
#include "typed.h"
#include "functions.h"
namespace coga
{
template<typename T, typename RETURN = size_t, typename ADD = const T&, typename REMOVE = const RETURN&>
class indexed_list : public typed<T>
{
public:
typedef RETURN handle;
indexed_list(size_t count, const T& placeholder) :
m_count(count),
m_next(0),
m_list(new T[count]),
m_placeholder(placeholder)
{
arrset(count, m_list, placeholder);
m_openings.reserve(count);
}
COGA_DCM(indexed_list);
virtual ~indexed_list()
{
delete[] m_list;
}
public:
virtual RETURN add(ADD t) = 0;
virtual void remove(REMOVE t) = 0;
const T& operator[](size_t i) const
{
return m_list[i];
}
T& operator[](size_t i)
{
return m_list[i];
}
size_t get_capacity() const
{
return m_count;
}
size_t get_size() const
{
return m_next - m_openings.size();
}
size_t get_next() const
{
return m_next;
}
bool is_empty() const
{
return m_openings.size() == m_next;
}
bool is_full() const
{
return m_next == m_count && m_openings.empty();
}
template<typename T>
void for_each(T fn) const
{
for (size_t i = 0; i < get_next(); i++)
if (is_valid(i))
fn(m_list[i]);
}
template<typename T>
void for_each(T fn)
{
for (size_t i = 0; i < get_next(); i++)
if (is_valid(i))
fn(m_list[i]);
}
protected:
size_t m_count, m_next;
std::vector<size_t> m_openings;
T* m_list, m_placeholder;
protected:
size_t add_base(ADD t)
{
COGA_CORE_ASSERT(!is_full(), "indexed_list is full");
const size_t i = next_index();
m_list[i] = t;
m_next += (i == m_next);
return i;
}
void remove_base(size_t i)
{
COGA_CORE_ASSERT(i < m_count, "Invalid indexed_list index {}", i);
// only remove if something's actually there
if (m_list[i] != m_placeholder)
{
m_list[i] = m_placeholder;
m_openings.push_back(i);
}
}
size_t next_index()
{
size_t i = m_next;
if (!m_openings.empty())
{
i = m_openings.back();
m_openings.pop_back();
}
return i;
}
bool is_valid(size_t i) const
{
return i < m_count && m_list[i] != m_placeholder;
}
};
}
| true |
06e000d430f43dd68703b437dcb1ad551fe7959e | C++ | DoubleQ0726/TinyServer | /src/config.cpp | UTF-8 | 3,168 | 2.796875 | 3 | [] | no_license | #include "config.h"
#include "env.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace TinyServer
{
static Ref<Logger> logger = TINY_LOG_NAME("system");
Ref<ConfigVarBase> Config::LookupBase(const std::string& name)
{
RWMutexType::ReadLockGuard lock(GetMutex());
auto iter = GetDatats().find(name);
return iter == GetDatats().end() ? nullptr : iter->second;
}
static void ListAllMember(const std::string& prefix,
YAML::Node& node,
std::list<std::pair<std::string, const YAML::Node>>& output)
{
if (prefix.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._0123456789") != std::string::npos)
{
TINY_LOG_ERROR(logger) << "Config invalid name: " << prefix << " : " << node;
return;
}
output.push_back(std::make_pair(prefix, node));
if (node.IsMap())
{
for (auto iter = node.begin(); iter != node.end(); ++iter)
{
ListAllMember(prefix.empty() ? iter->first.Scalar() :
prefix + "." + iter->first.Scalar(), iter->second, output);
}
}
}
void Config::LoadFromYaml(YAML::Node& root)
{
std::list<std::pair<std::string, const YAML::Node>> all_nodes;
ListAllMember("", root, all_nodes);
for (auto& item : all_nodes)
{
std::string key = item.first;
if (key.empty())
continue;
std::transform(key.begin(), key.end(), key.begin(), ::tolower);
Ref<ConfigVarBase> config = LookupBase(key);
if (config)
{
if (item.second.IsScalar())
{
config->fromString(item.second.Scalar());
}
else
{
std::stringstream ss;
ss << item.second;
config->fromString(ss.str());
}
}
}
}
static std::map<std::string, uint64_t> s_file2modifytime;
static MutexLock s_mutex;
void Config::LoadFromConfDir(const std::string& path)
{
std::string absolute_path = EnvMgr::GetInstance()->getAbsolutionPath(path);
std::vector<std::string> files;
FSUtil::ListAllFile(files, absolute_path, ".yml");
for (auto& item : files)
{
{
struct stat st;
lstat(item.c_str(), &st);
MutexLock::MutexLockGuard lock(s_mutex);
if (s_file2modifytime[item] == (uint64_t)st.st_mtime)
continue;
s_file2modifytime[item] = (uint64_t)st.st_mtime;
}
try
{
YAML::Node root = YAML::LoadFile(item);
LoadFromYaml(root);
TINY_LOG_INFO(logger) << "LoadConfFile file = " << item << " ok";
}
catch(const std::exception& e)
{
TINY_LOG_ERROR(logger) << "LoadConfFile file = " << item << " failed";
}
}
}
void Config::Visit(std::function<void(Ref<ConfigVarBase>)> cb)
{
RWMutexType::ReadLockGuard lock(GetMutex());
ConfigVarMaps& m = GetDatats();
for (auto iter = m.begin(); iter != m.end(); ++iter)
{
cb(iter->second);
}
}
} // namespace TinyServer
| true |
a2142683b9d10acd7a052c62e0c7f9a2ce88bd3b | C++ | gjbex/Scientific-C-plus-plus | /source-code/DesignPatterns/StrategyPattern/automaton_runner.cpp | UTF-8 | 1,269 | 3.109375 | 3 | [
"CC-BY-4.0"
] | permissive | #include "automaton_runner.h"
AutomatonRunner::AutomatonRunner(uint8_t rule_nr) {
for (uint8_t i = 0; i < rules.size(); ++i) {
rules[i] = rule_nr % 2;
rule_nr /= 2;
}
}
Automaton AutomatonRunner::next_generation(const Automaton& automaton) {
uint8_t idx;
size_t nr_cells {automaton.size()};
Automaton ng_automaton(nr_cells);
// first cell
idx = automaton[nr_cells - 1] << 2 | automaton[0] << 1 | automaton[1];
ng_automaton[0] = rules[idx];
// second to one before last cell
for (size_t cell_nr = 1; cell_nr < nr_cells - 1; ++cell_nr) {
idx = automaton[cell_nr - 1] << 2 | automaton[cell_nr] << 1 | automaton[cell_nr + 1];
ng_automaton[cell_nr] = rules[idx];
}
// last cell
idx = automaton[nr_cells - 2] << 2 | automaton[nr_cells - 1] << 1 | automaton[0];
ng_automaton[nr_cells - 1] = rules[idx];
return ng_automaton;
}
void AutomatonRunner::evolve(Automaton& automaton, const size_t nr_generations,
GenerationHandler* handler) {
if (!handler->handle(automaton)) return;
for (size_t gen_nr = 0; gen_nr < nr_generations; ++gen_nr) {
automaton = next_generation(automaton);
if (!handler->handle(automaton)) return;
}
}
| true |
22ad5672e98e12ab17b5101fcb1473d53deb2c65 | C++ | harshu175/DS-algos-using-cpp | /Array1/FirstLast.cpp | UTF-8 | 953 | 3.3125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int FirstInd(int arr[],int n,int d){
int f = -1;
int low = 0;
int high = n-1;
while(low<=high){
int mid = (low+high)/2;
if(d>arr[mid]){
low = mid+1;
}
else if(d<arr[mid]){
high = mid-1;
}
else{
f = mid;
high = mid-1;
}
}
return f;
}
int LastInd(int arr[],int n,int d){
int l = -1;
int low = 0;
int high = n-1;
while(low<=high){
int mid = (low+high)/2;
if(d>arr[mid]){
low = mid+1;
}
else if(d<arr[mid]){
high = mid-1;
}
else{
l = mid;
low = mid+1;
}
}
return l;
}
int main(){
int n,d;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
cin>>d;
cout<<FirstInd(arr,n,d)<<endl;
cout<<LastInd(arr,n,d);
return 0;
}
| true |
1da330446ec74a6882e3ff3074bc385ac70cf386 | C++ | Jabalov/Algorithms-And-DS-Implementations | /UCSD/C1/week2_algorithmic_warmup/2_last_digit_of_fibonacci_number/fibonacci_last_digit.cpp | UTF-8 | 789 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
long long get_fibonacci_last_digit_naive(long long n)
{
if (n <= 1)
return n;
long long previous = 0;
long long current = 1;
for (long long i = 0; i < n - 1; ++i)
{
long long tmp_previous = previous;
previous = current;
current = tmp_previous + current;
}
return current % 10;
}
long long get_fibonacci_last_digit_fast(long long n)
{
if (n <= 1)
return n;
vector<int> list(n + 1);
list[0] = 0, list[1] = 1;
for (long long i = 2; i <= n; i++)
list[i] = (list[i - 1] + list[i - 2]) % 10;
return list[n];
}
int main()
{
long long n;
cin >> n;
long long c = get_fibonacci_last_digit_fast(n);
cout << c << '\n';
}
| true |
06ca35f2ff99db17e829b9dbc1b167635ea3da87 | C++ | cmariemarty/Galaga | /EnemyShip.h | UTF-8 | 4,867 | 2.90625 | 3 | [] | no_license | /*
* Author: PlayersX (Claire Williams, Lizette Martinez,
Christina Martinez, Taylor Robinett)
* Assignment Title: Galaga_Project
* Assignment Description: This program is a recreation of the
* vintage shooter, Galaga.
* Due Date: 4/25/2018
* Date Created: 4/7/2018
* Date Last Modified: 4/21/2018
*/
#ifndef ENEMYSHIP_H_INCLUDED
#define ENEMYSHIP_H_INCLUDED
#include <SDL.h>
class EnemyShip
{
private:
int x, y;
int ShipH = 25;
int ShipW = 25;
public:
bool isSplosion = false;
bool isDestroyed = false;
int moveFrame = 0;
//********************************************************************
// description: This function constructs an enemy ship *
// return: none *
// precondition: the enemy ship class must exist *
// postcondition: creates an enemy ship *
// *
//********************************************************************
EnemyShip();
//********************************************************************
// description: This function constructs an enemy ship in a line up *
// return: none *
// precondition: the enemy ship class must exist *
// postcondition: creates an enemy ship with proper formation *
// placement *
// *
//********************************************************************
EnemyShip(int numOfEnemies);
//********************************************************************
// description: This function de-constructs an enemy ship *
// return: none *
// precondition: the enemy ship must exist *
// postcondition: destroys enemy ship *
// *
//********************************************************************
~EnemyShip();
//********************************************************************
// description: This function gets an enemy ship's x coordinate *
// return: int *
// precondition: the enemy ship must exist *
// postcondition: returns the x coordinate *
// *
//********************************************************************
int getX();
//********************************************************************
// description: This function gets an enemy ship's y coordinate *
// return: int *
// precondition: the enemy ship must exist *
// postcondition: returns the y coordinate *
// *
//********************************************************************
int getY();
//********************************************************************
// description: This function moves an enemy ship's x coordinate *
// return: void *
// precondition: the enemy ship must exist *
// postcondition: moves the ship to the left and the right *
// *
//********************************************************************
void enemyMove();
//********************************************************************
// description: This function renders an enemy ship to the window *
// return: void *
// precondition: the enemy ship must exist *
// postcondition: renders the ship to the game window *
// *
//********************************************************************
void renderShip(SDL_Renderer* field, SDL_Texture* space);
};
#endif // ENEMYSHIP_H_INCLUDED
| true |
b96c04012a9be676e7546f31ee52e66980cd75ca | C++ | MadRoboticist/Arduino | /SerialBridge/SerialBridge.ino | UTF-8 | 221 | 2.65625 | 3 | [] | no_license |
#define BAUD 230400
#define PORT Serial1
void setup() {
Serial.begin(BAUD);
PORT.begin(BAUD);
}
void loop() {
if(Serial.available()) PORT.write(Serial.read());
if(PORT.available()) Serial.write(PORT.read());
}
| true |
d8c23f0a38bff61b672e43e515dd0f5cf1971084 | C++ | zouwx2cs/JianZhiOffer | /Solutions/054.字符流中第一个不重复的字符/Solution2.cpp | UTF-8 | 678 | 2.984375 | 3 | [] | no_license | class Solution
{
private:
int cnts[128] = {0, } ;
int posFrist[128] = {0, } ;
int pos = 1 ;
public:
//Insert one char from stringstream
void Insert(char ch)
{
if (cnts[ch]++ == 0)
posFrist[ch] = pos ;
++pos ;
}
//return the first appearence once char in current stringstream
char FirstAppearingOnce()
{
int minPos = pos ;
char frist = '#' ;
for (int i = 0; i < 128; ++i)
{
if (1 == cnts[i] && posFrist[i] < minPos)
{
frist = i ;
minPos = posFrist[i] ;
}
}
return frist ;
}
}; | true |
44b9dfd0957ea73bf481fd4094bfbc54104b349b | C++ | wintel2014/LinuxProgram | /Compile_Link/wrap_symbol/malloc.cpp | UTF-8 | 1,022 | 2.65625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
/*
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to symbol will be resolved to "__wrap_symbol". Any undefined reference to "__real_symbol" will be resolved to symbol.
This can be used to provide a wrapper for a system function. The wrapper function should be called "__wrap_symbol". If it wishes to call the system function, it should call "__real_symbol".
Here is a trivial example:
void *
__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
*/
#include <execinfo.h>
#define BT_BUF_SIZE 32
void bt (void)
{
int j, nptrs;
void *buffer[BT_BUF_SIZE];
char **strings;
nptrs = backtrace(buffer, BT_BUF_SIZE);
backtrace_symbols_fd(buffer, nptrs, 1);
}
extern "C" {
void* __real_malloc(size_t);
void *__wrap_malloc (size_t c)
{
printf ("malloc called with %zu\n", c);
return __real_malloc (c);
}
}
| true |
ac539d66b5fd2a275bad5452d2e10072daafd181 | C++ | JiaqiJin/Cplusplus_Project | /Project/Project/Multithread/lock_guard.cpp | UTF-8 | 3,275 | 3.484375 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <list>
#include <thread>
#include <mutex>
using namespace std;
/*
Mutex
lock unlock
lock_guard template = lock_guard 构造函数里执行了mutex::lock(); 析造函数里执行了 mutex::unlock lock_guard 不灵活
死锁deadlock = 是俩个锁头也就是俩个互斥量(mutex)才能产生,俩个线程在争夺资源。
保证 2 mutex 上锁顺序一致就不会死锁。
mutex1 lock , mutex2 lock
mutex1 unlock , mutex2 unlock
std::lock_guard<mutex> sbguard(my_mutex,std::adopt_lock); //自动unlock,
不需要在std::lock_guard<mutex>对象再次lock
*/
void myprinter(int num)
{
//cout << "my printer thread init, thread number = " << num << endl;
//// codes
//cout << "my printer thread finish, thread number = " << num << endl;
cout << "id is" << std::this_thread::get_id() << "thread vector number is " << endl;
return;
}
class A
{
public:
A() = default;
~A() = default;
//收到的消息入到一个列队的线程。
void inMsgReceive()
{
for (int i = 0; i < 10000; i++)
{
cout << "inMsgReceive, inserting element" << i << endl;
{
std::lock(my_mutex, my_mutex2);
std::lock_guard<mutex> sbguard(my_mutex,std::adopt_lock); //自动unlock
std::lock_guard<mutex> sbguard2(my_mutex2, std::adopt_lock);
//my_mutex.lock();
myList.push_back(i);
//my_mutex.unlock();
//my_mutex2.unlock();
}
//my_mutex.unlock();
//.... 执行其他代码
}
return;
}
bool outMsgLULProc(int& command)
{
std::lock_guard<mutex> sbguard(my_mutex);
std::lock_guard<mutex> sbguard2(my_mutex2);
//my_mutex.lock();
if (!myList.empty())
{
command = myList.front();
myList.pop_front();
//myvector.push_back(command);
//my_mutex.unlock();
return true;
}
//my_mutex.unlock();
return false;
}
//把数据从列队中取出的线程
void outMsgReceive()
{
int command = 0;
for (int i = 0; i < 10000; i++)
{
bool result = outMsgLULProc(command);
if(result)
{
cout << "outMsgReceive, deleting element" << command << endl;
}
else
{
cout << "outMsgReceive, empty element" << i << endl;
}
}
}
private:
//you can use vector both xd
std::list<int> myList;
std::mutex my_mutex;
std::mutex my_mutex2;
std::vector<int> myvector;
};
/*
Notes :
List : elements can be inserted and removed just by modifying a few pointers, so that can be quite fast.(contiguo memory)
Vector use for random element insertion, but deleting random element in vector mid is slow(randow memory)
*/
int main()
{
/*vector<thread> myhtreads;
for (int i = 0; i < 10; i++)
{
myhtreads.push_back(thread(myprinter,i));
}
for (auto iter = myhtreads.begin(); iter != myhtreads.end() ; iter++)
iter->join();*/
A myobj;
std::thread myOutThread(&A::outMsgReceive, std::ref(myobj));
std::thread myInThread(&A::inMsgReceive, std::ref(myobj));
myInThread.join();
myOutThread.join();
//mutex 保护共享数据,把共享数据锁住,其他想操控共享数据的线程必须等待解锁。
// 先 lock 操作共享数据,unlock -> 每调用一次lock, 必然调用一次unlock。你忘记unlock lock_guard 替你unlock
cout << "hello kawaii" << endl;
return 0;
} | true |
ff38d98a9603d9e9b3d796127b0b4d891a607355 | C++ | Lawrencemm/LM-Engine | /lmng/include/lmng/name.h | UTF-8 | 633 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <string>
#include <entt/entt.hpp>
namespace lmng
{
struct name
{
std::string string;
};
inline std::string get_name(entt::registry const ®istry, entt::entity entity)
{
auto name_component = registry.try_get<name>(entity);
return name_component ? name_component->string
: std::to_string(to_integral(entity));
}
// Gets the name including parents in parent.child.grandchild format
std::string resolve_name(entt::registry const ®istry, entt::entity entity);
entt::entity
find_entity(entt::registry const ®istry, std::string const &name);
} // namespace lmng
| true |
173492bf8acdfc0fcb0bb16a8ece332b51a3219b | C++ | yvxiang/POJ | /1936.cpp | UTF-8 | 475 | 2.890625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *q,*p,*r;
bool check(char ch,char *dst)
{
while(*dst) {
if(*dst==ch) {
r=dst+1;
return true;
}
dst++;
}
return false;
}
int main()
{
char s[100002],t[100002];
p=s;
q=t;
while(scanf("%s%s",s,t)!=EOF) {
p=s;
q=t;
r=q;
bool flag=true;
while(*p) {
if(!check(*p,q)) {
printf("No\n");
flag=false;
break;
}
q=r;
p++;
}
if(flag) {
printf("Yes\n");
}
}
}
| true |
5d582fb0a5facf05b2e7c76cd39abe33e66ebc90 | C++ | AnthonyZhai/STL_Customed | /List/List_Dynamic.cpp | UTF-8 | 1,989 | 3.609375 | 4 | [] | no_license | #include "List_Dynamic.h"
#include <cassert>
using namespace std;
template <class T>
List_Dynamic<T>::List_Dynamic(int maxSize):size(0),capacity(maxSize)
{
List_Array=new(nothrow) T[maxSize];
assert(List_Array!=0);
}
template <class T>
List_Dynamic<T>::List_Dynamic(const List_Dynamic<T>& right)
:size(right.size),capacity(right.capacity){
List_Array=new(nothrow) T[capacity];
if(List_Array!=0){
for(int i=0;i<size;i++)
List_Array[i]=right.List_Array[i];
}
else{
cerr<<"No more mem for creating list!"<<endl;
exit(1);
}
}
template<class T>
const List_Dynamic<T>& List_Dynamic<T>::operator =(const List_Dynamic<T>& right)
{
if(this!=right){
if(capacity!=right.capacity){
delete []List_Array;
capacity=right.capacity;
List_Array=new(nothrow) T[capacity];
if(List_Array==0){
cerr<<"No more mem for creating list!"<<endl;
exit(1);
}
}
size=right.size;
for(int i=0;i<size;i++)
List_Array[i]=right.List_Array[i];
}
return *this;
}
template <class T>
List_Dynamic<T>::~List_Dynamic()
{
delete []List_Array;
size=0;
capacity=0;
}
template <class T>
bool List_Dynamic<T>::empty() const
{
return size==0;
}
template <class T>
void List_Dynamic<T>::insert(T item,int pos)
{
if(size==capacity){
cerr<<"No more space for insertion!"<<endl;
exit(1);
}
if(pos<0||pos>size){
cerr<<"Index out of bouds!"<<endl;
return;
}
for(int i=size;i>pos;i--){
List_Array[i]=List_Array[i-1];
}
List_Array[pos]=item;
size++;
}
template <class T>
void List_Dynamic<T>::erase(int pos)
{
if(size==0){
cerr<<"List is empty"<<endl;
exit(1);
}
if(pos<0||pos>=size){
cerr<<"Index out of bouds"<<endl;
return;
}
for(int i=pos;i<size;i++){
List_Array[i]=List_Array[i+1];
}
size--;
}
template <class T>
void List_Dynamic<T>::display(ostream &out) const
{
for(int i=0;i<size;i++)
out<<List_Array[i]<<" ";
}
template <class T>
ostream& operator << (ostream &out,const List_Dynamic<T> &aList)
{
aList.display(out);
return out;
} | true |
ad3dd580e02ea723f9922303c23ef32c91810cf2 | C++ | Pawel0/Sortowania | /main.cpp | UTF-8 | 3,855 | 3.125 | 3 | [] | no_license | #include <cstdlib>
#include <iostream>
#include <time.h>
#include <unistd.h>
using namespace std;
void rysuj( int tab[], int size )
{
for( int i = 0; i < size; i++ )
{
cout<<tab[i]<<" ";
}
cout<<endl;
}
void Bombelkowe( int tab[], int size )
{
for( int i = 0; i < size; i++ )
{
for( int j = 0; j < size - 1; j++ )
{
if( tab[ j ] > tab[ j + 1 ] )
swap( tab[ j ], tab[ j + 1 ] );
}
}
}
void Grzebieniowe( int tab[], int size )
{
int gap = size;
bool replace = true;
while( gap > 1 || replace )
{
gap = gap * 10 / 13;
if( gap == 0 )
gap = 1;
replace = false;
for( int i = 0; i + gap < size; i++ )
{
if( tab[ i + gap ] < tab[ i ] )
{
swap( tab[ i ], tab[ i + gap ] );
replace = true;
}
}
}
}
void Koktailowe( int tab[], int size )
{
int bottom = 0, top = size - 1;
bool replace = true;
while( replace )
{
replace = false;
for( int i = bottom; i < top; i++ )
{
if( tab[ i ] > tab[ i + 1 ] )
{
swap( tab[ i ], tab[ i + 1 ] );
replace = true;
}
}
top--;
for( int i = top; i > bottom; i-- )
{
if( tab[ i ] < tab[ i - 1 ] )
{
swap( tab[ i ], tab[ i - 1 ] );
replace = true;
}
}
bottom++;
}
}
void PrzezWstawianie( int tab[], int size )
{
int temp, j;
for( int i = 1; i < size; i++ )
{
temp = tab[ i ];
for( j = i - 1; j >= 0 && tab[ j ] > temp; j-- )
tab[ j + 1 ] = tab[ j ];
tab[ j + 1 ] = temp;
}
}
void PrzezWybieranie( int tab[], int size )
{
int k;
for( int i = 0; i < size; i++ )
{
k = i;
for( int j = i + 1; j < size; j++ )
if( tab[ j ] < tab[ k ] )
k = j;
swap( tab[ k ], tab[ i ] );
}
}
void Sybkie( int tab[], int left, int right )
{
int i = left;
int j = right;
int x = tab[( left + right ) / 2 ];
do
{
while( tab[ i ] < x )
i++;
while( tab[ j ] > x )
j--;
if( i <= j )
{
swap( tab[ i ], tab[ j ] );
i++;
j--;
}
} while( i <= j );
if( left < j ) Sybkie( tab, left, j );
if( right > i ) Sybkie( tab, i, right );
}
int main()
{
srand( time( NULL));
int zakres;
int poczatek;
int t;
int a;
cout<<"zakres liczb losowych:\n"
<<"od: "; cin>>poczatek;
cout<<"do: "; cin>>zakres;
zakres-=poczatek;
cout<<"ilosc liczb do posortowania: "; cin>>t;
cout<<"1.Sortowanie Bombelkowe\n"
<<"2.Sortowanie Grzebieniowe\n"
<<"3.Sortowanie Koktailowe\n"
<<"4.Sortowanie Przez Wstawianie\n"
<<"5.Sortowanie Przez Wybieranie\n"
<<"6.Sortowanie Sybkie\n"
<<"---------Dane do posortowania---------\n";
int tablica[t];
for(int i=0;i<t;i++)
{
tablica[i] = ( rand() % zakres) + poczatek;
}
rysuj(tablica,t);
cin>>a;
switch(a)
{
case 1:
{
time_t begin;
time_t end;
begin = clock();
Bombelkowe(tablica,t);
end = clock();
rysuj(tablica,t);
cout<<((end-begin)*1000/CLK_TCK);
break;
}
case 2:
Grzebieniowe(tablica,t);
rysuj(tablica,t);
break;
case 3:
Koktailowe(tablica,t);
rysuj(tablica,t);
break;
case 4:
PrzezWstawianie(tablica,t);
rysuj(tablica,t);
break;
case 5:
PrzezWybieranie(tablica,t);
rysuj(tablica,t);
break;
case 6:
Sybkie(tablica, t-t, t-1);
rysuj(tablica,t);
break;
}
return 0;
}
| true |
0301214fc838149205468529e4f0a8a61d8cf216 | C++ | AustinHerman95/AGameAboutNothing | /enemy.h | UTF-8 | 634 | 2.578125 | 3 | [] | no_license | #pragma once
#include <SFML\Graphics.hpp>
#include "animate.h"
#include "player.h"
#include <cmath>
class Enemy: public Animate
{
public:
Enemy();
Enemy(const std::string &name, sf::Vector2i dimensions, sf::Vector2f mPosition);
void path(sf::FloatRect* pMoveBox, sf::Clock* clock);
int findPlayer(sf::FloatRect* pMoveBox);
void move(sf::FloatRect* pMoveBox);
void kill();
void setSight(int sightDirection);
void setEnPosition(sf::Vector2f position);
sf::RectangleShape getSight();
private:
enum movement{UP, DOWN, LEFT, RIGHT, NONE};
movement moving;
sf::Vector2f velocity;
sf::RectangleShape sight;
bool spotted;
};
| true |
f93d96d0167cf9d6ee332e2703dde02c5351c892 | C++ | shh1473/Sunrin_Engine_2019 | /Direct3D_11/Sunrin_Engine_D3D11/Engine/SR_GameScene.h | UTF-8 | 2,412 | 2.578125 | 3 | [
"MIT"
] | permissive | #pragma once
#include "SR_Entity.h"
#include "SR_UI.h"
#include "SR_UpdateExecutor.h"
#include "SR_RenderExecutor.h"
#include "SR_ResourceGenerator.h"
namespace SunrinEngine
{
class SR_GameScene : public SR_NonCopyable
{
public:
explicit SR_GameScene(const std::wstring & name);
virtual ~SR_GameScene();
virtual bool OnEnter();
virtual bool OnExit();
virtual bool Initialize();
virtual bool FixedUpdate();
virtual bool Update();
virtual bool LateUpdate();
bool RenderFromExecutor();
bool FixedUpdateFromExevutor();
bool UpdateFromExevutor();
bool DefaultLateUpdate();
void SetIsDestroyed(bool isDestroyed) noexcept { m_isDestroyed = isDestroyed; }
bool GetIsDestroy() const noexcept { return m_isDestroyed; }
const std::wstring & GetName() const noexcept { return m_name; }
SR_UpdateExecutor & GetUpdateExecutor() noexcept { return m_updateExecutor; }
SR_RenderExecutor & GetRenderExecutor() noexcept { return m_renderExecutor; }
SR_ResourceGenerator & GetResourceGenerator() noexcept { return m_resourceGenerator; }
const std::map<std::wstring, std::unique_ptr<SR_Entity>> & GetEntities() const noexcept { return m_entities; }
const std::map<std::wstring, std::unique_ptr<SR_UI>> & GetUIs() const noexcept { return m_UIs; }
public:
template <typename T>
T * AddEntity(T * entity)
{
std::lock_guard<std::mutex> lockGuard(m_addEntityMutex);
std::unique_ptr<T> ent{ entity };
m_entities[entity->GetName()] = std::move(ent);
return entity;
}
template <typename T>
T * FindEntity(const std::wstring & name)
{
assert(m_entities.count(name) > 0);
return dynamic_cast<T*>(m_entities[name].get());
}
template <typename T>
T * AddUI(T * UI)
{
std::lock_guard<std::mutex> lockGuard(m_addUIMutex);
std::unique_ptr<T> ui{ UI };
m_UIs[UI->GetName()] = std::move(ui);
return UI;
}
template <typename T>
T * FindUI(const std::wstring & name)
{
assert(m_UIs.count(name) > 0);
return dynamic_cast<T*>(m_UIs[name].get());
}
private:
std::mutex m_addEntityMutex;
std::mutex m_addUIMutex;
private:
bool m_isDestroyed;
std::wstring m_name;
SR_UpdateExecutor m_updateExecutor;
SR_RenderExecutor m_renderExecutor;
SR_ResourceGenerator m_resourceGenerator;
std::map<std::wstring, std::unique_ptr<SR_Entity>> m_entities;
std::map<std::wstring, std::unique_ptr<SR_UI>> m_UIs;
};
} | true |
97caa13a3e05462873f49fae88c60c101187fbc7 | C++ | krayong/Data-Structures-and-Algorithms | /BinaryTree/check_mirror.cpp | UTF-8 | 3,655 | 2.953125 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
/*************************************************************************************************************
*
* Link : https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0
* Description:
Given two n-ary tree's the task is to check if they are mirror of each other or not.
Input:
1 1
/ \ / \
2 3 3 2
Output: 1
1 1
/ \ / \
2 3 2 3
Output: 0
Input:
The first line of input contains an integer T denoting the no of test cases.
Then T test cases follow. The first line of each test case contains two space
separated values n and e denoting the no of nodes and edges respectively.
Then in the next line two lines are 2*e space separated values
u,v denoting an edge from u to v for the both trees .
Output:
For each test case in a new line print 1 if both the trees are mirrors of each other else print 0.
Constraints:
1<=T<=20
1<=n<=15
1<=e<=20
Example:
Input:
2
3 2
1 2 1 3
1 3 1 2
3 2
1 2 1 3
1 2 1 3
Output:
1
0
* Resources:
* https://www.geeksforgeeks.org/check-mirror-n-ary-tree/
*
*************************************************************************************************************/
#define si(x) scanf("%d", &x)
#define sll(x) scanf("%lld", &x)
#define ss(s) getline(cin, s)
#define pi(x) printf("%d\n", x)
#define pll(x) printf("%lld\n", x)
#define ps(s) cout << s << "\n"
#define ll long long
#define fo(i, k, n) for (ll i = k; i < n; i++)
#define rof(i, k, n) for (ll i = k; i >= n; i--)
#define deb(x) cout << #x << "=" << x << "\n"
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define clr(x) memset(x, 0, sizeof(x))
#define set(x, i) memset(x, i, sizeof(x))
#define sortall(x) sort(all(x))
#define tr(a, it) for (auto it = a.begin(); it != a.end(); it++)
#define present(c, x) (c.find(x) != c.end())
#define cpresent(c, x) (find(all(c), x) != c.end())
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<string> vs;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
bool check_mirror(vector<stack<int>> &tree1, vector<queue<int>> &tree2)
{
fo(i, 1, tree1.size()) // nodes are from 1 to n
{
stack<int> &s = tree1[i];
queue<int> &q = tree2[i];
while (!s.empty() && !q.empty())
{
if (s.top() != q.front())
return false;
s.pop();
q.pop();
}
if (!s.empty() || !q.empty())
return false;
}
return true;
}
int main()
{
ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
int t;
si(t);
while (t--)
{
int n, e;
si(n);
si(e);
vector<stack<int>> tree1(n + 1);
fo(i, 0, e)
{
int l, r;
si(l);
si(r);
tree1[l].push(r);
}
vector<queue<int>> tree2(n + 1);
fo(i, 0, e)
{
int l, r;
si(l);
si(r);
tree2[l].push(r);
}
if (check_mirror(tree1, tree2))
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
} | true |
e1f91db692f726a6048bd8d02ceb398572338ff7 | C++ | spiderxm/Competitive-Coding | /DataStructures/Linked list/remove_kth_node_from_end.cpp | UTF-8 | 1,202 | 3.515625 | 4 | [] | no_license | //
// Created by Mrigank Anand on 05/09/20.
//
#include<iostream>
#define ll long long
using namespace std;
class node {
public:
node *next;
ll data;
node(ll d) {
data = d;
next = NULL;
}
};
void insertion_at_tail(node *&head, int d) {
if (head == NULL) {
head = new node(d);
} else {
node *temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
node *temp2 = new node(d);
temp->next = temp2;
}
}
void print(node *head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
void remove_kth_element(node *head, ll k) {
node *fast = head;
node *slow = head;
while (k--) {
fast = fast->next;
}
while (fast->next != NULL) {
fast = fast->next;
slow = slow->next;
}
node *temp = slow->next;
slow->next = slow->next->next;
delete temp;
return;
}
int main() {
node *head = NULL;
ll n;
cin >> n;
ll k;
cin >> k;
while (n--) {
ll d;
cin >> d;
insertion_at_tail(head, d);
}
remove_kth_element(head, k);
print(head);
return 0;
} | true |
653d4fc725622d21b6c7323753bf79c118b50665 | C++ | shanodis/Beakout-Arkanoid-SFML-2.x | /Arkanoid SFML/src/Blocks.h | UTF-8 | 484 | 2.546875 | 3 | [] | no_license | #include "Engine.h"
class Blocks
{
protected:
unsigned int totalBlocks;
float blockX, blockY;
Texture blockTextureBlue, blockTextureYellow, blockTextureGreen;
private:
Vector2f middleScreen;
private:
void Level1();
void Level2();
void Level3();
void onlineLevel();
public:
Sprite **blockSprite;
Sprite **verticalBlockSprite;
public:
Blocks();
~Blocks();
void drawBlocks(RenderWindow&, bool verticalDrawing);
void setLevel(unsigned int level, bool singlePlayer);
};
| true |
51ea9942a62b101925e97df0be52067356c678ee | C++ | GriciuGriger/rzutUkosny | /Cialo.cpp | UTF-8 | 1,847 | 3.125 | 3 | [] | no_license | #include "Cialo.h"
#include <iostream>
#include <iomanip>
#include <windows.h>
#include <math.h>
#define g 9.81
Cialo::Cialo(std::string name)
{
this->name = name;
this->w_predkosci = new WektorPredkosci(0.0, 0.0, 0.0);
this->w_polozenia = new Wektor(0.0, 0.0, 0.0);
}
void Cialo::nadajPredkosc(Wektor *wp){
this->w_predkosci = wp;
}
void Cialo::przeprowadzRzutUkosny(double time){
Wektor *wpolozenia = this->w_polozenia;
WektorPredkosci *wpredkosci = (WektorPredkosci*) this->w_predkosci;
double kat = wpredkosci->getKatNachylenia();
// std::cout<<"Kat: "<<kat<<std::endl<<"Sin(kat): "<<sin(kat*M_PI/180);
// int i = 0;
// wpredkosci->setY(wpredkosci->getWartosc() * sin(kat*M_PI/180) - g*i);
// std::cout<<std::endl<<wpredkosci->getY();
for(double i=0; i<time; i=i+1.0){
Sleep(1000);
wpredkosci->setY(wpredkosci->getWartosc() * sin(kat*M_PI/180) - g*i);
wpolozenia->setX(wpredkosci->getX() * i);
wpolozenia->setY(wpredkosci->getY() * i - (g*i*i)/2);
std::cout<<"Ruch ciala po "<<i<<" sekund: "<<std::endl;
this->pokazWektorPolozenia();
this->pokazWektorPredkosci();
}
}
std::string Cialo::getName(){
return this->name;
}
void Cialo::pokazWektorPredkosci(){
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout<<"Wektor predkosci ciala "<< this->getName() <<": ["<<this->w_predkosci->getX()<<", "<<this->w_predkosci->getY()<<", "<<this->w_predkosci->getZ()<<"]"<<std::endl;
}
void Cialo::pokazWektorPolozenia(){
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout<<"Wektor polozenia ciala "<< this->getName() <<": ["<<this->w_polozenia->getX()<<", "<<this->w_polozenia->getY()<<", "<<this->w_polozenia->getZ()<<"]"<<std::endl;
}
Cialo::~Cialo()
{
//dtor
}
| true |
e336a04f3245735e14546410a9f078e2e78859ac | C++ | Ceyword/ssdb | /src/proc_queue.cpp | UTF-8 | 1,878 | 2.53125 | 3 | [] | no_license | /* queue */
static int proc_qsize(Server *serv, Link *link, const Request &req, Response *resp){
if(req.size() < 2){
resp->push_back("client_error");
}else{
int64_t ret = serv->ssdb->qsize(req[1]);
if(ret == -1){
resp->push_back("error");
}else{
char buf[20];
sprintf(buf, "%" PRIu64 "", ret);
resp->push_back("ok");
resp->push_back(buf);
}
}
return 0;
}
static int proc_qfront(Server *serv, Link *link, const Request &req, Response *resp){
if(req.size() < 2){
resp->push_back("client_error");
}else{
std::string item;
int ret = serv->ssdb->qfront(req[1], &item);
if(ret == -1){
resp->push_back("error");
}else if(ret == 0){
resp->push_back("not_found");
}else{
resp->push_back("ok");
resp->push_back(item);
}
}
return 0;
}
static int proc_qback(Server *serv, Link *link, const Request &req, Response *resp){
if(req.size() < 2){
resp->push_back("client_error");
}else{
std::string item;
int ret = serv->ssdb->qback(req[1], &item);
if(ret == -1){
resp->push_back("error");
}else if(ret == 0){
resp->push_back("not_found");
}else{
resp->push_back("ok");
resp->push_back(item);
}
}
return 0;
}
static int proc_qpush(Server *serv, Link *link, const Request &req, Response *resp){
if(req.size() < 3){
resp->push_back("client_error");
}else{
int ret = serv->ssdb->qpush(req[1], req[2]);
if(ret == -1){
resp->push_back("error");
}else{
resp->push_back("ok");
}
}
return 0;
}
static int proc_qpop(Server *serv, Link *link, const Request &req, Response *resp){
if(req.size() < 2){
resp->push_back("client_error");
}else{
std::string item;
int ret = serv->ssdb->qpop(req[1], &item);
if(ret == -1){
resp->push_back("error");
}else if(ret == 0){
resp->push_back("not_found");
}else{
resp->push_back("ok");
resp->push_back(item);
}
}
return 0;
}
| true |
046ad04e8151c95ec50098a908d15682fe2b7e24 | C++ | wjddlsy/Algorithm | /Baekjoon/baek_11969_BreedCounting/main.cpp | UTF-8 | 709 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int N, Q;
cin>>N>>Q;
vector<int> one(N+1, 0), two(N+1, 0), three(N+1, 0);
for(int i=1; i<=N; ++i){
int a; cin>>a;
if(a==1)
one[i]=1;
else if(a==2)
two[i]=1;
else if(a==3)
three[i]=1;
one[i]+=one[i-1];
two[i]+=two[i-1];
three[i]+=three[i-1];
}
for(int i=0; i<Q; ++i){
int a, b;
cin>>a>>b;
cout<<one[b]-one[a-1]<<" "<<two[b]-two[a-1]<<" "<<three[b]-three[a-1]<<'\n';
}
//std::cout << "Hello, World!" << std::endl;
return 0;
} | true |
2b2225f5ef8813b4a9468d871819e79fead679d1 | C++ | Arnknee/ArduinoPong | /ArduinoPong/graphics.h | UTF-8 | 367 | 2.75 | 3 | [] | no_license | #ifndef GRAPHICS_H
#define GRAPHICS_H
#include <SDL.h>
class Graphics
{
public:
Graphics(int screenwidth, int screenheigth);
~Graphics();
void flip();
void clear();
SDL_Renderer * getRenderer();
int getScreenHeigth();
int getScreenWidth();
private:
SDL_Window* _window = NULL;
SDL_Renderer* _renderer = NULL;
int _screenwidth, _screenheigth;
};
#endif | true |
9b7e462d78bd5af2056a6db548cffee33e3facb6 | C++ | mrlous2789/Project | /ProjectDibenaySDL/Province.cpp | UTF-8 | 1,791 | 2.609375 | 3 | [] | no_license | #include "Province.h"
namespace Mer
{
Province::Province()
{
provinceBorders = SDL_CreateRGBSurface(0, 1920, 1080, 32, 0, 0, 0, 0);
pixels = (Uint32*)provinceBorders->pixels;
format = provinceBorders->format;
}
Province::Province(std::string id, Uint8 red, Uint8 green, Uint8 blue, int screenWidth, int screenHeight)
{
this->id = id;
this->red = red;
this->green = green;
this->blue = blue;
Uint32 rmask, gmask, bmask, amask;
rmask = 0x00;gmask = 0x00;bmask = 0x00;amask = 0x00;
provinceBorders = SDL_CreateRGBSurface(0, 3840, 2160, 32, rmask, gmask, bmask, amask);
provinceBorders = SDL_ConvertSurfaceFormat(provinceBorders, SDL_PIXELFORMAT_RGBA8888, 0);
SDL_FillRect(provinceBorders, NULL, SDL_MapRGBA(provinceBorders->format, 0, 0, 0, 0));
pixels = (Uint32*)provinceBorders->pixels;
format = provinceBorders->format;
sRect.x = 0; sRect.y = 0; sRect.w = 3840; sRect.h = 2160;
dRect.x = 0; dRect.y = 0; dRect.w = screenWidth; dRect.h = screenHeight;
}
Uint8 Province::getRed()
{
return red;
}
Uint8 Province::getGreen()
{
return green;
}
Uint8 Province::getBlue()
{
return blue;
}
std::string Province::getID()
{
return id;
}
void Province::MapPixelColour(int x, int y, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha)
{
Uint32 color = SDL_MapRGBA(format, red, green, blue, alpha);
pixels[(y * provinceBorders->w) + x] = color;
}
SDL_Texture* Province::getTexture()
{
return provinceTexture;
}
SDL_Surface* Province::getSurface()
{
return provinceBorders;
}
void Province::ConvertToTexture(SDL_Renderer* renderer)
{
provinceTexture = SDL_CreateTextureFromSurface(renderer, provinceBorders);
}
SDL_Rect* Province::getSRect()
{
return &sRect;
}
SDL_Rect* Province::getDRect()
{
return &dRect;
}
}
| true |
60d4fed9fb25dbe94000d21c08dce84c0fcffaed | C++ | SurimYuk/Algorithm | /_BAEKJOON/11652_카드.cpp | UTF-8 | 555 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
map<long long, int> m;
map<long long, int>::iterator it;
int main(void) {
int n;
long long num;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> num;
m[num]++;
}
int max = -1;
long long maxNum = -1;
for (it = m.begin(); it != m.end(); it++) {
if (it->second > max) {
max = it->second;
maxNum = it->first;
}
else if (it->second == max) {
maxNum = min(maxNum, it->first);
}
}
cout << maxNum;
return 0;
} | true |
3ab6156d51882e301789c2ec8a6c4079664fdc36 | C++ | DanyYanev/SchoolDiary | /functions/add_to_file.cpp | UTF-8 | 804 | 2.9375 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<fstream>
#include"../headers/student.h"
using namespace std;
void addToFile(string fname){
Employee s;
ofstream ofs;
ofs.open(fname.c_str(), ios_base::app);
while(1){
cout << "Enter name: ";
string name = "";
cin >> name;
if(!name.compare("none")){
break;
}
s.setName(name);
double salary = 0.0, Wdays = 0.0, Wddays = 0.0, Oh = 0.0, coef = 0.0;
cout << "Enter Salary: ";
cin >> salary;
s.setSalary(salary);
cout << "Enter work days for month: ";
cin >> Wdays;
s.setWday(Wdays);
cout << "Enter worked days: ";
cin >> Wddays;
s.setWddays(Wddays);
cout << "Enter overtime worked hours: ";
cin >> Oh;
s.setOverHours(Oh);
ofs << s.toString();
ofs.close();
}
}
| true |
c7180213942bf1a4fc35ec2b161f0137a847d164 | C++ | Darthron/Algorithms | /Problems/Educational Round 1/6.cpp | UTF-8 | 3,490 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <vector>
const double INF = 1 << 30;
struct Line
{
// y = a * x + b;
double a;
double b;
double& x = a;
double& y = b;
Line(double p,
double q)
: a(p),
b(q)
{
}
Line()
{
}
};
struct Segment
{
Line line;
Point p;
Point q;
Segment(Line l,
Point r,
Point s)
: line(l),
p(r),
q(s)
{
}
Segment()
{
}
};
using Point = Line;
Line
getLine(const Point& p,
const Point& q)
{
double slope;
if (p.x == q.x)
{
return Line(p.x,
INF);
}
if (p.y == q.y)
{
return Line(0,
p.y);
}
/*
a * x1 + b = y1;
a * x2 + b = y2;
*/
slope = (p.y - q.y) / (p.x - q.x);
return Line(slope,
p.y - slope * p.x);
}
Segment
getSegment(const Point& p,
const Point& q)
{
return Segment(getLine(p, q),
p,
q);
}
Point
getIntersectionPoint(Segment segment,
Line l)
{
double xOfIntersection;
if(l == segment.line)
{
//TODO
return Point();
}
// Parallel line
if (l.a == segment.line.a)
{
return Point(INF,
INF);
}
// a1 * x + b1 = a2 * x + b2
xOfIntersection = (segment.line.b - line.b) / (line.a - segment.line.a);
if ( (xOfIntersection >= std::min(segment.p.x, segment.q.x) and
(xOfIntersection <= std::max(segment.p.x, segment.q.x) )
{
return Point(xOfIntersection,
line.a * xOfIntersection + line.b);
}
// Not intersecting the segment
return Point(INF,
INF);
}
int main()
{
int N;
int M;
int index;
Point tempPoint;
Point tempPoint2;
std::vector <Point> polygonPoints;
std::vector <Segment> polygonSegments;
std::vector <Point> intersectionPoints;
std::cin >> N;
std::cin >> M;
// Reading the n-gon points
for (index = 0; index < N; ++index)
{
std::cin >> tempPoint.x;
std::cin >> tempPoint.y;
polygonPoints.push_back(tempPoint);
}
// Creating the n-gon segments
for (index = 1; index < N; ++index)
{
polygonSegments.push_back(getSegment(polygonPoints[i - 1],
polygonPoints[i]));
}
// The segment determined by the last point and the first one
polygonSegments.push_backI(getSegment(polygonPoints[i - 1],
polygonPoints[0]));
// Reading the lines
for (index = 0; index < M; ++index)
{
std::cin >> tempPoint.x;
std::cin >> tempPoint.y;
std::cin >> tempPoint2.x;
std::cin >> tempPoint2.y;
intersectionPoints.clear();
for (const auto& segment : polygonSegments)
{
tempPoint = getIntersectionPoint(segment,
getLine(tempPoint,
tempPoint2))
if ( (tempPoint.x != INF) and
(tempPoint.y != INF) )
{
intersectionPoints.push_back(tempPoint);
}
}
}
return 0;
}
| true |
5937df275fc614e806118c3ad0d01a4a67e334d5 | C++ | bhupkas/Backup | /programs/codes/codeforces/practice/190d2_2.cpp | UTF-8 | 570 | 2.875 | 3 | [] | no_license |
#include <stdio.h>
#include <math.h>
int main()
{
int x1,y1,r1,x2,y2,r2;
while (scanf("%d%d%d%d%d%d",&x1,&y1,&r1,&x2,&y2,&r2)==6)
{
int delta1=(r2+r1)*(r2+r1);
int delta2=(r2-r1)*(r2-r1);
int delta3=(x2-x1)*(x2-x1)+(y2-y1)*(y2-y1);
if (delta3>=delta1)
{
printf("%.10f\n",(sqrt(delta3*1.0)-r1-r2)/2.0);
}
else if (delta3<=delta2)
{
printf("%.10f\n",(fabs(r2*1.0-r1)-sqrt(delta3*1.0))/2.0);
}
else
puts("0.00000000000");
}
return 0;
} | true |
3f0a5909af13f831c6b794f50e2f22b2d5f9b8cb | C++ | Hyeongho/Academic_Materials | /C++ 5주차/과제 해설/Number.h | UTF-8 | 252 | 2.765625 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <algorithm>
using namespace std;
class Number
{
int size;
float *arr;
public:
Number();
Number(int _size);
~Number();
void SetArr();
void Print();
float Max();
float Min();
float Average();
}; | true |
8cc9b4c4360afa40da887661aa775e1ac16ac305 | C++ | happyj/e4c | /tests/generation-tests/widgetsmm/Property.cpp | UTF-8 | 904 | 2.5625 | 3 | [] | no_license |
#include "Property.hpp"
#include <widgetsmm/WidgetsmmPackage.hpp>
using namespace widgetsmm;
/*PROTECTED REGION ID(widgetsmm::Property include) START*/
/*PROTECTED REGION END*/
Property::Property() :
m_name(),
m_value()
{
/*PROTECTED REGION ID(Property constructor) START*/
/*PROTECTED REGION END*/
}
Property::~Property()
{
/*PROTECTED REGION ID(Property destructor) START*/
/*PROTECTED REGION END*/
}
void Property::setName(name_t _name)
{
m_name = _name;;
}
Property::name_t Property::getName() const
{
return m_name;
}
void Property::setValue(value_t _value)
{
m_value = _value;;
}
Property::value_t Property::getValue() const
{
return m_value;
}
/*PROTECTED REGION ID(widgetsmm::Property implementation) START*/
/*PROTECTED REGION END*/
ecore::EClass_ptr Property::eClassImpl() const
{
return WidgetsmmPackage::_instance()->getProperty();
}
| true |
d048ad06f27d211e480a6dc96dc58cfa43cddad7 | C++ | Marc--Olivier/presentations | /cpp_in_brussels_2017-05-16/boost_graph_library/code/src/tests/testGraph.cpp | UTF-8 | 1,944 | 3.453125 | 3 | [] | no_license | #include <catch.hpp>
#include "Graph.hpp"
#include "tests/utils.hpp"
namespace test {
SCENARIO("create graph", "[boost::adjacency_list]") {
GIVEN("an empty graph G") {
Graph g;
WHEN("add 5 vertices and 5 edges to G") {
buildGraph(g);
THEN("G has 5 vertices and 5 edges") {
CHECK(boost::num_vertices(g) == 5);
CHECK(boost::num_edges(g) == 5);
}
}
}
}
SCENARIO("get an edge (if exist)", "[boost::adjacency_list]") {
GIVEN("a graph G with:\n"
"- 5 vertices: V0, V1, V2, V3, V4\n"
"- 5 edges: V0->V1, V0->V3, V1->V3, V3->V4, V4->V2")
{
Graph g;
buildGraph(g);
WHEN("/") {
THEN("G has an edge between V1 and V3") {
bool isEdge = false;
Edge e;
const Vertex v1 = 1;
const Vertex v3 = 3;
boost::tie(e, isEdge) = boost::edge(v1, v3, g);
CHECK(isEdge == true);
}
THEN("G has no edge between V0 and V4") {
bool isEdge = false;
Edge e;
const Vertex v0 = 0;
const Vertex v4 = 4;
boost::tie(e, isEdge) = boost::edge(v0, v4, g);
CHECK(isEdge == false);
}
}
}
}
SCENARIO("edge iterator", "[boost::adjacency_list]") {
GIVEN("a graph G with:\n"
"- 5 vertices: V0, V1, V2, V3, V4\n"
"- 5 edges: (V0,V1), (V0,V3), (V1,V3), (V3,V4), (V4,V2)")
{
Graph g;
buildGraph(g);
WHEN("compute total edge weight") {
size_t totalWeight = 0;
for (const Edge& e : boost::make_iterator_range(edges(g))) {
totalWeight += g[e].weight;
}
THEN("total edge weight == 22") {
CHECK(totalWeight == 22);
}
}
}
}
}
| true |
fd36903a848dfa576331f53def5d4515b90fb5d1 | C++ | novikov-ilia-softdev/thinking_cpp | /tom_1/chapter_15/26/ostack.h | UTF-8 | 594 | 3.375 | 3 | [] | no_license | #ifndef OSTACK_H
#define OSTACK_H
class Object{
public:
virtual ~Object() = 0;
};
inline Object::~Object() {}
class Stack{
public:
Stack() : head_( 0) {}
~Stack()
{
while( head_)
{
delete pop();
}
}
void push( Object* dat)
{
head_ = new Link( dat, head_);
}
Object* pop()
{
if( !head_)
return 0;
Object* result = head_->data;
Link* oldHead = head_;
head_ = head_->next;
delete oldHead;
return result;
}
private:
struct Link{
Object* data;
Link* next;
Link( Object* dat, Link* nxt): data( dat), next( nxt) {}
}* head_;
};
#endif //OSTACK_H
| true |
1f2c1ef8ef4b204cd1bc8906c54d5df912b653fd | C++ | pallavigudipati/deluminator | /Project-Euler/lcm.cpp | UTF-8 | 356 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
main() {
unordered_set<int> fac2 = 0;
int fac3 = 0;
int fac5 = 0;
int fac7 = 0;
int fac11 = 0;
int fac13 = 0;
int fac17 = 0;
int fac19 = 0;
for (int i = 11; i <= 20; ++i) {
}
}
11
12 - 2 2 3
13
14 - 2 7
15 - 3 5
16 - 2 2 2 2
17
18 - 2 3 3
19
20 - 2 2 5
| true |
8fa0da73e7ad9b7327010e013c8ef5574b6dbda5 | C++ | OfficerGrag/testingOut | /stats/stats.cpp | UTF-8 | 1,473 | 3.625 | 4 | [] | no_license |
#include <iostream>
#include <vector>
float calcMean(std::vector<int> & numbers, std::vector<float> & probs, int number) {
float value{};
for (int i = 0; i < number; i++) {
value += (numbers[i] * probs[i]);
}
return value;
}
void expectedMeanDisRand() {
std::cout << "How many numbers? ";
int number;
std::cin >> number;
std::vector<int> numbers(number);
std::vector<float> probs(number);
for (int i = 0; i < number; i++) {
std::cin >> numbers[i];
}
for (int i = 0; i < number; i++) {
std::cin >> probs[i];
}
std::cout << "\nThe expected mean is:\n";
float value = calcMean(numbers, probs, number);
std::cout << value << '\n';
}
void discreteVariance() {
std::cout << "How many numbers? ";
int number;
std::cin >> number;
std::vector<int> numbers(number);
std::vector<float> probs(number);
for (int i = 0; i < number; i++) {
std::cin >> numbers[i];
}
for (int i = 0; i < number; i++) {
std::cin >> probs[i];
}
std::cout << "\nThe expected variance is:\n";
float value{};
float mean = calcMean(numbers, probs, number);
for (int i = 0; i < number; i++) {
value += static_cast<float>(std::pow((numbers[i] - mean), 2) * probs[i]);
}
std::cout << value << '\n';
}
int main()
{
int n;
float p;
std::cin >> n >> p;
float value = std::sqrt((p * (1 - p)) / n);
std::cout << value;
}
| true |
959baaa457d14c5a5c3b8685cc330e1763159929 | C++ | AvansTi/TMTI-DATC-Voorbeelden | /Week6/AsyncExample/ClassA.h | UTF-8 | 430 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
class BaseClass {
public:
BaseClass() {
data = new int[100];
}
~BaseClass() {
if (data != nullptr) {
delete[] data; data = nullptr;
}
}
BaseClass(const BaseClass&) {
if (data != nullptr) {
}
}
virtual void DoSomething() = 0;
private:
int* data;
};
class ClassB : public BaseClass {
public:
ClassB() : BaseClass() {
}
private:
void DoWork();
};
class C {
public:
C() {
}
};
| true |
37d7092d5b3178171228ba781723e9ba562857fb | C++ | rtlessly/RTL_Motors | /Test/StepperMotor4_RunToPosition_Test/StepperMotor4_RunToPosition_Test.ino | UTF-8 | 1,404 | 2.671875 | 3 | [] | no_license | //
// Shows how to run AccelStepper in the simplest,
// fixed speed mode with no accelerations
/// \author Mike McCauley (mikem@airspayce.com)
// Copyright (C) 2009 Mike McCauley
// $Id: ConstantSpeed.pde,v 1.1 2011/01/05 01:51:01 mikem Exp mikem $
#define DEBUG 1
#include <Debug.h>
#include <StepperMotor_4.h>
StepperMotor_4 stepper(StepperMotor_4::HALF4WIRE, 8, 9, 10, 11); // Defaults to StepperMotor_4::FULL4WIRE (4 pins) on 2, 3, 4, 5
long stepsPerMotorRev = 8 * stepper.interface();
float gearRatio = 64; // 63.65;
float stepsPerShaftRev = stepsPerMotorRev * gearRatio;
long stepsToTurn(float revs) { return revs * stepsPerShaftRev; }
void setup()
{
Serial.begin(115200);
DEBUG_PRINTLN("");
DEBUG_PRINTLN("");
DEBUG_PRINTLN2("gearRatio=",gearRatio);
DEBUG_PRINTLN2("stepsPerMotorRev=",stepsPerMotorRev);
DEBUG_PRINTLN2("stepsPerShaftRev=",stepsPerShaftRev);
float shaftRevs = 2;
long position = stepsToTurn(shaftRevs);
DEBUG_PRINTLN2("revolutions to turn=",shaftRevs);
DEBUG_PRINTLN2("target position=",position);
DEBUG_PRINTLN("");
stepper.setAcceleration(120);
stepper.setTargetSpeed(500);
stepper.setTargetPosition(position);
}
void loop()
{
stepper.runToPosition();
// stepper.enableOutputs();
// stepper.setCurrentPosition(0);
// stepper.setTargetPosition(stepsToTurn);
// stepper.runToPosition();
// stepper.disableOutputs();
// stepsToTurn = -stepsToTurn;
}
| true |