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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b72fa19339d276609022a24e5643440d889c78cb | C++ | Mistakx/Vending-Machine | /EDA Projeto 1/main.cpp | ISO-8859-1 | 2,153 | 3.296875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include "employee.h"
#include "client.h"
using namespace std;
int main(int argc, char* argv[]) {
locale::global(locale("English"));
srand(time(NULL));
string products_file_path = "";
string prices_file_path = "";
if (argc > 1) {
products_file_path = argv[1];
prices_file_path = argv[2];
}
else {
cout << endl;
cout << "Localizao do ficheiro que contm os produtos: ";
getline(cin, products_file_path);
cout << endl;
cout << "Localizao do ficheiro que contm os preos: " ;
getline(cin, prices_file_path);
cout << endl;
system("cls");
}
Products* products = new Products;
products_text_parsing(products_file_path, products); // Parses the "produtos.txt" file to a struct we can work it, and saves the result to "products".
Prices* prices = new Prices;
prices_text_parsing(prices_file_path, prices); // Parses the "precos.txt" file to a struct we can work it , and saves the result to "prices".
if ((products->lenght != 0) and (prices->lenght != 0)) { // If the files were correctly opened.
Vending_machine vending_machine;
initialize_vending_machine(&vending_machine, products, prices);
delete products;
delete prices;
while (true) {
system("cls");
cout << endl;
cout << "Modo de utilizao:" << endl
<< " 1 - Funcionrio" << endl
<< " 2 - Utilizador" << endl << endl;
int choice = 0;
cin >> choice;
switch (choice)
{
case 1:
employee_menu(&vending_machine);
break;
case 2:
client_menu(&vending_machine);
break;
default:
break;
}
}
return 0;
}
else {
cout << "Os ficheiros de inicializao da mquina no foram abertos corretamente." << endl;
return 1;
}
}
| true |
f593ad244073a80c15b170a94ff370b211be25f2 | C++ | vgaudard/liu-tddd38-cpp-exercises | /mixed_exercises/exceptions/exceptions.cpp | UTF-8 | 540 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <stdexcept>
#include <cstdlib>
using namespace std;
class useless_exception : public logic_error
{
public:
useless_exception() : logic_error("I say wattouat!") {}
};
void recursive(int n)
{
if (n == 0)
throw useless_exception();
cout << "Allez, plus que " << n << endl;
return recursive(n-1);
}
int main (int argc, char *argv[])
{
try
{
recursive(atoi(argv[1]));
}
catch (const exception& ex)
{
cout << ex.what() << endl;
}
return 0;
}
| true |
7bbe4b35c0e28b8f0df85c95c4b3e4b59cb9bc4f | C++ | st2662579/cis17a | /Hmwk/Assignment3/Problem11-14/main.cpp | UTF-8 | 1,589 | 3.71875 | 4 | [] | no_license | /*
* File: main.cpp
* Author: Seth Tyler
* Purpose: Calculate pay
* Created on March 26, 2018, 10:05 PM
*/
// System libraries
#include <iostream>
#include <string>
#include "Structures.h"
using namespace std;
int main() {
Worker worker;
int option;
float totalSalary;
while (true) {
cout << "Please select your option \n";
cout << "1. Hourly Paid \n";
cout << "2. Salary \n";
cout << "3. Exit \n";
cin >> option;
switch (option) {
case 1:
HourlyPaid hourlyPaid;
cout << "Enter Number of Hours Worked: ";
cin >> hourlyPaid.HoursWorked;
cout << endl << "Enter Hourly Rate: ";
cin >> hourlyPaid.HourlyRate;
worker.hourlyPaid = hourlyPaid;
totalSalary = worker.hourlyPaid.HoursWorked * worker.hourlyPaid.HourlyRate;
cout << endl << "Total Salary is: " << totalSalary << endl;
break;
case 2:
Salaried salaried;
cout << "Enter Salary: ";
cin >> salaried.Salary;
cout << endl << "Enter Bonus: ";
cin >> salaried.Bonus;
worker.salaried = salaried;
totalSalary = worker.salaried.Salary + worker.salaried.Bonus;
cout << endl << "Total Salary is: " << totalSalary << endl;
break;
case 3:
break;
default:
cout << endl << "Invalid Option\n";
}
if (option == 3)
break;
}
cout << "Thank you\n";
return 0;
} | true |
85273144aad3b7b53c31a1f3309a1812edf6b6fc | C++ | Lee-DongWon/Baekjoon_Problems | /1012.cpp | UTF-8 | 1,134 | 2.90625 | 3 | [] | no_license | #include <iostream>
using namespace std;
void dfs(int N, int M, int y, int x, int **arr, int **visited) {
int dy[4] = { 1,-1,0,0 };
int dx[4] = { 0,0,1,-1 };
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (ny < 0 || ny >= N || nx < 0 || nx >= M)
continue;
if (arr[ny][nx] && !visited[ny][nx]) {
visited[ny][nx]++;
dfs(N, M, ny, nx, arr, visited);
}
}
}
int main() {
int M, N, K;
int **arr = new int*[50];
int **visited = new int*[50];
for (int i = 0; i < 50; i++) {
arr[i] = new int[50];
visited[i] = new int[50];
}
int t, x, y;
cin >> t;
while (t--) {
cin >> M >> N >> K;
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 50; j++) {
arr[i][j] = 0;
visited[i][j] = 0;
}
}
int ans = 0;
for (int i = 0; i < K; i++) {
cin >> x >> y;
arr[y][x] = 1;
}
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
if (arr[i][j] && !visited[i][j]) {
ans++;
visited[i][j]++;
dfs(N, M, i, j, arr, visited);
}
cout << ans << endl;
}
return 0;
}
| true |
60ca4e90f9116a0c97f60bd66cc3b689b24b44d7 | C++ | Edwardlu0904/InterviewQuestion | /CheckStringAnagrams.cpp | UTF-8 | 1,374 | 3.953125 | 4 | [] | no_license | //
// Top 20 String Algorithm Questions from Coding Interviews
// (2) How to check if two Strings are anagrams of each other?
//
//
#include <iostream>
#include <map>
using namespace std;
int getIndex(char c) {
int charCount_index;
if ('a' <= c && 'z' >= c) {
charCount_index = (int)(c - 'a');
} else if ('A' <= c && 'z' >= c) {
charCount_index = (int)(c - 'A');
}
return charCount_index;
}
bool isAnagrams(const char* s, const char* t) {
bool result = false;
//Condition 1: strings length must be indentical
if (strlen(s) != strlen(t)) {
return false;
}
//Condition 2: two words with same character counts
int charCount[26];
for (int i = 0; i < 26; i++) {
*(charCount + i) = 0;
}
while (*s != '\0') {
char singleCharS = *s;
char singleCharT = *t;
s++;
t++;
int indexS = getIndex(singleCharS);
*(charCount + indexS) += 1;
int indexT = getIndex(singleCharT);
*(charCount + indexT) -= 1;
}
for (int i = 0; i < 26; i++) {
if (*(charCount + i) != 0) {
return false;
}
}
return true;
}
int main(int argc, const char * argv[]) {
const char *str1 = "Chaiy";
const char *str2 = "chiay";
cout << isAnagrams(str1, str2) << endl;
return 0;
}
| true |
9aa12d00cd3a02d417443d91315beeb8e708b482 | C++ | AlexHarker/FrameLib | /FrameLib_Objects/Filters/FrameLib_SVF.cpp | UTF-8 | 887 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive |
#include "FrameLib_SVF.h"
using namespace FrameLib_Filters;
constexpr SVF::Description SVF::sDescription;
constexpr SVF::ParamType SVF::sParameters;
constexpr SVF::ModeType SVF::sModes;
// Filter Implementation
void SVF::operator()(double x)
{
// Compute all modes
hp = (x - (2.0 * r * s1) - (g * s1) - s2) / (1.0 + (2.0 * r * g) + (g * g));
bp = g * hp + s1;
lp = g * bp + s2;
// Update state
s1 = g * hp + bp;
s2 = g * bp + lp;
}
double SVF::hpf(double x)
{
return hp;
}
double SVF::bpf(double x)
{
return bp;
}
double SVF::lpf(double x)
{
return lp;
}
void SVF::reset()
{
s1 = 0.0;
s2 = 0.0;
lp = 0.0;
bp = 0.0;
hp = 0.0;
}
void SVF::updateCoefficients(double freq, double reson, double samplingRate)
{
g = tan(freq * pi() / samplingRate);
r = std::min(std::max(1.0 - reson, 0.005), 1.0);
}
| true |
35ecede4ad5773a787df1028562cb30d6ad99181 | C++ | Relics/Leetcode | /Work_leetcode/Contests/week 14/Sliding Window Median_Stomach_ache.cpp | UTF-8 | 1,686 | 2.6875 | 3 | [] | no_license | /*
* created by Stomach_ache
* Jan. 1, 2017
* runs in 118ms
*/
class Solution {
public:
typedef multiset<int>::iterator Iter;
Iter prev(Iter x) {
return -- x;
}
vector<double> medianSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();
assert(n >= k);
vector<int> tmp(begin(nums), begin(nums) + k);
sort(begin(tmp), begin(tmp) + k);
multiset<int> small, big;
for (int i = 0; i < k / 2; ++ i) {
small.insert(tmp[i]);
}
for (int i = k / 2; i < k; ++ i) {
big.insert(tmp[i]);
}
vector<double> ans;
int i = k;
do {
if (k & 1) {
ans.emplace_back(*begin(big));
} else {
ans.emplace_back((*begin(big)) * 0.5 + (*small.rbegin()) * 0.5);
}
if (i == n) break;
bool flag = false;
if (small.find(nums[i - k]) != end(small)) {
flag = true;
small.erase(small.find(nums[i - k]));
} else {
big.erase(big.find(nums[i - k]));
}
if (flag) {
small.insert(nums[i]);
} else {
big.insert(nums[i]);
}
if (k > 1 && *small.rbegin() > (*begin(big))) {
small.insert(*begin(big));
big.erase(begin(big));
big.insert(*small.rbegin());
small.erase(prev(small.end()));
}
++ i;
} while (i <= n);
return ans;
}
}; | true |
ed4b1f606043eb7187d467e53ddc5945f496c76b | C++ | nimish-dev/DSA-with-cpp | /linked list/sparse_polynomial_addition.cpp | UTF-8 | 5,464 | 4.1875 | 4 | [] | no_license | //Program to implement polynomial using linked list
#include<iostream>
using namespace std;
//Node class
//It will contain three slots named coefficient,exponent and the next node pointer
class node
{
public:
int coeff;
int exp;
node* next;
};
//Poly class
//To declare the polynomial class with it's head node pointer as private entity
class poly
{
private:
node* head;
public:
poly(){head=NULL;} //Constructor for the poly class
void create(); //Create function for creation of the list
int value(); //Value function to evaluate the polynomial with some base value
void add(poly* p1,poly* p2,poly* p3);
~poly(){}
};
int power(int x,int y); //Power function to calculate the exponentiation of the variable
node* newnode(int x,int y); //Function to create a newnode with some coefficient and exponent value
//Create function block
//Here we create the linked list which will contain the coefficient,exponent and the next node pointer
void poly::create()
{
int n;
cout<<"Enter the number of terms in the polynomial : ";
cin>>n;
cout<<"Start entering "<<n<<" terms as coeff and exponent :\n";
head=new node;
int x,y;
cin>>x>>y;
head->coeff=x; //By default assignment of the head node
head->exp=y;
node* last;
head->next=NULL;
last=head; //Uppdate the last node pointer to point to the last node in the list
for(int i=1;i<n;i++) //Start loop for other node's data except the head node
{
cin>>x>>y;
node* t=newnode(x,y); //Create the new node and store it's location in a temporary node pointer variable
last->next=t; //Update the last node next node pointer value
last=t; //Update the last node value
}
}
//Newnode function block
//It will take two argument as coefficient and exponent
//And insert then into a newly craeted node
//And return the node address back to the calling function
node* newnode(int x,int y)
{
node* t=new node;
t->coeff=x;
t->exp=y;
t->next=NULL;
return t;
}
//Value function to evaluate the polynomial
int poly::value()
{
int x;
cout<<"Enter the base value for polynomial : ";
cin>>x;
node* p=head; //Start the tracker from the head node and continue the calculations till it reaches the last node
int res=0;
while(p!=NULL)
{
int pow=power(x,p->exp); //Get the result of the exponential function
pow=pow*p->coeff;
res+=pow; //Then update the result value
p=p->next; //Update the next node pointer value
}
return res; //return the result to the calling function
}
//Power function block
//It calculates the exponential expression
//It takes two argument
//One base and other exponent
int power(int x,int y)
{
int prod=1;
for(int i=0;i<y;i++)
{
prod*=x;
}
return prod;
}
//Add function block
//To add two polynomials
//There will be two seperate lists representing the coefficients and exponents for each polynomial
//Whenever the exponents matches the coeffiecients are added and a newnode is created then that node is insertde to the end of the new list
//Else whichever exponent is greter that node is copied to the new list
void poly::add(poly* p1,poly* p2,poly *p3)
{
node *p=p1->head;
node *q=p2->head;
node *last;
while((p!=NULL)&&(q!=NULL))
{
if(p->exp==q->exp)
{
node* t=newnode(q->coeff+p->coeff,q->exp);
if(p3->head==NULL)
{
p3->head=t;
last=t;
}
else
{
last->next=t;
last=t;
}
p=p->next;
q=q->next;
}
else if(p->exp>q->exp)
{
node* t=newnode(p->coeff,p->exp);
if(p3->head==NULL)
{
p3->head=t;
last=t;
}
else
{
last->next=t;
last=t;
}
p=p->next;
}
else if(p->exp<q->exp)
{
node* t=newnode(q->coeff,q->exp);
if(p3->head==NULL)
{
p3->head=t;
last=t;
}
else
{
last->next=t;
last=t;
}
q=q->next;
}
while(p!=NULL)
{
node* t=newnode(p->coeff,p->exp);
if(p3->head==NULL)
{
p3->head=t;
last=t;
}
else
{
last->next=t;
last=t;
}
p=p->next;
}
while(q!=NULL)
{
node* t=newnode(q->coeff,q->exp);
if(p3->head==NULL)
{
p3->head=t;
last=t;
}
else
{
last->next=t;
last=t;
}
q=q->next;
}
}
}
//main function block
int main()
{
poly p1; //An object of polynomial class is created
p1.create(); //Then the values are assigned to the list and the list is updated for the newly created object
poly p2;
p2.create();
poly p3;
p3.add(&p1,&p2,&p3);
int res=p3.value();
cout<<"The value of the resultant polynomial is "<<res<<"\n";
} | true |
4160fff7af42e8c51eef99e4089f466b042ef1f3 | C++ | Altantur/algorithms | /basics/problem-35/code_cpp/max_diff_of_array_solution1.cpp | UTF-8 | 952 | 3.59375 | 4 | [
"MIT"
] | permissive | /**
@file max_diff_of_array_solution1.cpp
@author Altantur Bayarsaikhan (altantur)
@purpose Find 2 integers that have biggest difference
@version 1.0 08/11/17
*/
#include <iostream>
#include <fstream>
using namespace std;
int main(){
// ifstream test_file;
// Read from test files
// test_file.open ("../test/test1.txt");
// test_file.close();
// Getting user input
int n, maxi = -1, mini = -1;
cin >> n;
int a[n];
for (int i = 0; i < n; i ++)
cin >> a[i];
// Iniatate with first value
if (n > 0){
maxi = 0;
mini = 0;
}
// To find max and min value
for (int i = 0; i < n; i ++){
if (a[maxi] < a[i])
maxi = i;
else if (a[mini] > a[i])
mini = i;
}
cout << "Max(value, index) : " << a[maxi] << ", " << maxi << endl;
cout << "Min(value, index) : " << a[mini] << ", " << mini << endl;
return 0;
}
| true |
d1f2a89d868a399be55ba54e7135bbcdf0c4947b | C++ | McStasMcXtrace/NJOY21 | /src/njoy21/input/PURR/Card3/Temp.hpp | UTF-8 | 803 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | struct Temp {
using Value_t = std::vector< Quantity< Kelvin > >;
static std::string name(){ return "temp"; }
static std::string description() {
return
"The temp argument is a list of temperatures (in Kelvin) to which the\n"
"the unresolved resonances are produced.";
}
static bool verify( const Value_t& temps,
const Argument< Card2::Ntemp > & ntemp ){
auto found = std::find_if( temps.begin(), temps.end(),
[](auto& E){ return E < 0.0*kelvin; });
if ( found != temps.end() ){
Log::warning( "Negative temperature ({}) found at index {}",
*found, std::distance(temps.begin(), found));
return false;
} else {
return ( long(temps.size()) == ntemp.value );
}
}
};
| true |
e62d281e04078dabc659ba5dc4ae2bf4c8451d48 | C++ | renlf/LeetCode | /Maximum_Product_Subarray.cpp | UTF-8 | 478 | 2.78125 | 3 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
int maxProduct(vector<int>& nums) {
vector<vector<int>> dp(nums.size(), vector<int>(2));
dp[0][0] = nums[0];
dp[0][1] = nums[0];
int max_val = nums[0];
for (int i = 1; i < nums.size(); i++)
{
dp[i][0] = max(nums[i], max(nums[i] * dp[i - 1][0], nums[i] * dp[i - 1][1]));
dp[i][1] = min(nums[i], min(nums[i] * dp[i - 1][0], nums[i] * dp[i - 1][1]));
max_val = max(max_val, dp[i][0]);
}
return max_val;
}
| true |
f5dd07f930ecee01e3dac9de5270861644b68c41 | C++ | kimdg1105/Algorithm_Solving | /BOJ/1913.cpp | UTF-8 | 1,258 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
#define MAX 101
using namespace std;
int arr[1001][1001];
void snail(int n) {
int y = n / 2 + 1;
int x = n / 2 + 1;
arr[y][x] = 1;
int stamp = 2;
int move = 0;
while ( 1 ) {
move++;
for (int i = 0; i < move; i++) {
y = y - 1;
arr[y][x] = stamp;
stamp++;
if (stamp > n * n) break;
}
if (stamp > n * n) break;
for (int i = 0; i < move; i++) {
x = x + 1;
arr[y][x] = stamp;
stamp++;
}
move++;
for (int i = 0; i < move; i++) {
y = y + 1;
arr[y][x] = stamp;
stamp++;
}
for (int i = 0; i < move; i++) {
x = x - 1;
arr[y][x] = stamp;
stamp++;
}
}
}
void printSnailAndFindNumPoint(int find, int size)
{
int findNumPointY, findNumPointX;
for (int i = 1; i <= size; i++)
{
for (int j = 1; j <= size; j++)
{
cout << arr[i][j] << " ";
if (arr[i][j] == find)
{
findNumPointY = i;
findNumPointX = j;
}
}
cout << "\n";
}
cout << findNumPointY << " " << findNumPointX << "\n";
}
int main()
{
int N;
cin >> N;
int find;
cin >> find;
snail(N);
printSnailAndFindNumPoint(find, N);
} | true |
0a4aa2ebafe6901f9a73b1db1bf0280536fd68df | C++ | Lafayette-FSAE/PacManFirmware | /PacMan_CANOpen/Core1.cpp | UTF-8 | 33,386 | 2.75 | 3 | [
"MIT",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | /**
* @file Core1.cpp
* @author Clement Hathaway (cwbh10@gmail.com)
* @brief The Code running on Core1 controlling much of the data processing
* @version 1.0
* @date 2020-04-13
*
* @copyright Copyright (c) 2020
*
*/
#include "Core1.h"
uint8_t cellFaults[16];
/**
* @brief A Callback triggered by the warning timer
* Locks Object Dictionary
* Updates the Object Dictionary with the cellFaults warnings that have been set prior to their appropriate values
* Unlocks Object Dictionary
* @param pxTimer parameter used in the callback in the timers - given by ESP IDF guidelines
*/
void warningCallBack(TimerHandle_t pxTimer){
CO_LOCK_OD();
//Serial.println("15 seconds has past setting warnings!");
for(int i = 0; i < 16; i++){
OD_warning[i] = cellFaults[i];
}
CO_UNLOCK_OD();
}
/**
* @brief A Callback triggered by the safetyloop timer
* Opens Safety loop
* Locks Object Dictionary
* Updates the Object Dictionary with the cellFaults faults that have been set prior to their appropriate values
* Unlocks Object Dictionary+
* @param pxTimer parameter used in the callback in the timers - given by ESP IDF guideline
*/
void openSafetyLoopCallBack(TimerHandle_t pxTimer){
digitalWrite(PIN_SLOOP_EN, LOW);
OD_SLOOP_Relay = false;
Serial.println("SAFETY LOOP OPENED!");
CO_LOCK_OD();
for(int i = 0; i < 16; i++){
OD_fault[i] = cellFaults[i];
}
CO_UNLOCK_OD();
}
// CONSTRUCTOR
/**
* @brief Constructs a new Core 1::Core 1 object
* Created interrupt Semaphores
* Starts I2C driver and joins the bus on specified pins in PacMan.h
* Creates all the warning and fault timers
* @param CO The CANopen object which is passed in via the toplevel PacMan file
*/
Core1::Core1(CO_t *CO) {
// Interrupt Semaphores
if (DEBUG) printf("Core 1: Initialising");
I2C_InterrupterSemaphore = xSemaphoreCreateBinary();
chargeDetectSemaphore = xSemaphoreCreateBinary();
if (DEBUG) printf("Core 1: I2C and Charge Detect Interrupt Semaphores Created");
Wire.begin(PIN_SDA, PIN_SCL); // Join the I2C bus (address optional for master) -- CHANGE THIS FOR DISPLAY
if (DEBUG) printf("Core 1: Joined I2C Bus");
currentSensor.init(LTC4151::L, LTC4151::L); // Init the LTC4151 responsible for PacMan power consumption and TSV consumption
consumedMAH = 0; // Should be made into OB stuff so we can save this upon loss of power or reset -- Complex issue
totalMAH = 60000;
// Create safetyloop timers
underVoltageTimer = xTimerCreate(
/* Just a text name, not used by the RTOS kernel. */
"underVoltageTimer",
/* The timer period in ticks. From Time To Trigger *1000 for ms */
pdMS_TO_TICKS(TTT*1000),
/* The timer is a one-shot timer. */
pdFALSE,
/* The id is not used by the callback so can take any
value. */
0,
/* The callback function that switches the LCD back-light
off. */
openSafetyLoopCallBack);
underVoltageWarningTimer = xTimerCreate("underVoltageWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
overVoltageTimer = xTimerCreate("overVoltageTimer", pdMS_TO_TICKS(TTT*1000), pdFALSE, 0, openSafetyLoopCallBack);
overVoltageWarningTimer = xTimerCreate("overVoltageWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
overTemperatureTimer = xTimerCreate("overTemperatureTimer", pdMS_TO_TICKS(TTT*1000), pdFALSE, 0, openSafetyLoopCallBack);
overTemperatureWarningTimer = xTimerCreate("overTemperatureWarningTimer", pdMS_TO_TICKS(TTT*1000/6), pdFALSE, 0, warningCallBack);
if (DEBUG) printf("Core 1: Created Software Safety Timers!");
}
// Quick sorts out struct of addressVoltage based off of the .addressMinusVoltage property
/**
* @brief Sorts an array of AddressVoltage structs by ascending voltage reference level
* Uses quicksort as the main sorting method
* @param addressVoltages The array of structs of type addressVoltage
* @param first Part of the recursion in Quicksort
* @param last Part of the recursion in Quicksort
*/
void Core1::addressVoltageQuickSort(addressVoltage* addressVoltages, int first, int last) {
int i, j, pivot;
uint16_t tempVoltage;
uint8_t tempAddress;
if (first < last) {
pivot = first;
i = first;
j = last;
while (i < j) {
while (addressVoltages[i].addressMinusVoltage <= addressVoltages[pivot].addressMinusVoltage && i < last)
i++;
while (addressVoltages[j].addressMinusVoltage > addressVoltages[pivot].addressMinusVoltage)
j--;
if (i < j) {
tempAddress = addressVoltages[i].address;
tempVoltage = addressVoltages[i].addressMinusVoltage;
addressVoltages[i].address = addressVoltages[j].address;
addressVoltages[i].addressMinusVoltage = addressVoltages[j].addressMinusVoltage;
addressVoltages[j].address = tempAddress;
addressVoltages[j].addressMinusVoltage = tempVoltage;
}
}
tempAddress = addressVoltages[pivot].address;
tempVoltage = addressVoltages[pivot].addressMinusVoltage;
addressVoltages[pivot].address = addressVoltages[j].address;
addressVoltages[pivot].addressMinusVoltage = addressVoltages[j].addressMinusVoltage;
addressVoltages[j].address = tempAddress;
addressVoltages[j].addressMinusVoltage = tempVoltage;
addressVoltageQuickSort(addressVoltages, first, j - 1);
addressVoltageQuickSort(addressVoltages, j + 1, last);
}
}
bool Core1::addressVoltageSorter(addressVoltage const lhs, addressVoltage const rhs) {
return (lhs.addressMinusVoltage < rhs.addressMinusVoltage);
}
// Discovery I2C devices, excluding I2C devices on PacMan
/**
* @brief Discover the CellMen that are connected to the I2C bus
* Scans for devices between all available I2C addresses (1-127)
* Excludes known non-cellman devices defined in PacMan.h
* @return uint8_t number of CellMen found
*/
uint8_t Core1::discoverCellMen() {
uint8_t cellMenCount = 0;
// Since we are using a set array size, let's initialise all values in the array to 0
for (int i = 0; i < 16; i++) {
addresses[i] = 0x00;
}
// Start the scan for I2C devices between 1 and 127
for (int address = 1; address < 127; address++ )
{
// The I2C scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
byte error = Wire.endTransmission();
if (error == 0) {
// Exclude PacMan I2C devices
if (address != I2C_ADDR_MCP9804
&& address != I2C_ADDR_MCP23008
&& address != I2C_ADDR_BQ32002
&& address != I2C_ADDR_LTC4151
&& address != I2C_ADDR_LTC4151_GLOB)
{
Serial.print("CellMan I2C device found at address 0x");
if (address < 16) Serial.print("0");
Serial.print(address, HEX);
Serial.println(" !");
// Add the new address to our address array and increment the number we have found
addresses[cellMenCount] = address;
cellMenCount++;
}
}
else if (error == 4) {
Serial.print("Unknown error at address 0x");
if (address < 16)
Serial.print("0");
Serial.print(address, HEX);
Serial.println(" skipping...");
}
}
return cellMenCount;
}
// Request byte array from specified CellMan I2C address, using index and preCollect we know when to check for I2C faults
/**
* @brief Requests data from an I2C slave
* Requests data from I2C slaves, used for collecting data from CellMen
* Can be used before we have information about what CellMan is in what position during precollection
* @param address The address of the I2C Device/CellMan
* @param index The index for where the data will be stored - Not relevant in precollection mode
* @param preCollect A boolean to decide if the method is collecting data in the beginning for processing or just gathering new data
* @return unsigned* char returns data array sent from the I2C slave
*/
unsigned char* Core1::requestDataFromSlave(unsigned char address, uint8_t index, bool preCollect) {
uint8_t physicalODAddress = physicalLocationFromSortedArray(index);
if(!preCollect) toggleCellManLED(address, true);
Wire.requestFrom((int) address, REQUEST_LENGTH); // 24 is the max data length expected in bytes
if (DEBUG) {
Serial.print("Requesting data from CellMan on Address: ");
Serial.println(address);
}
if (Wire.available()) {
if (DEBUG) Serial.println("Wire Available!");
if(cellFaults[physicalODAddress] == 9 && !preCollect){
if(DEBUG) Serial.println("CellMan I2C Re-established!");
cellFaults[physicalODAddress] = 0; // If the Cellman comes back online, set the fault back to 0
}
for (int i = 0; i < REQUEST_LENGTH; i++) {
*(cellDs + i) = Wire.read(); // Append the read character (byte) to our cellData array
if (DEBUG) {
Serial.println(cellDs[i], HEX); // Print the character (byte) in HEX
Serial.println(cellDs[i], DEC); // Print the character (byte) in DEC
}
}
}else{
if(!preCollect && cellFaults[physicalODAddress] != 9){
if(DEBUG) Serial.println("Got a fault!");
cellFaults[physicalODAddress] = 9;
}
}
if(!preCollect) toggleCellManLED(address, false);
// Only update the faults if its 0 or 9, otherwise it negates the timer's purpose - Gets called a lot, maybe we can reduce the OD usage here sometime
if(!preCollect){
if(cellFaults[physicalODAddress] == 9 || cellFaults[physicalODAddress] == 0){
CO_LOCK_OD();
OD_warning[physicalODAddress] = cellFaults[physicalODAddress];
CO_UNLOCK_OD();
}
}
return cellDs;
}
// Process the celldata into our private arrays to be stored into the OD later
/**
* @brief Process the collected cellData array from the CellMan into its respective arrays in the class
* Since we get data from each CellMan at a time, but in the Object Dictionary it is stored by Data and then CellMan
* We have to preprocess the data so it is ready to be inserted in the OD with minimal locking time
* @param cellData Pass in the CellData array of bytes obtained from requestDataFromSlave
* @param cellPhysicalLocation Pass in the physical location of the cell so it matches in the array, e.g. physical location 8 is 7 in the array
*/
void Core1::processCellData(unsigned char* cellData, uint8_t cellPhysicalLocation) {
cellPositions[cellPhysicalLocation] = cellPhysicalLocation;
cellVoltages[cellPhysicalLocation] = (uint16_t)((cellData[2] << 8) + cellData[1]); // Shift MSBs over 8 bits, then add the LSBs to the first 8 bits and cast as a uint16_t
cellTemperatures[cellPhysicalLocation] = (uint16_t)((cellData[4] << 8) + cellData[3]);
minusTerminalVoltages[cellPhysicalLocation] = (uint16_t)((cellData[6] << 8) + cellData[5]);
cellBalanceCurrents[cellPhysicalLocation] = (uint16_t)((cellData[8] << 8) + cellData[7]);
// If we are in I2C Debug Mode
if (DEBUG) {
LEDStatuses[cellPhysicalLocation] = (bool)cellData[9];
balanceStatuses[cellPhysicalLocation] = (bool)cellData[10];
balanceDutyCycles[cellPhysicalLocation] = (uint8_t)cellData[10];
balanceFrequencies[cellPhysicalLocation] = (uint16_t)((cellData[13] << 8) + cellData[12]);
temperatureSlopes[cellPhysicalLocation] = (uint16_t)((cellData[15] << 8) + cellData[14]);
temperatureOffsets[cellPhysicalLocation] = (uint16_t)((cellData[17] << 8) + cellData[16]);
balanceCurrentSlopes[cellPhysicalLocation] = (uint16_t)((cellData[19] << 8) + cellData[18]);
balanceVoltageSlopes[cellPhysicalLocation] = (uint16_t)((cellData[21] << 8) + cellData[20]);
}
}
// Check the safety of our measurements, trigger warnings and safetyloop here
/**
* @brief Checks the safety our of CellMen Data in the Object Dictionary
* Looks through the number of CellMen we have detected and checks their values for
* Undervoltage, Overvoltage, Overtemperature, and I2C disconnect/error
* Starts/Stops appropriate warning and fault timers
* @param numberOfDiscoveredCellMen Integer with the number of detected CellMan so we don't check bad data
*/
void Core1::checkSafety(uint8_t numberOfDiscoveredCellMen){
tempUV = false;
tempOV = false;
tempOT = false;
int i;
int newIndex;
if (DEBUG) printf("Core 1: Checking Safety of Data in Object Dictionary");
CO_LOCK_OD();
if (DEBUG) printf("Core 1: Obtained Object Dictionary Lock");
for(i = 0; i < numberOfDiscoveredCellMen; i++){
// Because we have everything stored in physical locations in the array. e.g. 0 goes to Cell 0, 1 goes to Cell 8 in the array since they are in different segments
newIndex = physicalLocationFromSortedArray(i);
// Voltages are below the threshold trigger the tempValue to symbolise at least one voltage low
if(cellVoltages[newIndex] < OD_minCellVoltage[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 2;
tempUV = true;
} else if(cellVoltages[newIndex] > OD_maxCellVoltage[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 1;
tempOV = true;
} else if(cellTemperatures[newIndex] > OD_maxCellTemp[newIndex] && cellFaults[newIndex] != 9){
cellFaults[newIndex] = 3;
tempOT = true;
/* Reset values here so that we get rid of warnings and reset timers
Except if it is 9, since this means the cellman is not on I2C
and the data is old and therefore not trustworthy*/
}else if(cellFaults[newIndex] != 9){
cellFaults[newIndex] = 0;
OD_warning[newIndex] = 0;
OD_fault[newIndex] = 0;
}
}
CO_UNLOCK_OD();
if (DEBUG) printf("Core 1: Released Object Dictionary Lock");
// At least 1 cell was found below the voltage threshold - start undervoltage counter
if(tempUV){
if(xTimerIsTimerActive(underVoltageTimer) == pdFALSE){
if(xTimerStart(underVoltageTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start underVoltage Timer");
}else{
if(DEBUG) Serial.println("Core 1: underVoltage Timer as begun!");
}
}
if(xTimerIsTimerActive(underVoltageWarningTimer) == pdFALSE){
if(xTimerStart(underVoltageWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start underVoltage Warning Timer");
}else{
if(DEBUG) Serial.println("Core 1: underVoltage Warning Timer as begun!");
}
}
// No cells were found below the minimum voltage - stop and reset both counters
}else{
// Reset puts the timer in an active state - Resets time, but need to stop it to put it in a dormant state
xTimerReset(underVoltageTimer, 0);
xTimerReset(underVoltageWarningTimer, 0);
// Stop puts timer in a dormant state which lets us use xTimerIsTimerActive
xTimerStop(underVoltageTimer, 0);
xTimerStop(underVoltageWarningTimer, 0);
}
// At least 1 cell was found above the voltage threshold - start overvoltage counter
if(tempOV){
if(xTimerIsTimerActive(overVoltageTimer) == pdFALSE){ // Check to see if the timer has not been started yet, we don't want to start an already started timer
if(xTimerStart(overVoltageTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overVoltage Timer");
}else{
if(DEBUG) Serial.println("Core 1: overVoltage Timer as begun!");
}
if(xTimerIsTimerActive(overVoltageWarningTimer) == pdFALSE){ // Check to see if the timer has not been started yet, we don't want to start an already started timer
if(xTimerStart(overVoltageWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overVoltage Warning Timer");
}else{
if(DEBUG) Serial.println("Core 1: overVoltage Timer warning as begun!");
}
}
}
// No cells were found above the maximum voltage - stop and reset counters
}else{
xTimerReset(overVoltageTimer, 0);
xTimerReset(overVoltageWarningTimer, 0);
xTimerStop(overVoltageTimer, 0);
xTimerStop(overVoltageWarningTimer, 0);
}
// At least 1 cell temp was found above the temp threshold - start overTemperature counter
if(tempOT){
if(xTimerIsTimerActive(overTemperatureTimer) == pdFALSE){
if(xTimerStart(overTemperatureTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overTemperature Timer");
}else{
if(DEBUG) Serial.println("Core 1: overTemperature Timer as begun!");
}
}
if(xTimerIsTimerActive(overTemperatureWarningTimer) == pdFALSE){
if(xTimerStart(overTemperatureWarningTimer, 0) != pdPASS ){
/* The timer could not be set into the Active state. */
if(DEBUG) Serial.println("Core 1: Could not start overTemperature Warning Timer");
}else{
if (DEBUG) Serial.println("Core 1: overTemperature Timer Warning as begun!");
}
}
// No cell temps were found above the maximum temp - stop and reset counter
}else{
xTimerReset(overTemperatureTimer, 0);
xTimerReset(overTemperatureWarningTimer, 0);
xTimerStop(overTemperatureTimer, 0);
xTimerStop(overTemperatureWarningTimer, 0);
}
}
// Maps the arrayIndex to a physical cell location in the packs (since we can't tell between segments right now) by saying the second instance of a same voltage potential cell is in the other segment
/**
* @brief Maps an arrayIndex into the physical Cell Location in the Packs
* This method is using a work around since the PacMan hardware this firmware was developed on has a flaw
* We cannot differentiate between segments since they have their own grounds.
* A PacMan board revision should have been made to fix this but this method randomises in which seg a cell gets placed
* This way you have a 50% chance of knowing what cell the data is about by looking in the Packs, this is better than otherwise
* This function will need to be rewritten or swapped for something else once segment detection works
* Segment detection will eventually be done by reseting a known segment and performing a CellMen discovery
* @param arrayIndex Integer of the array's Index (not physical location!)
* @return uint8_t Returns an integer of the physical location which can be used as an index for physically indexed arrays (e.g OD)
*/
uint8_t Core1::physicalLocationFromSortedArray(uint8_t arrayIndex) {
uint8_t physicalAddress;
if (arrayIndex % 2 == 0) { // If Even
physicalAddress = arrayIndex / 2;
} else { // If Odd
physicalAddress = ((arrayIndex - 1) / 2) + 8;
}
// return physicalAddress;
return arrayIndex;
}
// Simple voltage-based SOC - Very inaccurate
/**
* @brief Calculates a simple Voltage based State of Charge
* This shouldn't be used in production and should be replaced
* A simple EKF based model would be best here
* Columb counting is the easier and better soltion than voltage but worse than EKF models
*/
void Core1::calculateTotalPackSOC() {
int SOCTotal = 0;
for (int index = 0; index < 16; index++) {
//SOCTotal += privateCells[index].SOC; // Sum up all of our SOCs from all the cells to get an average for the 16 cells in a pack
}
packSOC = (float)(SOCTotal / 16); // Return the average SOC from the cells
}
void Core1::toggleCellManLED(unsigned char address, bool state){
// If on
if(state){
Wire.beginTransmission(address);
Wire.write(0x23); // 0x23 is the LED register
Wire.write(0x00); // MSB
Wire.write(0x01); // LSB
Wire.endTransmission();
}else{ //If off
Wire.beginTransmission(address);
Wire.write(0x23); // 0x23 is the LED register
Wire.write(0x00); // MSB
Wire.write(0x00); // LSB
Wire.endTransmission();
}
}
// Toggle LEDs on CellMen in segment position order to indicate that they are properly connected and communicating
// addressVoltages should be sorted at this point
// Will need to modify when the segments are distinguishable so that the order is correct
/**
* @brief Flashes CellMen LEDs in order of detection
* Follows the order of flashing each CellMan and then all of them at once
*/
void Core1::indicateCellMen(){
if(DEBUG){
Serial.print("Flashing CellMen LEDs at time ");
Serial.println(millis());
}
// Light up each LED incrementally every 250ms
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, true);
delay(250);
}
// Blink the LEDs off and on 4 times
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, false);
}
delay(250);
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, true);
}
delay(250);
}
// Turn each LED off
for (int i = 0; i < numberOfDiscoveredCellMen; i++)
{
toggleCellManLED(addressVoltages[i].address, false);
}
if(DEBUG){
Serial.print("Done flashing CellMen LEDs at time ");
Serial.println(millis());
}
}
/**
* @brief Updates the Object Dictionary with udpated local CellMan data that was collected
* Goes through the detected CellMen and collects, processes, and checks safety of CellMen Data
* Locks the Object Dictionary
* Updates all of the data from the warnings, faults, and measurements into the OD
* Unlocks the OD
*/
void Core1::updateCellMenData(){
//Collect data from all the CellMen & Update Object Dictionary Interrupt
if (DEBUG) printf("Core 1: Attempting to take I2C Interrupt Semaphore");
if (xSemaphoreTake(I2C_InterrupterSemaphore, 0) == pdTRUE) {
if (DEBUG) printf("Core 1: Took I2C Interrupt Semaphore");
// Update CellMan Code
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
if (DEBUG) printf("Core 1: Requesting Data From CellMan");
unsigned char* celldata = requestDataFromSlave(addressVoltages[i].address, i, false);
if (DEBUG) printf("Core 1: Processing Collected Data");
processCellData(celldata, physicalLocationFromSortedArray(i)); // Process data retrieved from each cellman and is inerted based off of physicalAddress
if (DEBUG) printf("Core 1: Checking Safety of Collected Data");
checkSafety(numberOfDiscoveredCellMen);
}
if (DEBUG) printf("Core 1: Finishing Collecting CellMen Data");
// Update the Object Dictionary Here
if (DEBUG) printf("Core 1: Updating Object Dictionary");
CO_LOCK_OD();
if (DEBUG) printf("Core 1: Obtained Object Dictionary Lock");
// index i here will go through the array, but in this array the physical stuff is already set - I hate how confusing the indexes are depending on where you are in the code
for (int i = 0; i < 16; i++) {
// If this cell is disconnected, set all its useful data to 0 prior to changing the O
if(minusTerminalVoltages[i] != 0) // TODO: Examine this, the first cells should be at zero -- Removing this causes shit values so gotta fix this
{
if(cellFaults[i] == 9)
{
cellVoltages[i] = 0;
cellTemperatures[i] = 0;
cellBalancingEnabled[i] = 0;
cellBalanceCurrents[i] = 0;
}
OD_cellPosition[i] = cellPositions[i];
OD_cellVoltage[i] = cellVoltages[i];
OD_cellTemperature[i] = cellTemperatures[i];
OD_minusTerminalVoltage[i] = minusTerminalVoltages[i];
OD_cellBalancingEnabled[i] = cellBalancingEnabled[i];
OD_cellBalancingCurrent[i] = cellBalanceCurrents[i];
maxCellVoltage[i] = OD_maxCellVoltage[i];
maxCellTemp[i] = OD_maxCellTemp[i];
}
}
CO_UNLOCK_OD();
if (DEBUG) printf("Core 1: Updated Object Dictionary and Released OD Lock");
}
}
bool Core1::handleChargingSafety(){
bool charge = true;
int newIndex; // Gets us the actual physical location which is how the array in defined
// Check all cells are within spec -- This might cause issue for balancing if 1 cell becomes too high it'll turn off the relay, voltage will drop, and we will have relay oscillations
// UPDATE: ^ Above statement fixed by haiving the currentlyCharging variable which gives us hysteresis until the plug is taken out and put back in
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
newIndex = physicalLocationFromSortedArray(i);
if(cellVoltages[newIndex] > maxCellVoltage[newIndex] || cellTemperatures[newIndex] > maxCellTemp[newIndex]){
charge = false;
}
}
return charge;
}
bool Core1::handleChargingInterrupt(bool chargingState){
// Charge detect interrupt
if (xSemaphoreTake(chargeDetectSemaphore, 0) == pdTRUE) {
if(DEBUG) Serial.println("Detected Charging thing!");
// TODO: Prevent inverted state from occuring when lowering voltage when connector is in and then unplugging
if(chargingState == true){
if(digitalRead(PIN_CHRG_EN) == LOW && currentlyCharging == false){ // It's not already on, e.g. we've plugged the cable in
digitalWrite(PIN_CHRG_EN, HIGH);
OD_chargingEnabled = true;
currentlyCharging = true;
}else{ // The state changed because we removed the connector
digitalWrite(PIN_CHRG_EN, LOW);
OD_chargingEnabled = false;
currentlyCharging = false;
}
}
}
}
/**
* @brief Handles the charging interrupt and relays
* Checks to make sure all cells are within acceptable voltage ranges
* Trys to take the interrupt semaphore for the charge connector
* Adjusts the state of the relay based on the safety and state of charge connector
* This provides some hysteresis until the connector is replugged in if a cell goes out of safety spec
* @bug Can get the state inverted in certain cases (Relay on when plug out, and vice-versa), some additional logic should be put in to fix this
*/
void Core1::handleCharging(){
// Reordered to seperate the functionality for more flexibility in the algorithm later in the road
bool charge = handleChargingSafety();
charge = handleChargingInterrupt(charge);
if(charge == false){
digitalWrite(PIN_CHRG_EN, LOW);
OD_chargingEnabled = false;
//currentlyCharging = false; -- Don't do this here, this gives us hysteresis without this and fixes bug that when we lower voltage and remove plug it turns on
}
}
// This code is relatively untested due to being unable to test currents at home, please don't think this code works properly but take it as a basis to work off of
void Core1::updateMAH(){
newMeasTime = micros();
int pacManCurrent = (int)(currentSensor.getLoadCurrent(0.82)*PacManDisConst*1000); // Parameter is the shunt resistor value in Ohms - Measuring power consumed by PacMan
int dischargeCurrent = (int)(currentSensor.getADCInVoltage()*DischargeConst);
consumedMAH += (pacManCurrent*((newMeasTime-oldMeasTime)/1000000) + (dischargeCurrent*(newMeasTime-oldMeasTime)/1000000));
oldMeasTime = newMeasTime;
}
// Start main loop for thread
/**
* @brief The main loop for Core 1 thread
* Initialises various variables
* Discovers CellMen
* Quick Sorts discovered CellMen into voltage ascending over
* Begins main loop of:
* Updating CellMen Data
* Handling Charging
* Short delay to avoid triggering the Watchdog built into the ESP due to overloading Core1
*/
void Core1::start() {
if (DEBUG) printf("Core 1: Starting");
///// Initial Functions
unsigned char* tempCellData;
/* We know this because in the PacMan.ino file we start
the ESP32 with charging false and this occurs before we start checking */
currentlyCharging = false;
oldMeasTime = 0;
DischargeConst = 1;
PacManDisConst = 1;
ChargeConst = 1;
// Not really needed to zero the array of structures but why not
for (int i = 0; i < 16; i++) {
addressVoltages[i].address = 0x00;
addressVoltages[i].addressMinusVoltage = 0;
cellPositions[i]=i;
minusTerminalVoltages[i]=0;
}
if (DEBUG) printf("Core 1: Initalised & Zeroed AddressVoltages Array");
// Get all CellMan Addresses - loop discovering until we get some devices to prevent crashing of the CPU
numberOfDiscoveredCellMen = 0;
if (DEBUG) printf("Core 1: Beginning Discovery of CellMen on I2C Bus");
while (numberOfDiscoveredCellMen == 0) {
if(DEBUG) Serial.println("In the while loop, looking for CellMen");
numberOfDiscoveredCellMen = discoverCellMen();
}
if (DEBUG) printf("Core 1: Finished Discoverying CellMen");
if (DEBUG) {
Serial.print("Core 1: The number of address found: ");
Serial.println(numberOfDiscoveredCellMen);
}
// Put together addressVoltages array by requesting data from each cellman
if (DEBUG) printf("Core 1: Collecting Initial Data from CellMen for Location Calculation");
for (int i = 0; i < numberOfDiscoveredCellMen; i++) {
tempCellData = requestDataFromSlave(addresses[i], i, true);
addressVoltages[i].address = addresses[i];
addressVoltages[i].addressMinusVoltage = (uint16_t)((tempCellData[6] << 8) + tempCellData[5]);
if(DEBUG){
Serial.print("Cell 1: Address minus voltage for address ");
Serial.print(addressVoltages[i].address);
Serial.print(": ");
Serial.println(addressVoltages[i].addressMinusVoltage);
}
}
if (DEBUG) printf("Core 1: Quicksorting the AddressVoltage Array");
// for (int i = 0; i < numberOfDiscoveredCellMen; i++)
// {
// Serial.print("Index ");
// Serial.print(i);
// Serial.print(": ");
// Serial.print(addressVoltages[i].address);
// Serial.print(", ");
// Serial.println(addressVoltages[i].addressMinusVoltage);
// }
// Sort the addressVoltages by ascending voltages - Wow this bug fix took FOREVER, forgot the -1 (haha jouny) after the numberOfDiscoveredCellMen oof
addressVoltageQuickSort(addressVoltages, 0, numberOfDiscoveredCellMen - 1);
// Serial.println("After quicksort:");
// for (int i = 0; i < numberOfDiscoveredCellMen; i++)
// {
// Serial.print("Index ");
// Serial.print(i);
// Serial.print(": ");
// Serial.print(addressVoltages[i].address);
// Serial.print(", ");
// Serial.println(addressVoltages[i].addressMinusVoltage);
// }
// Flash the LEDs on each CellMen in position order
if (DEBUG) printf("Core 1: Flashing CellMen in Detected Order");
indicateCellMen();
///// Main Loop
if (DEBUG) printf("Core 1: Entering Main Loop");
for (;;) {
// Interrupt based updating of CellMen data and OD
updateCellMenData();
// Interrupt based charging detect method
handleCharging();
// High Priority Main Loop Code Here -- If empty put a fucking delay you faff
delay(10);
}
}
| true |
b5bfe58e636475fbbd1b9d8a21933a1c4a1d1bb4 | C++ | PrshntS/PREP | /BINARY TREES/lca.cpp | UTF-8 | 1,319 | 2.890625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl "\n"
#define mx INT_MAX
#define mn INT_MIN
#define pb push_back
class Node
{
public:
int data;
Node* left;
Node* right;
Node(int n)
{
data = n;
Node* left = NULL;
Node* right = NULL;
}
};
Node* newn(int n)
{
Node* a = new Node(n);
return a;
}
bool lcau(Node* root, vector<int>& path, int k)
{
if (!root)
{
return false;
}
path.pb(root->data);
if (root->data == k)
{
return true;
}
if (((root->left) && lcau(root->left, path, k)) || ((root->right) && lcau(root->right, path, k)))
{
return true;
}
path.pop_back();
return false;
}
int lca(Node* root, int n1, int n2)
{
vector<int> path1, path2;
if (!lcau(root, path1, n1) || !lcau(root, path2, n2))
{
return -1;
}
int i = 0;
for (i = 0; i < path1.size() && i < path2.size(); i++)
{
if (path1[i] != path2[i])
{
break;
}
}
return path1[i - 1];
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
Node* root = newn(1);
root->left = newn(2);
root->right = newn(3);
root->left->left = newn(4);
root->left->right = newn(5);
root->right->left = newn(6);
root->right->right = newn(7);
cout << lca(root, 2, 3);
return 0;
} | true |
3d1f0fdb117f953d1535dd405f7755e76e364940 | C++ | Zandriy/NeHe_SDL | /src/Sample_12.cpp | UTF-8 | 5,460 | 2.515625 | 3 | [] | no_license | /*
* Sample_12.cpp
*
* Created on: Feb 28, 2013
* Author: Andrew Zhabura
*/
#include "Sample_12.h"
GLfloat Sample_12::m_boxcol[COL_QTY][COORD_QTY]= {
{1.0f,0.0f,0.0f},{1.0f,0.5f,0.0f},{1.0f,1.0f,0.0f},{0.0f,1.0f,0.0f},{0.0f,1.0f,1.0f}
};
GLfloat Sample_12::m_topcol[COL_QTY][COORD_QTY]= {
{.5f,0.0f,0.0f},{0.5f,0.25f,0.0f},{0.5f,0.5f,0.0f},{0.0f,0.5f,0.0f},{0.0f,0.5f,0.5f}
};
Sample_12::Sample_12()
: m_xrot(0.0f)
, m_yrot(0.0f)
, m_box(0)
, m_top(0)
, m_xloop(0)
, m_yloop(0)
{
m_image.loadBMP( "data/cube.bmp" );
glGenTextures(TEX_QTY, &m_texture[TEX_1]); // Create The Texture
}
Sample_12::~Sample_12()
{
delete [] m_texture;
}
void Sample_12::reshape(int width, int height)
{
// Height / width ration
GLfloat ratio;
// Protect against a divide by zero
if ( height == 0 )
height = 1;
ratio = ( GLfloat )width / ( GLfloat )height;
// Setup our viewport.
glViewport( 0, 0, ( GLsizei )width, ( GLsizei )height );
// change to the projection matrix and set our viewing volume.
glMatrixMode( GL_PROJECTION );
glLoadIdentity( );
// Set our perspective
gluPerspective( 45.0f, ratio, 0.1f, 100.0f );
// Make sure we're chaning the model view and not the projection
glMatrixMode( GL_MODELVIEW );
// Reset The View
glLoadIdentity( );
}
void Sample_12::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glBindTexture(GL_TEXTURE_2D, m_texture[TEX_1]);
for (m_yloop=1;m_yloop<6;m_yloop++)
{
for (m_xloop=0;m_xloop<m_yloop;m_xloop++)
{
glLoadIdentity(); // Reset The View
glTranslatef(1.4f+(float(m_xloop)*2.8f)-(float(m_yloop)*1.4f),((6.0f-float(m_yloop))*2.4f)-7.0f,-20.0f);
glRotatef(45.0f-(2.0f*m_yloop)+m_xrot,1.0f,0.0f,0.0f);
glRotatef(45.0f+m_yrot,0.0f,1.0f,0.0f);
glColor3fv(m_boxcol[m_yloop-1]);
glCallList(m_box);
glColor3fv(m_topcol[m_yloop-1]);
glCallList(m_top);
}
} // Keep Going
}
void Sample_12::initGL()
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
// set here server attributes (states)
glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable(GL_LIGHT0); // Quick And Dirty Lighting (Assumes Light0 Is Set Up)
glEnable(GL_LIGHTING); // Enable Lighting
glEnable(GL_COLOR_MATERIAL); // Enable Material Coloring
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations
// Typical Texture Generation Using Data From The Bitmap
glBindTexture(GL_TEXTURE_2D, m_texture[TEX_1]);
// Generate The Texture
glTexImage2D(GL_TEXTURE_2D, 0, 3, m_image.sizeY(), m_image.sizeY(), 0, GL_RGB, GL_UNSIGNED_BYTE, m_image.data() );
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); // Linear Filtering
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering
glPushClientAttrib(GL_ALL_CLIENT_ATTRIB_BITS);
// set here client attributes (states)
m_box=glGenLists(2); // Generate 2 Different Lists
BuildLists();
}
void Sample_12::restoreGL()
{
// restore server and client attributes (states)
glPopClientAttrib();
glPopAttrib();
}
// Build Cube Display Lists
GLvoid Sample_12::BuildLists()
{
glNewList(m_box,GL_COMPILE); // Start With The Box List
glBegin(GL_QUADS);
// Bottom Face
glNormal3f( 0.0f,-1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
// Front Face
glNormal3f( 0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glNormal3f( 0.0f, 0.0f,-1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Right face
glNormal3f( 1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
glEndList();
m_top=m_box+1; // Storage For "Top" Is "Box" Plus One
glNewList(m_top,GL_COMPILE); // Now The "Top" Display List
glBegin(GL_QUADS);
// Top Face
glNormal3f( 0.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glEnd();
glEndList();
}
| true |
b60d432dd05020edbff774005a39f53696e646b5 | C++ | SimiVoid/Student-Life-Simulator | /Student-Life-Simulator/src/Board.h | UTF-8 | 546 | 2.703125 | 3 | [] | no_license | #pragma once
#include "BoardField.h"
typedef std::vector<std::vector<BoardField>> BoardArray;
class Board {
const sf::Color& m_gridColor = sf::Color(41, 41, 41);;
sf::VertexArray m_boardGrid;
BoardArray m_fields;
uint16_t m_size;
void checkFieldPosition(const sf::Vector2i& position) const;
public:
explicit Board(const uint16_t& size);
~Board() = default;
[[nodiscard]] BoardField& getField(const sf::Vector2i& position);
[[nodiscard]] uint16_t getBoardSize() const;
void draw(sf::RenderWindow& window);
void clearFields();
};
| true |
5286f126d732959343ec2abfd674ab79fb10cae7 | C++ | tamasferencz12/c-feladatok | /16.k.8.cpp | UTF-8 | 545 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int main()
{
string nev, elt;
unsigned short n;
float atlag, maximum;
ifstream file1;
ofstream file2;
file1.open("tanulok.in");
file2.open("tanulok.out");
file1 >> n;
for (unsigned int i = 1; i <= n; i++)
{
file1 >> nev >> atlag;
if (atlag > maximum)
{
maximum = atlag;
elt = nev;
}
}
file2 << elt << " " << maximum;
file1.close();
file2.close();
return 0;
}
| true |
ac1a8892384ac04c53484976232683e9ea26cb6c | C++ | ailyanlu1/leetcode-4 | /C++/220_Contains Duplicate III.cpp | UTF-8 | 843 | 3.03125 | 3 | [] | no_license | class Solution {
public:
bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
if (nums.size() == 0)
return false;
vector<node> vt;
for (int i = 0; i < nums.size(); i++)
vt.push_back(node(nums[i], i));
sort(vt.begin(), vt.end());
for (int i = 0; i < vt.size(); i++) {
for (int j = i + 1; j < vt.size() && vt[j].x - vt[i].x <= t; j++) {
if (abs(vt[j].pos - vt[i].pos) <= k)
return true;
}
}
return false;
}
private:
struct node {
long long x;
int pos;
node(long long x, int p): x(x), pos(p) {}
bool operator < (const node &a) const {
if (x == a.x)
return pos < a.pos;
return x < a.x;
}
};
}; | true |
27514e9e7a9f7737752d729ee95a146d55292b7a | C++ | Rainboylvx/pcs | /luogu/1147/1.cpp | UTF-8 | 587 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<algorithm>
#include<set>
using namespace std;
const int maxn=2000000 + 5;
long long a[maxn];
int main()
{
long long n;
cin>>n;
for(int i=1;i<=n;i++) a[i]=a[i-1]+i;//前缀和
for(int i=1;i<=n;i++)
{
long long mid=a[i-1]+n;// 要找的那个数,显然比a[i-1] 大n
long long pos=lower_bound(a,a+n+1,mid)-a; // 找到第一个>=的位置
if(a[pos]-a[i-1]==n) //确实为n
{
if(i!=pos) //不止一个数
cout<<i<<" "<<pos<<endl;
}
}
return 0;
}
| true |
d434b6a63238e84efc00e48f2332eac61a1cfccd | C++ | mevid93/8mulator | /include/chip8.hpp | UTF-8 | 5,993 | 2.9375 | 3 | [] | no_license | #ifndef CHIP8_HPP
#define CHIP8_HPP
#include <string>
#include <irrKlang.h>
class Chip8
{
public:
static const int MEMORY_SIZE = 4096; // size of the memory area
static const char REGISTERS_SIZE = 16; // number of registers
static const char STACK_SIZE = 16; // number of supported stack levels
static const char KEYS_SIZE = 16; // number of keys
static const int PIXELS_SIZE = 64 * 32; // number of pixels
static const char FONTSET_SIZE = 80; // chip 8 font set size
bool drawFlag; // flag tells if the display needs to be updated or not
void initialize(); // initialize the chipset
void loadProgram(const std::string filename); // load program into the chipset memory
void emulateCycle(); // emulate one cycle
void setKey(const unsigned char key, const unsigned char state); // store key press state (press and release)
unsigned char *getPixelStates(); // return array of chars that represent pixel state (on/off)
~Chip8(); // free resources
private:
irrklang::ISoundEngine *soundEngine; // sound engine for audio output
irrklang::ISoundSource *soundSource; // sound effect source
unsigned char memory[MEMORY_SIZE]; // memory of the chipset
unsigned short opcode; // current operation code
unsigned char registers[REGISTERS_SIZE]; // chipset registers
unsigned short ir; // index register
unsigned short pc; // program counter
unsigned char gfx[PIXELS_SIZE]; // pixel states (on/off)
unsigned char delayTimer; // 60 Hz delay timer
unsigned char soundTimer; // 60 Hz timer for sound
unsigned short stack[STACK_SIZE]; // 16-level stack
unsigned short sp; // stack pointer
unsigned char keys[KEYS_SIZE]; // states of the keypad keys
unsigned char fontset[FONTSET_SIZE] = // font set for chip 8 --> each character is 4*5 pixels
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
void fetchOpcode(); // get next opcode
void decodeAndExecuteOpcode(); // decode and execute the opcode
void updateTimers(); // update delay timer and sound timer
void executeOpcode00E0(); // clear the screen
void executeOpcode00EE(); // return from subroutine
void executeOpcode0NNN(); // call machine code routine at address NNN
void executeOpcode1NNN(); // jump to address NNN
void executeOpcode2NNN(); // call subroutine at address NNN
void executeOpcode3XNN(); // skip next instruction if registers[X] == NN
void executeOpcode4XNN(); // skip next instruction if registers[X] != NN
void executeOpcode5XY0(); // skip next instruction if registers[X] == registers[Y]
void executeOpcode6XNN(); // registers[X] = NN
void executeOpcode7XNN(); // registers[X] += NN
void executeOpcode8XY0(); // registers[X] = registers[Y]
void executeOpcode8XY1(); // registers[X] = registers[X] | registers[Y]
void executeOpcode8XY2(); // registers[X] = registers[X] & registers[Y]
void executeOpcode8XY3(); // registers[X] = registers[X] ^ registers[Y]
void executeOpcode8XY4(); // registers[X] += registers[Y]; registers[F] = (1 or 0)
void executeOpcode8XY5(); // registers[X] -= registers[Y]; registers[F] = (1 or 0)
void executeOpcode8XY6(); // store least significat bit to registers[F] and shift registers[X] >> 1
void executeOpcode8XY7(); // registers[X] = registers[Y] - registers[X]; registers[F] = (0 or 1)
void executeOpcode8XYE(); // store most significant bit to registers[F] and shift registers[X] << 1
void executeOpcode9XY0(); // skip next instruction if registers[X] != registers[Y]
void executeOpcodeANNN(); // ir = NNN
void executeOpcodeBNNN(); // Jumps to address NNN + registers[0]
void executeOpcodeCXNN(); // register[X] = rand() & NN
void executeOpcodeDXYN(); // Draws a sprite at coordinate (registesr[X], registers[Y]) that has a height of N+1 pixels
void executeOpcodeEX9E(); // Skips the next instruction if the key stored in registers[X] is pressed
void executeOpcodeEXA1(); // Skips the next instruction if the key stored in registers[X] is not pressed.
void executeOpcodeFX07(); // registers[X] = delay_timer
void executeOpcodeFX0A(); // A key press is awaited, and then stored in VX. (Blocking until next key event)
void executeOpcodeFX15(); // delay_timer = registers[X]
void executeOpcodeFX18(); // sound_timer = registers[X]
void executeOpcodeFX1E(); // ir += registers[X]
void executeOpcodeFX29(); // Sets ir to the location of the sprite for the character in registers[X]
void executeOpcodeFX33(); // Stores the binary-coded decimal representation of registers[X]
void executeOpcodeFX55(); // Stores registers[0] to registers[X] (including registers[X] in memory starting at address ir
void executeOpcodeFX65(); // Fills registers[0] to registers[X] (including registers[X]) with values starting at address ir
};
#endif | true |
f43f6aec66e69c04aa9f4fb85df22b3bc84a88a4 | C++ | Zachary-Kramer/FMWS | /include/Types.hpp | UTF-8 | 869 | 3.234375 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////////////////
/// @file Types.hpp
/// @brief Defines various custom data types for ease-of-use
///////////////////////////////////////////////////////////////////////////////
#pragma once
#include <utility> // For std::size_t
#include <iostream> // For printing
#include <iomanip> // For messing with precision
#include <string> // For std::string
// Define a standard type to represent indices
// -------------------------------------------
// std::size_t is designed for this, make it our standard
// It is essentially an unsigned int, which is the type used in sizeof() and
// similar functions. It can store the maximum size of any type.
// https://en.cppreference.com/w/cpp/types/size_t
// Is extremely important to *not* use int because of the human genome
using Index = std::size_t;
| true |
4c186d9739f05e2ae039a5cf9843263e4768780a | C++ | LXGVENICE/my-webserver | /HttpResponse.hpp | UTF-8 | 842 | 2.578125 | 3 | [] | no_license | #pragma once
#include <string>
#include <unordered_map>
#include "HttpState.hpp"
#define PATH "/home/ubuntu/my-webserver/html"
#define CRFL "\r\n"
//enum HTTPMethod
//{
// GET, POST, DELETE, PUT, HEAD,
// INVAILD;
//}
class HttpResponse
{
public:
HttpResponse():keep_alive(true){}
bool parser(int ret,std::string line);
bool first_parser(std::string line);
std::string get_pkg();
bool is_keep_alive(){ return keep_alive; }
void clear();
private:
bool header_parser(std::string &line);
void create_first();
std::string set_time();
private:
HttpState m_state;//HTTP状态码
std::string m_protocol;//HTTP协议版本
std::string m_resource;//HTTP请求资源
bool keep_alive;
std::string m_first;
std::unordered_map<std::string,std::string> m_header;
std::string m_body;
};
| true |
9c537036524b837e8d2a96bb8b7a0ade57e30751 | C++ | bresearch/json | /jparser.h | UTF-8 | 935 | 2.703125 | 3 | [] | no_license | // A simple recursive descent JSON Object parser
// Author: Nurudeen Lameed
#include "jscan.h"
#include "jtypes.h"
class JParser
{
struct ParsingError : public std::runtime_error
{ParsingError(const char* what) : std::runtime_error{what} {}};
public:
using Member = std::pair<std::string, JValue*>;
JParser(const JScanner::TokenList& tkns) :
offset{0}, tokens{tkns}, ct{JScanner::END} {}
JObject* parse();
JObject* parseObject();
JArray* parseArray();
Member parseMember();
JValue* parseValue();
private:
// match the read token with the expected one
// throw an error if there is no match:
void match(JScanner::TokenType read, JScanner::TokenType expected,
bool readNextToken = true);
const JScanner::Token& getNextToken() const
{ return offset < tokens.size() ?
tokens[offset++] : tokens.back();}
mutable size_t offset;
const JScanner::TokenList& tokens;
JScanner::Token ct;
};
| true |
754e8b9d6f8e3099b2d2eeee0d2f31af7fb834b8 | C++ | overnew/CodeSaving | /GA_30.cpp | UTF-8 | 1,025 | 3.375 | 3 | [] | no_license | //https://www.acmicpc.net/problem/10610
//너무 깊게 생각함.
//30의 배수는 0이 있어야하고, 각 자리수들의 합이 3의 배수면 됨.(3의 배수의 특징)
//두 조건만 성립하면 0이 앞에 있기만 하면 30의 배수이기 때문에 그냥 내림차순으로 정리하면됨.
// 그리고 계속 num[i] = n[i] -'0'; 처럼 문자열에서 수를 가져올때 -'0'를 빼먹어서 오류가 나오니 조심하자
#include <iostream>
#include<string>
#include <algorithm>
using namespace std;
int num[100000];
int main() {
string n;
int sum=0;
cin>>n;
for(int i=0; i<n.length() ; ++i){
num[i] = n[i] -'0';
}
sort(num, num+n.length(), greater<int>());
//내림차순
if(num[n.length() -1] != 0){ //0이 없으면 불가능
cout<<-1<<endl;
return 0;
}
for(int i=0; i<n.length() ; ++i){
sum += num[i];
}
if(sum %3 !=0){
cout<<-1<<endl;
return 0;
}
for(int i=0; i<n.length() ; ++i){
cout<<num[i];
}
cout<<endl;
return 0;
}
| true |
10a8b0e4516f1ddfcd36a38df4ef57177f9df624 | C++ | itsss/SASA_Programming-I | /ProgrammingIClass/Homework/int2(HW)/(A) 경로 구하기1.cpp | UTF-8 | 1,759 | 3.359375 | 3 | [] | no_license | /*
경로 구하기 1
사이클이 없는 그래프 G의 한 정점에서 다른 정점까지 이동할 수 있는 경로는 1가지만 존재한다.
그래프 G와 시작정점 s, 도착정점 e를 입력받아 s로부터 e까지의 경로에 포함되는 정점들을 순서대로 출력하는 프로그램을 작성하시오.
<입력>
첫 줄에 정점의 개수 n(2<n<=10)과 간선의 개수 m(=n-1)이 입력된다.
둘째줄부터 인접한 2개의 정점이 m+1째 줄까지 입력된다.
마지막 줄에 시작정점 s와 도착정점 e가 입력된다.
단 정점은 1 이상의 정수로 표현되며, 비어있는 수는 없다고 가정한다.
5 4
1 2
1 3
3 5
2 4
4 5
<출력>
시작정점 s로부터 도착정점 e까지의 경로에 포함되는 정점들을 방문 순서대로 출력한다.
4 2 1 3 5
*/
#include <stdio.h>
#include <stack>
using namespace std;
stack<int> st;
int n, m, endd, map[100][100], visited[100];
void visit(int a)
{
visited[a]=1;
st.push(a);
}
void dfs(char k)
{
int i;
visit(k);
while(!st.empty())
{
if(st.top()==endd) return;
for(i = 1; i <= n; i++)
{
if(map[st.top()][i] && !visited[i])
{
visit(i);
break;
}
}
if(i == n+1)
st.pop();
}
}
void print()
{
if(st.empty()) return;
int ans = st.top();
st.pop();
print();
printf("%d ", ans);
}
int main()
{
scanf("%d %d", &n, &m);
for(int i = 0; i < m; i++)
{
int v1, v2;
scanf("%d %d", &v1, &v2);
map[v1][v2]=map[v2][v1] = 1;
}
int start;
scanf("%d %d", &start, &endd);
dfs(start);
print();
return 0;
}
| true |
5424469285cf7bcaf2dff304acb51ac9646d9b71 | C++ | HAW-MT-Jg2013/HAW_S14-PRP2 | /PRP2-A4/DataReader.cpp | UTF-8 | 1,338 | 2.875 | 3 | [] | no_license | //
// DataReader.cpp
// BScMech2-SoSe14-PRP2
//
// Created by Jannik Beyerstedt on 31.05.14.
// Copyright (c) 2014 Jannik Beyerstedt. All rights reserved.
//
#include "DataReader.h"
#include <fstream>
DataReader::DataReader () {
} // SOMETHING TO DO HERE ???
DataReader::~DataReader() {
if (rawData != NULL) {
delete [] rawData;
}else {
cout << "INFO: DataReader::~DataReader - no data to free" << endl;
}
}// DONE
void DataReader::readDataFrom(const char *FileName) {
if (rawData == NULL) {
rawData = new double[200];
}else {
cout << "INFO: DataReader::readDataFrom - rawData already read" << endl;
}
ifstream rawInput(FileName);
for (int i = 0; i < MAX_DATA; i++) {
rawInput >> rawData[i];
}
rawInput.close();
}// DONE
void DataReader::setDataCorrection(Corrector *corrector) {
ptrCorrector = corrector;
}// DONE
void DataReader::writeCorrectedDataToFile(const char* FileName) {
ofstream outputFile(FileName);
if (rawData != NULL && ptrCorrector != NULL) {
for (int i = 0; i < MAX_DATA; i++) {
outputFile << ptrCorrector->correctValue(rawData[i]) << endl;
}
}else {
cerr << "ERROR: DataReader::writeCorrectedDataToFile - NULL pointer found" << endl;
}
outputFile.close();
}// DONE
| true |
40e4dac7ebf623420c4c561350f30e4b09633e7a | C++ | AndrewNomura/Virtual-Memory-Manager | /main.cpp | UTF-8 | 3,363 | 2.875 | 3 | [] | no_license | //
// main.cpp
// CPSC 351 Final Programming Project
//
// Created by Andrew Nomura on 4/27/19.
// Copyright © 2019 Andrew Nomura. All rights reserved.
//
#include <iostream>
#include <iomanip>
#include <cstddef>
#include <string>
#include <vector>
#include <fstream>
//#include "Hardware/MemoryManagementUnit.hpp"
//#include "Hardware/Word.hpp" //Address
#include "Hardware/MemoryManagementUnit.cpp"
//#include "Hardware/Word.cpp" //Address
//#include "Hardware/Address.hpp"
//#include "OperatingSystem/MemoryManager.hpp"
#include "OperatingSystem/PageTable.cpp"
#include "Hardware/Word.cpp"
/*
namespace Hardware{
struct ProcessControlBlock{
PageTable myPageTable;
};
using PCB = ProcessControlBlock;
}
*/
/*
namespace {
void runProcess()
{
auto & MMU = Hardware::MemoryManagementUnit::instance();
OperatingSystem::ProcessControlBlock myPCB;
MMU.clearTLB();
// For each address (while not EOF):
// 1) Read the byte of data at that address; and
// 2) Display the address and data.
Hardware::Address logicalAddress;
while(std::cin >> logicalAddress;) // For each address (while not EOF)
{
while(true) try // A single instruction may generate many page faults
{
// 1) Read the byte of data at that address
MMU.read( logicalAddress, myPCB.myPageTable, myData ); // May throw PageFault
// 2) Display the address and data
std::cout << myData;
break; // instruction completed successfully, okay to move to the next one
}
catch(const Hardware::MMU::PageFault & fault) // Handle page faults, then restart instruction
{
// load the page, update tables, and restart the instruction
memoryManager.pageIn( fault.pageNumber_, myPCB.myPageTable );
}
} // while(...)
} // void runProcess()
}
*/
using namespace std;
int main(int argc, const char * argv[]) {
int table[256][2]; //page table
Word page;
Word offset;
//create all objects
PageTable myPageTable;
MemoryManagementUnit MMU;
MemoryManager mm;
vector<int> v;
char data;
myPageTable.fillPT();
mm.makeVector();
Word logicalAddress;
ifstream file;
file.open("/Users/andrewnomura/Documents/CSUF/SPRING 2019/CPSC-351 Operating Systems/Final Programing Project/CPSC 351 Final Programming Project/CPSC 351 Final Programming Project/addresses.txt");
if (!file.is_open()){
cerr << "unable to open file...";
exit(1);
}
while (file >> logicalAddress.uint32_t){
//cout << logicalAddress << "\n";
page.uint32_t = (logicalAddress.uint32_t & 0xFF00) >> 8;
offset.uint32_t = (logicalAddress.uint32_t & 0xFF);
//cout << page << "\t" << offset << "\n";
//v.push_back(logicalAddress);
mm.makeValid(table, page.uint32_t);
MMU.read(logicalAddress, myPageTable, data);
}
file.close();
//we now have a list of all addresses
//myPageTable.outputPT();
myPageTable.outputRAM();
return 0;
}
| true |
26286dc97497cae333b45e395f26265a1024036f | C++ | erleben/matchstick | /PROX/FOUNDATION/TINY/TINY/include/tiny_accessor.h | UTF-8 | 1,060 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef TINY_ACCESSOR_H
#define TINY_ACCESSOR_H
#include <cstddef> // Needed for size_t
namespace tiny
{
namespace detail
{
/**
* Accessor class.
* This class provides cast operations for type conversions.
*
* @tparam M The math base type that should be accessed.
*/
template <typename M>
class Accessor
{
public:
typedef typename M::op_type op_type;
static op_type & cast (M & m, size_t const & i, size_t const & j)
{
return m.get_op_type(i,j);
}
static op_type cast (M const & m, size_t const i, size_t const j)
{
return m.get_op_type(i,j);
}
static size_t stride () { return M::stride; }
static size_t padding () { return M::padding; }
static size_t J_padded () { return M::J_padded; }
static size_t allocsize() { return M::allocsize; }
};
} // namespace detail
} // namespace tiny
// TINY_ACCESSOR_H
#endif
| true |
9df55eea860f079e5e0ba62424ef7bffafa245f5 | C++ | hulian425/ACM-ICPC | /algorithm code/Computational Geometry/Jarcis March.cpp | UTF-8 | 1,463 | 3.234375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
using namespace std;
// Finding LTL
// 三点一线未解决
struct Point
{
int x;
int y;
bool extreme;
int succ;
};
int LTL(Point S[], int n) // n > 2
{
int ltl = 0; // the lowest-thrn-leftmost point
for (int k = 1; k < n; k++) // test all points
{
if (S[k].y < S[ltl].y || (S[k].y == S[ltl].y && S[k].x < S[ltl].x))
ltl = k;
}
return ltl;
}
int area2(Point A, Point B, Point C)
{
return (A.x * (B.y - C.y)) + B.x * (C.y - A.y) + C.x * (A.y - B.y);
}
int ToLeft(Point p, Point q, Point s)
{
int ans = area2(p, q, s);
if (ans > 0) return 1;
else if (ans == 0) return 0;
else return -1;
}
void Jarvis(Point S[], int n)
{
for (int k = 0; k < n; k++)
{
S[k].extreme = false;
S[k].succ = -1;
}
int ltl = LTL(S, n); int k = ltl;
do { // start with LTL
S[k].extreme = true; int s = -1;
for (int t = 0; t < n; t++) // check
if (t != k && t != s && (s == -1) || ToLeft(S[k], S[s], S[t]) == -1) // candidate t
{
s = t; // update s if t lies right to ks
}
S[k].succ = s; k = s; // new EE(p, q)identified
} while (ltl != k); // quit when LTL reached
printf("x = %d, y = %d\n", S[ltl].x, S[ltl].y);
for (int i = S[ltl].succ; i != ltl; i = S[i].succ)
printf("x = %d, y = %d\n", S[i].x, S[i].y);
}
int main()
{
Point points[] = { {0, 3}, {2, 2}, {1, 1}, {2, 1},
{3, 0}, {0, 0}, {3, 3} };
int n = sizeof(points) / sizeof(points[0]);
Jarvis(points, n);
return 0;
}
| true |
e6abc9a77d82db44327b50c45750ad9d2038a6c1 | C++ | pqrs-org/cpp-osx-chrono | /tests/src/chrono_test.hpp | UTF-8 | 1,402 | 2.640625 | 3 | [
"BSL-1.0"
] | permissive | #include <boost/ut.hpp>
#include <iostream>
#include <pqrs/osx/chrono.hpp>
void run_chrono_test(void) {
using namespace boost::ut;
using namespace boost::ut::literals;
"make_absolute_time_duration"_test = [] {
{
std::chrono::nanoseconds ns(256 * 1000000);
auto absolute_time_duration = pqrs::osx::chrono::make_absolute_time_duration(ns);
expect(pqrs::osx::chrono::make_milliseconds(absolute_time_duration) == std::chrono::milliseconds(256));
}
{
std::chrono::milliseconds ms(256 * 1000000);
auto absolute_time_duration = pqrs::osx::chrono::make_absolute_time_duration(ms);
expect(pqrs::osx::chrono::make_milliseconds(absolute_time_duration) == ms);
}
};
"make_nanoseconds"_test = [] {
{
pqrs::osx::chrono::absolute_time_duration absolute_time_duration(256 * 1000000);
auto ns = pqrs::osx::chrono::make_nanoseconds(absolute_time_duration);
expect(std::abs(type_safe::get(pqrs::osx::chrono::make_absolute_time_duration(ns) - absolute_time_duration)) < 1000);
}
};
"make_milliseconds"_test = [] {
{
pqrs::osx::chrono::absolute_time_duration absolute_time_duration(256 * 1000000);
auto ms = pqrs::osx::chrono::make_milliseconds(absolute_time_duration);
expect(std::abs(type_safe::get(pqrs::osx::chrono::make_absolute_time_duration(ms) - absolute_time_duration)) < 1000000);
}
};
}
| true |
b9af237bea467197aae60a93b6238d56cb7c6b6b | C++ | sauravchaudharysc/InterviewBit-Solutions | /Arrays/Min Steps in Infinite Grid.cpp | UTF-8 | 854 | 3.75 | 4 | [] | no_license | /*One way to reach from a point (x1, y1) to (x2, y2) is to move
abs(x2-x1) steps in the horizontal direction and abs(y2-y1) steps
in the vertical direction, but this is not the shortest path to
reach (x2, y2). The best way would be to cover the maximum
possible distance in a diagonal direction and remaining in
horizontal or vertical direction.If we look closely this just
reduces to the maximum of abs(x2-x1) and abs(y2-y1).*/
int count(int x1,int y1,int x2,int y2){
//Steps along x-axis
int dx=abs(x1-x2);
//Steps along y-axis
int dy=abs(y1-y2);
//The max of dx and dy which is at distance from diagonals
return max(dx,dy);
}
int Solution::coverPoints(vector<int> &A, vector<int> &B) {
int n=A.size();
int sum=0;
for(int i=0;i<n-1;i++){
sum+=count(A[i],B[i],A[i+1],B[i+1]);
}
return sum;
}
| true |
e77e3f121bb191fcabd565df0303d73d5274ed98 | C++ | AmbBAI/softrender | /softrender/softrender/texture2d.cpp | UTF-8 | 6,339 | 2.578125 | 3 | [
"Unlicense"
] | permissive | #include "texture2d.h"
#include "math/mathf.h"
#include "freeimage/FreeImage.h"
#include "sampler.hpp"
namespace sr
{
Texture2D::SampleFunc Texture2D::sampleFunc[2][AddressModeCount][AddressModeCount] = {
{
{
PointSampler::Sample < WarpAddresser, WarpAddresser >,
PointSampler::Sample < WarpAddresser, MirrorAddresser >,
PointSampler::Sample < WarpAddresser, ClampAddresser >
},
{
PointSampler::Sample < MirrorAddresser, WarpAddresser >,
PointSampler::Sample < MirrorAddresser, MirrorAddresser >,
PointSampler::Sample < MirrorAddresser, ClampAddresser >
},
{
PointSampler::Sample < ClampAddresser, WarpAddresser >,
PointSampler::Sample < ClampAddresser, MirrorAddresser >,
PointSampler::Sample < ClampAddresser, ClampAddresser >
},
},
{
{
LinearSampler::Sample < WarpAddresser, WarpAddresser >,
LinearSampler::Sample < WarpAddresser, MirrorAddresser >,
LinearSampler::Sample < WarpAddresser, ClampAddresser >
},
{
LinearSampler::Sample < MirrorAddresser, WarpAddresser >,
LinearSampler::Sample < MirrorAddresser, MirrorAddresser >,
LinearSampler::Sample < MirrorAddresser, ClampAddresser >
},
{
LinearSampler::Sample < ClampAddresser, WarpAddresser >,
LinearSampler::Sample < ClampAddresser, MirrorAddresser >,
LinearSampler::Sample < ClampAddresser, ClampAddresser >
},
}
};
void Texture2D::Initialize()
{
FreeImage_Initialise();
}
void Texture2D::Finalize()
{
FreeImage_DeInitialise();
}
Texture2DPtr Texture2D::CreateWithBitmap(BitmapPtr& bitmap)
{
if (bitmap == nullptr) return nullptr;
Texture2DPtr tex = Texture2DPtr(new Texture2D());
tex->mainTex = bitmap;
tex->width = bitmap->GetWidth();
tex->height = bitmap->GetHeight();
return tex;
}
Texture2DPtr Texture2D::LoadTexture(const std::string& file)
{
return LoadTexture(file.c_str());
}
std::map<std::string, Texture2DPtr> Texture2D::texturePool;
Texture2DPtr Texture2D::LoadTexture(const char* file)
{
std::map<std::string, Texture2DPtr>::iterator itor;
itor = texturePool.find(file);
if (itor != texturePool.end())
{
return itor->second;
}
else
{
BitmapPtr bitmap = Bitmap::LoadFromFile(file);
Texture2DPtr tex = CreateWithBitmap(bitmap);
if (tex != nullptr)
{
tex->file = file;
texturePool[file] = tex;
}
return tex;
}
}
void Texture2D::ConvertBumpToNormal(float strength/* = 10.f*/)
{
int width = mainTex->GetWidth();
int height = mainTex->GetHeight();
std::vector<float> bump(width * height, 0.f);
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
bump[y * width + x] = mainTex->GetAlpha(x, y);
}
}
mainTex = std::make_shared<Bitmap>(width, height, Bitmap::BitmapType_RGB24);
for (int y = 0; y < (int)height; ++y)
{
for (int x = 0; x < (int)width; ++x)
{
int x1 = x - 1;
int x2 = x + 1;
int y1 = y - 1;
int y2 = y + 1;
if (x1 < 0) x1 = 0;
if (x2 >= (int)width) x2 = width - 1;
if (y1 < 0) y1 = 0;
if (y2 >= (int)height) y2 = height - 1;
float px1 = bump[y * width + x1];
float px2 = bump[y * width + x2];
float py1 = bump[y1 * width + x];
float py2 = bump[y2 * width + x];
Vector3 normal = Vector3(px1 - px2, py1 - py2, 1.f / strength).Normalize();
Color color;
color.r = (normal.x + 1.0f) / 2.0f;
color.g = (normal.y + 1.0f) / 2.0f;
color.b = (normal.z + 1.0f) / 2.0f;
mainTex->SetPixel(x, y, color);
}
}
}
const Color Texture2D::Sample(const Vector2& uv, float lod/* = 0.f*/) const
{
switch (filterMode) {
case FilterMode_Point:
{
int miplv = FixMipLevel(Mathf::RoundToInt(lod));
const Bitmap& bmp = GetBitmapFast(miplv);
return sampleFunc[0][xAddressMode][xAddressMode](bmp, uv.x, uv.y);
}
case FilterMode_Bilinear:
{
int miplv = FixMipLevel(Mathf::RoundToInt(lod));
const Bitmap& bmp = GetBitmapFast(miplv);
return sampleFunc[1][xAddressMode][xAddressMode](bmp, uv.x, uv.y);
}
case FilterMode_Trilinear:
{
int miplv1 = FixMipLevel(Mathf::FloorToInt(lod));
int miplv2 = FixMipLevel(miplv1 + 1);
float frac = lod - miplv1;
const Bitmap& bmp1 = GetBitmapFast(miplv1);
Color color1 = sampleFunc[1][xAddressMode][xAddressMode](bmp1, uv.x, uv.y);
if (miplv1 == miplv2)
{
return color1;
}
const Bitmap& bmp2 = GetBitmapFast(miplv2);
Color color2 = sampleFunc[1][xAddressMode][xAddressMode](bmp2, uv.x, uv.y);
return Color::Lerp(color1, color2, frac);
}
}
return Color::black;
}
bool Texture2D::GenerateMipmaps()
{
int width = mainTex->GetWidth();
int height = mainTex->GetHeight();
if (width != height) return false;
if (!Mathf::IsPowerOfTwo(width)) return false;
mipmaps.clear();
BitmapPtr source = mainTex;
int s = (width >> 1);
for (int l = 0;; ++l)
{
BitmapPtr mipmap = std::make_shared<Bitmap>(s, s, mainTex->GetType());
for (int y = 0; y < s; ++y)
{
int y0 = y * 2;
int y1 = y0 + 1;
for (int x = 0; x < s; ++x)
{
int x0 = x * 2;
int x1 = x0 + 1;
Color c0 = source->GetPixel(x0, y0);
Color c1 = source->GetPixel(x1, y0);
Color c2 = source->GetPixel(x0, y1);
Color c3 = source->GetPixel(x1, y1);
mipmap->SetPixel(x, y, Color::Lerp(c0, c1, c2, c3, 0.5f, 0.5f));
}
}
mipmaps.emplace_back(mipmap);
source = mipmaps[l];
s >>= 1;
if (s <= 0) break;
}
return true;
}
const BitmapPtr Texture2D::GetBitmap(int miplv) const
{
miplv = FixMipLevel(miplv);
if (miplv == 0) return mainTex;
else
{
return mipmaps[miplv - 1];
}
}
int Texture2D::FixMipLevel(int miplv) const
{
return Mathf::Clamp(miplv, 0, (int)mipmaps.size());
}
const Bitmap& Texture2D::GetBitmapFast(int miplv) const
{
if (miplv == 0) return *mainTex;
else
{
return *mipmaps[miplv - 1];
}
}
float Texture2D::CalcLOD(const Vector2& ddx, const Vector2& ddy) const
{
if (mainTex == nullptr) return 0.f;
float w2 = (float)width * width;
float h2 = (float)height * height;
float delta = Mathf::Max(ddx.Dot(ddx) * w2, ddy.Dot(ddy) * h2);
return Mathf::Max(0.f, 0.5f * Mathf::Log2(delta));
}
int Texture2D::GetMipmapsCount() const
{
return mipmaps.size();
}
void Texture2D::SetMipmaps(std::vector<BitmapPtr>& bitmaps)
{
mipmaps = bitmaps;
}
}
| true |
30cba863efac9f108b519b3ebf6475f7cad7d072 | C++ | thodorisGeorgiou/3D_texture_based_clustering | /Source_code/mitra_var_1.cpp | UTF-8 | 7,762 | 2.640625 | 3 | [] | no_license | #include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <pthread.h>
#include <iostream>
#include <thread>
#include <math.h>
#include "mitra_var_1.h"
MITRA_VAR_1::MITRA_VAR_1(int n_threads, float thres){
num_threads = n_threads;
threshold = thres;
}
void MITRA_VAR_1::distance_calculator(cv::Mat &_src, std::vector<std::vector<MITRA_VAR_1::dist_struct> > &dst){
float *src = (float*)_src.data;
size_t step_src = _src.step/sizeof(src[0]);
std::vector<std::thread> threads;
void *temp = (void*) &dst;
dims = _src.rows;
for(int t = 0; t< num_threads; t++){
threads.push_back(std::thread(&MITRA_VAR_1::thread_mici_calculator, this, t, src, step_src, temp, _src.cols));
}
// for(int t = 0; t< num_threads; t++){
// threads.push_back(std::thread(&MITRA_VAR_1::thread_cosine_calculator, this, t, src, step_src, temp, _src.cols));
// }
for (auto& t: threads) t.join();
for(int feature = _src.cols - 1; feature >= 0 ; feature--) {
for(int qFeature = 0; qFeature < dst[feature].size(); qFeature++){
MITRA_VAR_1::dist_struct s;
s.distance = dst[feature][qFeature].distance;
s.index = feature;
sorted_insert(s, dst[dst[feature][qFeature].index]);
}
}
}
void MITRA_VAR_1::thread_cosine_calculator(int thread_id, float *src, size_t step_src, void *_dst, int num_features){
std::vector< std::vector<MITRA_VAR_1::dist_struct> > &dst = *((std::vector< std::vector<MITRA_VAR_1::dist_struct> > *)_dst);
for(int feature = thread_id; feature < num_features - 1; feature+=num_threads){
long double feature_length = 0;
for(int d = 0; d<dims; d++){
float val = src[feature + d*step_src];
feature_length += (long double)(val*val);
}
feature_length = (long double)sqrt((double)(feature_length));
for(int qFeature = feature+1; qFeature<num_features; qFeature++){
long double qFeature_length = 0;
long double inner_prod = 0;
for(int d = 0; d<dims; d++){
register float qVal = src[qFeature + d*step_src];
register float fVal = src[feature + d*step_src];
qFeature_length += (long double)(qVal*qVal);
inner_prod += (long double)(qVal*fVal);
}
qFeature_length = (long double)sqrt((double)(qFeature_length));
MITRA_VAR_1::dist_struct s;
s.index = qFeature;
float prod = (float)(feature_length*qFeature_length);
if(prod == 0) s.distance = 1;
else{
s.distance = (float)(1-(inner_prod/prod));
}
sorted_insert(s, dst[feature]);
}
}
}
void MITRA_VAR_1::thread_mici_calculator(int thread_id, float *src, size_t step_src, void *_dst, int num_features){
std::vector< std::vector<MITRA_VAR_1::dist_struct> > &dst = *((std::vector< std::vector<MITRA_VAR_1::dist_struct> > *)_dst);
for(int feature = thread_id; feature < num_features - 1; feature+=num_threads){
long double var_feature = 0;
long double mean_feature = 0;
for(int d = 0; d<dims; d++){
float val = src[feature + d*step_src];
var_feature += (long double)(val*val);
mean_feature += (long double)val;
}
mean_feature = mean_feature/dims;
var_feature = var_feature/dims - mean_feature*mean_feature;
for(int qFeature = feature+1; qFeature<num_features; qFeature++){
long double var_qFeature = 0;
long double mean_qFeature = 0;
long double cov = 0;
for(int d = 0; d<dims; d++){
register float val = src[qFeature + d*step_src];
var_qFeature += (long double)(val*val);
mean_qFeature += (long double)val;
cov += (long double)(val*src[feature + d*step_src]);
}
mean_qFeature = mean_qFeature/dims;
var_qFeature = var_qFeature/dims - mean_qFeature*mean_qFeature;
MITRA_VAR_1::dist_struct s;
s.index = qFeature;
float prod = (float)(var_feature*var_qFeature);
if(prod == 0) s.distance = 1;
else{
cov = (cov/dims - mean_qFeature*mean_feature)/sqrtf(prod);
register float riza = (float)((var_qFeature+var_feature)*(var_qFeature+var_feature)-4*prod*(1-cov*cov));
s.distance = (float)(var_feature+var_qFeature-sqrtf(riza))/(float)(var_feature+var_qFeature);
// s.distance = (float)(var_feature+var_qFeature-sqrtf(riza));
}
sorted_insert(s, dst[feature]);
}
}
}
void MITRA_VAR_1::sorted_insert(MITRA_VAR_1::dist_struct s, std::vector<MITRA_VAR_1::dist_struct> &vec){
int temp = 0;
register float distance = s.distance;
while(temp < vec.size()){
if(distance <= vec[temp].distance)
break;
temp++;
}
vec.insert(vec.begin()+temp, s);
}
int MITRA_VAR_1::find_mini(std::vector<std::vector<MITRA_VAR_1::dist_struct> > sorted_distances, bool *checked, bool *deleted){
int minimum_feature = -1;
int minimum_count = 0;
// std::cout << sorted_distances.size() << std::endl;
for(int feature = 0; feature < sorted_distances.size(); feature++){
if(checked[feature] || deleted[feature]) continue;
int current_count = 0;
// std::cout << sorted_distances.size() << std::endl;
for(int qFeature = 0; qFeature < sorted_distances[feature].size(); qFeature++){
if(!deleted[sorted_distances[feature][qFeature].index]){
// std::cout << sorted_distances[feature][qFeature].distance << std::endl;
if(sorted_distances[feature][qFeature].distance < threshold)
current_count++;
else break;
}
}
if(current_count > minimum_count){
minimum_count = current_count;
minimum_feature = feature;
}
}
return(minimum_feature);
}
int MITRA_VAR_1::select_features(cv::Mat &_data){
std::vector<std::vector<MITRA_VAR_1::dist_struct> > sorted_distances;
for(int feature = 0; feature<_data.cols; feature++){
std::vector<MITRA_VAR_1::dist_struct> temp_vec;
sorted_distances.push_back(temp_vec);
}
// std::cout << "line 1" << std::endl;
distance_calculator(_data, sorted_distances);
// std::cout << "line 2" << std::endl;
bool checked[_data.cols], deleted[_data.cols];
for(int i = 0; i<_data.cols; i++){
checked[i] = false;
deleted[i] = false;
}
int nn_features = _data.cols;
int counter = 1;
while(true){
int to_delete_feature = find_mini(sorted_distances, checked, deleted);
// std::cout << "in this loop " << counter << " times" << std::endl;
counter++;
// std::cout << K << std::endl;
if(to_delete_feature == -1) break;
checked[to_delete_feature] = true;
int kapa = 0;
while(true){
// std::cout << to_delete_feature << " " << sorted_distances[to_delete_feature][kapa].index << " " << sorted_distances[to_delete_feature][kapa].distance << std::endl;
// std::cout << deleted[sorted_distances[to_delete_feature][kapa].index] << std::endl;
// std::cout << deleted[sorted_distances[minimum_feature][kapa].index] << std::endl;
if(!deleted[sorted_distances[to_delete_feature][kapa].index]){
if(sorted_distances[to_delete_feature][kapa].distance < threshold){
// std::cout << sorted_distances[minimum_feature][kapa].index << std::endl;
// std::cout << sorted_distances[to_delete_feature][kapa].index << " " << sorted_distances[to_delete_feature][kapa].distance << std::endl;
deleted[sorted_distances[to_delete_feature][kapa].index] = true;
nn_features--;
}
else break;
}
kapa++;
if((kapa >= sorted_distances[to_delete_feature].size())) break;
}
}
// std::cout << "line 3" << std::endl;
sorted_distances.clear();
cv::Mat _new_features = cv::Mat(_data.rows, nn_features, CV_32F);
float *data = (float*)_data.data;
size_t step_d = _data.step/sizeof(data[0]);
float *new_features = (float*)_new_features.data;
size_t step_nf = _new_features.step/sizeof(new_features[0]);
int new_ind = 0;
for(int feature = 0; feature < _data.cols; feature++){
if(deleted[feature]) continue;
for(int d = 0; d < _data.rows; d++) new_features[new_ind + d*step_nf] = data[feature+d*step_d];
kept_features.push_back(feature);
new_ind++;
}
cv::swap(_data, _new_features);
return nn_features;
}
MITRA_VAR_1::~MITRA_VAR_1(){
} | true |
e7a7950cde344fb33d8a07c1a2460fce4ed84628 | C++ | Yory-Z/Algorithm | /header/Parenthesis.h | UTF-8 | 3,880 | 3.609375 | 4 | [] | no_license | //
// Created by Yory on 2019/1/18.
//
#ifndef ALGORITHM_PARENTHESIS_H
#define ALGORITHM_PARENTHESIS_H
#include <string>
#include <stack>
#include <iostream>
using namespace std;
class Parenthesis {
public:
void testParenthesis();
void testGenerateParenthesis();
static void testLongestValidParentheses();
private:
bool testParenthesis(string s);
bool isCorrect(char ch1, char ch2);
void generateParenthesis(int n, int k, char *arr, int left, int right, vector<string> &res);
static int longestValidParentheses(string s);
static int longestValidParentheses2(string s);
};
//generate parenthesis
void Parenthesis::testGenerateParenthesis() {
int n = 3;
char* arr = new char[n*2];
vector<string> res;
generateParenthesis(n * 2, 0, arr, 0, 0, res);
for (string str : res) {
cout<<str<<endl;
}
}
void Parenthesis::generateParenthesis(int n, int k, char *arr, int left, int right, vector<string> &res) {
if (k == n){
string temp;
for (int i = 0; i < n; ++i) {
temp += arr[i];
}
res.push_back(temp);
return;
}
if (left < n / 2){
arr[k] = '(';
generateParenthesis(n, k + 1, arr, left + 1, right, res);
}
if (right < left){
arr[k] = ')';
generateParenthesis(n, k + 1, arr, left, right + 1, res);
}
}
void Parenthesis::testParenthesis() {
// string str = "()";
// string str = "(){}[]";
// string str = "(]";
string str = "([)]";
// string str = "{[()]}";
// string str = "((";
bool res = testParenthesis(str);
cout<<"res: "<<res<<endl;
}
bool Parenthesis::testParenthesis(string s) {
if(s.size() % 2 == 1)
return false;
stack<char> sta;
for (int i = 0; i < s.size(); ++i) {
char ch = s.at(i);
if (ch == '(' || ch == '[' || ch == '{'){
sta.push(ch);
} else {
if (sta.empty() || !isCorrect(sta.top(), ch))
return false;
sta.pop();
}
}
return sta.empty();
}
bool Parenthesis::isCorrect(char ch1, char ch2) {
switch (ch1) {
case '(':
return ch2 == ')';
case '[':
return ch2 == ']';
case '{':
return ch2 == '}';
default:
break;
}
return false;
}
void Parenthesis::testLongestValidParentheses() {
// string str = "(()";
string str = ")()())";
// string str = "()())((()))";
// string str = "))((())())))()";
int res = longestValidParentheses(str);
cout<<"res: "<<res<<endl;
res = longestValidParentheses2(str);
cout<<"res: "<<res<<endl;
}
int Parenthesis::longestValidParentheses2(string s) {
stack<int> sta;
sta.push(-1);
int maxLen = 0;
for (int i = 0; i < s.size(); ++i) {
int top = sta.top();
if (top != -1 && s.at(i) == ')' && s.at(top) == '('){
sta.pop();
maxLen = max(maxLen, i - sta.top());
} else {
sta.push(i);
}
}
return maxLen;
}
int Parenthesis::longestValidParentheses(string s) {
int left = 0, right = 0;
int maxLen = 0;
for(int i = 0; i < s.size(); ++i){
if(s.at(i) == '('){
++left;
} else {
++right;
}
if (left == right){
maxLen = max(maxLen, 2 * right);
} else if (right > left){
left = 0;
right = 0;
}
}
left = 0;
right = 0;
for(int i = s.size() - 1; i >= 0; --i){
if(s.at(i) == '('){
++left;
} else {
++right;
}
if (left == right){
maxLen = max(maxLen, 2 * right);
} else if (left > right){
left = 0;
right = 0;
}
}
return maxLen;
}
#endif //ALGORITHM_PARENTHESIS_H
| true |
dd4cfc9e0810ca8a69b72e3e28ad36c5192b5924 | C++ | pochi0701/cybele | /source/cbl_base64.cpp | UTF-8 | 2,408 | 2.828125 | 3 | [] | no_license | #include "stdafx.h"
// ==========================================================================
//code=UTF8 tab=4
//
// Cybele: Application SErver.
//
// cbl_base64.cpp
// $Revision: 1.0 $
// $Date: 2018/02/12 21:11:00 $
//
// ==========================================================================
static unsigned char ToBase64tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static unsigned char tmpout[256];
/// <summary>
/// 文字列からBASE64表現の文字列に変換
/// 返還後の文字列が255文字まで。
/// </summary>
/// <param name="instr">変換する文字列</param>
/// <returns>変換した文字列</returns>
unsigned char* base64(unsigned char* instr)
{
unsigned char* p = tmpout;
int count = 0;
/*
ABC ->
414243 ->
0100 0001 0100 0010 0100 0011 ->
010000 010100 001001 000011
10 14 09 03
*/
while (*instr) {
switch (count) {
case 0:
*p = (unsigned char)((*instr >> 2) & 0x3f);
break;
case 1:
*p = (unsigned char)((*instr++ << 4) & 0x3f);
*p |= (unsigned char)((*instr >> 4) & 0x3f);
break;
case 2:
*p = (unsigned char)((*instr++ << 2) & 0x3f);
*p |= (unsigned char)((*instr >> 6) & 0x3f);
break;
case 3:
*p = (unsigned char)((*instr++) & 0x3f);
break;
}
count++;
count %= 4;
*p = ToBase64tbl[*p];
*++p = '\0';
}
count = (4 - count) % 4;
while (count-- > 0) {
*p++ = '=';
*p = '\0';
}
return tmpout;
}
/// <summary>
/// BASE64表現の文字列から変換前の文字列に復元
/// 返還後の文字列が255文字まで。
/// </summary>
/// <param name="instr">変換する文字列</param>
/// <returns>変換した文字列</returns>
unsigned char* unbase64(unsigned char* instr)
{
char FromBase64tbl[256] = {};
unsigned char* p = tmpout;
//逆テーブルの作成,=も0になる
for (unsigned int i = 0; i < sizeof(ToBase64tbl); i++) {
FromBase64tbl[ToBase64tbl[i]] = (unsigned char)i;
}
/*
ABC -> 414243 -> 0100 0001 0100 0010 0100 0011
-> 010000 010100 001001 000011
10 14 09 03
*/
while (*instr) {
int s1 = FromBase64tbl[*instr++];
int s2 = FromBase64tbl[*instr++];
int s3 = FromBase64tbl[*instr++];
int s4 = FromBase64tbl[*instr++];
*p++ = (unsigned char)((s1 << 2) | (s2 >> 4));
*p++ = (unsigned char)(((s2 & 0x0f) << 4) | (s3 >> 2));
*p++ = (unsigned char)(((s3 & 0x03) << 6) | s4);
*p = 0;
}
return tmpout;
} | true |
498d1f00e18d3f0756252094e3f00c8cbfd388ae | C++ | MohammedHassan98/Problem-Solving | /Anton and Letters/main.cpp | UTF-8 | 463 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
int count = 0;
string str ;
getline (cin, str);
for (int i = 0; i < strlen(str); i++){
bool appears = false;
for (int j = 0; j < i; j++){
if (str[j] == str[i]){
appears = true;
break;
}
}
if (!appears){
count++;
}
}
cout << count ;
}
| true |
c85c9de3bc36274866e7675b81434a1f47e29b11 | C++ | PranabSarker10/CPlusPlus | /86 to 110 IO/86 to 110.IO PROGRAMMING/109.IO CUSTOM INSERTER EXTRACTOR FINAL EXAMPLE.cpp | UTF-8 | 673 | 3.5625 | 4 | [] | no_license | ///IO CUSTOM INSERTER EXTRACTOR FINAL EXAMPLE
/**
Input:
3
Output:
*
***
*****
*/
#include<iostream>
using namespace std;
class triangle
{
public:
int n;
triangle(){}
triangle(int x){n=x;}
};
///output part:
ostream & operator << (ostream &stream, triangle t)
{
int i,j;
for(i=1;i<=t.n;i++)
{
for(j=1; j<=(t.n-i); j++)
stream<<" ";
for(j=1; j<=(2*i - 1); j++)
stream<<"*";
stream<<endl;
}
return stream;
}
///input part:
istream & operator >> (istream &stream, triangle &t)
{
stream>>t.n;
return stream;
}
int main()
{
triangle ob;
cin>>ob;
cout<<ob;
return 0;
}
| true |
86baeb267671cb95a093270cf04b3d21aacd5a03 | C++ | minhduc462001/languageC | /nguyen to cung nhau.cpp | UTF-8 | 471 | 2.8125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int nguyento(int k){
if ( k<2) return 0;
for (int i = 2; i<= sqrt(k); i++)
if ( k % i ==0) return 0;
return 1;
}
int nguyentocungnhau(int x, int i){
int t;
t = __gcd(x,i);
if (t == 1) return 1;
return 0;
}
int main(){
int t;
cin>>t;
while(t--){
int x;
cin>>x;
int d = 0;
for(int j = 1;j<x;j++)
if(nguyentocungnhau(x,j)) d++;
if(nguyento(d)) cout<<"1"<<endl;
else cout<<"0"<<endl;
}
return 0;
}
| true |
b4bfcdce68c77090e070d48af6df0b557acdec4d | C++ | LouisLu78/My_Cbase | /CPP/mergeSort.cpp | UTF-8 | 2,022 | 3.1875 | 3 | [] | no_license | //Author: Guangqiang Lu
//Time: 20200504
//Email: gq4350lu@hotmail.com
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define SIZEA 11
#define SIZEB 14
#define SIZEC 10000
void merge(int*, int, int, int, int*);
void mergeSort(int*, int, int, int*);
void mergeSort(int*, const int);
void printArray(int*, const int);
int main()
{
int dataA[] = {5, 3, 7, 6, 4, 1, 0, 2, 9, 10, 8};
mergeSort(dataA, SIZEA);
printArray(dataA, SIZEA);
int dataB[] = {2, 6, 4, 8, 100, 12, 89, 68, 314, 45, 37, 43, 456, 84};
mergeSort(dataB, SIZEB);
printArray(dataB, SIZEB);
srand(time(NULL));
int dataC[SIZEC];
for (int i = 0; i < SIZEC; i++)
{
dataC[i] = rand() % SIZEC +1;
}
mergeSort(dataC, SIZEC);
printArray(dataC, SIZEC);
return 0;
}
void merge(int* unsorted, int first, int mid, int last, int* sorted)
{
int k = 0, i = first, j= mid;
while(i < mid && j < last)
{
if (unsorted[i] < unsorted[j])
{
sorted[k++] = unsorted[i++] ;
}
else
{
sorted[k++] = unsorted[j++];
}
}
while (i < mid)
{
sorted[k++] = unsorted[i++] ;
}
for(int m = 0; m < k; m++)
{
unsorted[m + first] = sorted[m];
}
}
void mergeSort(int* unsorted, int first, int last, int* sorted)
{
int mid = (first + last ) / 2;
if (first < last - 1)
{
mergeSort(unsorted, first, mid, sorted);
mergeSort(unsorted, mid, last, sorted);
merge(unsorted, first, mid, last, sorted);
}
}
void mergeSort(int* array, const int size)
{
int* sorted = new int[size];
if (sorted)
{
mergeSort(array, 0, size, sorted);
delete [ ] sorted;
}
else
{
printf("No memory is assigned!");
}
}
void printArray(int* array, const int size)
{
int i;
for ( i = 0; i < size; i++)
{
printf("%-6d", array[i]);
if (i % 20 == 19)
{
printf("\n");
}
}
printf("\n");
}
| true |
f8495cfe74f6c05d0ffaa43952e6d99b68f9fb1f | C++ | huangshenno1/algo | /soj/2014.cpp | UTF-8 | 845 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b)
{
return (*(int *)a-*(int *)b);
}
int main()
{
int t,iCase;
scanf("%d",&t);
for (iCase=0;iCase<t;iCase++)
{
int rope[1010];
int n;
scanf("%d",&n);
int max=0;
for (int i=0;i<n;i++)
{
scanf("%d",&rope[i]);
}
qsort(rope,n,sizeof(int),cmp);
int tearWeight;
for (int i=0;i<n;i++)
{
tearWeight=rope[i]*(n-i);
if (tearWeight>max)
max=tearWeight;
}
printf("%d\n",max);
}
return 0;
} | true |
35dea9b53e3065798de9c17a2943f4df61807042 | C++ | ManusiatamVan/AlPro2 | /LMS/Tugas/Tugas 4 TipeBentukLain/Typedef.cpp | UTF-8 | 196 | 3.03125 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
typedef int integer;
integer num1, num2, sum;
cout<<"Masukkan Dua Angka : ";
cin>>num1>>num2;
sum=num1+num2;
cout<<"Total = "<<sum;
}
| true |
210fd8d49c3c68ab7b206f3d4f2732cb8df07508 | C++ | BioinformaticsArchive/hal | /api/inc/halColumnIterator.h | UTF-8 | 4,110 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | /*
* Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
*
* Released under the MIT license, see LICENSE.txt
*/
#ifndef _HALCOLUMNITERATOR_H
#define _HALCOLUMNITERATOR_H
#include <list>
#include <map>
#include <set>
#include "halDefs.h"
#include "halDNAIterator.h"
#include "halSequence.h"
namespace hal {
/**
* Interface Column iterator for allowing traditional maf-like (left-to-right)
* parsing of a hal alignment. Columns are iterated with respect to
* a specified reference genome. This isn't the most efficient way
* to explore the hal structure, which is designed for bottom-up and/or
* top-down traversal.
*/
class ColumnIterator
{
public:
/// @cond TEST
// we can compare genomes by pointers (because they are persistent
// and unique, though it's still hacky) but we can't do the same
// for anything else, including sequences.
struct SequenceLess { bool operator()(const hal::Sequence* s1,
const hal::Sequence* s2) const {
return s1->getGenome() < s2->getGenome() || (
s1->getGenome() == s2->getGenome() &&
s1->getStartPosition() < s2->getStartPosition()); }
};
/// @endcond
typedef std::vector<hal::DNAIteratorConstPtr> DNASet;
typedef std::map<const hal::Sequence*, DNASet*, SequenceLess> ColumnMap;
/** Move column iterator one column to the right along reference
* genoem sequence */
virtual void toRight() const = 0;
/** Move column iterator to arbitrary site in genome -- effectively
* resetting the iterator (convenience function to avoid creation of
* new iterators in some cases).
* @param columnIndex position of column in forward genome coordinates
* @param lastIndex last column position (for iteration). must be greater
* than columnIndex */
virtual void toSite(hal_index_t columnIndex,
hal_index_t lastIndex) const = 0;
/** Use this method to bound iteration loops. When the column iterator
* is retrieved from the sequence or genome, the last column is specfied.
* toRight() cna then be called until lastColumn is true. */
virtual bool lastColumn() const = 0;
/** Get a pointer to the reference genome for the column iterator */
virtual const hal::Genome* getReferenceGenome() const = 0;
/** Get a pointer to the reference sequence for the column iterator */
virtual const hal::Sequence* getReferenceSequence() const = 0;
/** Get the position in the reference sequence */
virtual hal_index_t getReferenceSequencePosition() const = 0;
/** Get a pointer to the column map */
virtual const ColumnMap* getColumnMap() const = 0;
/** Get the index of the column in the reference genome's array */
virtual hal_index_t getArrayIndex() const = 0;
/** As we iterate along, we keep a column map entry for each sequence
* visited. This works out pretty well except for extreme cases (such
* as iterating over entire fly genomes where we can accumulate 10s of
* thousands of empty entries for all the different scaffolds when
* in truth we only need a handful at any given time). Under these
* circumstances, calling this method every 1M bases or so will help
* reduce memory as well as speed up queries on the column map. Perhaps
* this should eventually be built in and made transparent? */
virtual void defragment() const = 0;
protected:
friend class counted_ptr<ColumnIterator>;
friend class counted_ptr<const ColumnIterator>;
virtual ~ColumnIterator() = 0;
};
inline ColumnIterator::~ColumnIterator() {}
}
#ifndef NDEBUG
#include "halGenome.h"
namespace hal {
inline std::ostream& operator<<(std::ostream& os, ColumnIteratorConstPtr ci)
{
const ColumnIterator::ColumnMap* cmap = ci->getColumnMap();
for (ColumnIterator::ColumnMap::const_iterator i = cmap->begin();
i != cmap->end(); ++i)
{
os << i->first->getName() << ": ";
for (size_t j = 0; j < i->second->size(); ++j)
{
os << i->second->at(j)->getArrayIndex() << ", ";
}
os << "\n";
}
return os;
}
}
#endif
#endif
| true |
eac2e4671c7cf1a1c4c64d2e4c6b36bd366f745e | C++ | jb1361/Class-files-repo | /C343 Data Structures/CppDevSp17/L2P2/unittest1.cpp | UTF-8 | 8,712 | 2.9375 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include "wrapper.h"
#include "IntegerSequence.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace L2P2
{
TEST_CLASS(UnitTest1)
{
public:
// -----------------------------------------------------------------------------------
// add
// -----------------------------------------------------------------------------------
//! updates self
//! restores pos
//! clears x
//! requires: 0 <= pos <= |self|
//! ensures: self = #self[0, pos) * <#x> * #self[pos, |#self|)
// -----------------------------------------------------------------------------------
TEST_METHOD(UT05AddV1)
{
IntegerSequence s1;
Text x1;
Integer j, k;
Logger::WriteMessage(L"UT05AddV1: s1.add(j, k);");
Logger::WriteMessage(L"\tincoming: s1 = ([0,0,0,0,0],0) and j = 0 and k = 15");
Logger::WriteMessage(L"\toutgoing: s1 = ([15,0,0,0,0],1) and j = 0 and k = 0");
// Test set up and execute add
j = 0;
k = 15;
// Execute operation: add
s1.add(j, k);
// Verify ensures: self = #self[0, pos) * <#x> * #self[pos, |#self|)
toText(s1, x1);
Assert::IsTrue(x1 == "([15,0,0,0,0],1)", L"s1 = ([15,0,0,0,0],1)");
// Verify restores parameter mode: restores pos
Assert::IsTrue(j == 0, L"j = 0");
// Verify clears parameter mode: clears x
Assert::IsTrue(k == 0, L"k = 0");
} // UT05AddV1
// -----------------------------------------------------------------------------------
// remove
// -----------------------------------------------------------------------------------
//! updates self
//! restores pos
//! replaces x
//! requires: 0 <= pos < |self|
//! ensures: <x> = #self[pos, pos+1) and
//! self = #self[0, pos) * #self[pos+1, |#self|)
// -----------------------------------------------------------------------------------
TEST_METHOD(UT06RemoveV1)
{
IntegerSequence s1;
Text x1;
Integer j, k;
Logger::WriteMessage(L"UT06RemoveV1: s1.remove(j, k);");
Logger::WriteMessage(L"\tincoming: s1 = ([77,0,0,0,0],1) and j = 0 and k = 0");
Logger::WriteMessage(L"\toutgoing: s1 = ([0,0,0,0,0],0) and j = 0 and k = 77");
// Test set up
j = 0;
k = 77;
s1.add(j, k);
// Execute operation: remove
s1.remove(j, k);
// Verify ensures: <x> = #self[pos, pos+1)
Assert::IsTrue(k == 77, L"k = 77");
// Verify ensures: self = #self[0, pos) * #self[pos+1, |#self|)
toText(s1, x1);
Assert::IsTrue(x1 == "([0,0,0,0,0],0)", L"s1 = ([0,0,0,0,0],0)");
// Verify restores parameter mode: restores pos
Assert::IsTrue(j == 0, L"j = 0");
} // UT06RemoveV1
TEST_METHOD(UT06RemoveV2)
{
IntegerSequence s1;
Text x1;
Integer j, k;
Logger::WriteMessage(L"UT06RemoveV1: s1.remove(j, k);");
Logger::WriteMessage(L"\tincoming: s1 = ([77,76,75,74,73],5) and j = 0 and k = 0");
Logger::WriteMessage(L"\toutgoing: s1 = ([76,75,74,73,0],4) and j = 0 and k = 77");
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
j = 2;
k = 75;
s1.add(j, k);
j = 3;
k = 74;
s1.add(j, k);
j = 4;
k = 73;
s1.add(j, k);
j = 0;
// Execute operation: remove
s1.remove(j, k);
// Verify ensures: <x> = #self[pos, pos+1)
Assert::IsTrue(k == 77, L"k = 77");
// Verify ensures: self = #self[0, pos) * #self[pos+1, |#self|)
toText(s1, x1);
Assert::IsTrue(x1 == "([76,75,74,73,0],4)");
// Verify restores parameter mode: restores pos
Assert::IsTrue(j == 0, L"j = 0");
} // UT06RemoveV2
TEST_METHOD(UT06RemoveV3)
{
IntegerSequence s1;
Text x1;
Integer j, k;
Logger::WriteMessage(L"UT06RemoveV1: s1.remove(j, k);");
Logger::WriteMessage(L"\tincoming: s1 = ([77,76,75,74,73],5) and j = 0 and k = 0");
Logger::WriteMessage(L"\toutgoing: s1 = ([77,76,74,73,0],4) and j = 0 and k = 77");
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
j = 2;
k = 75;
s1.add(j, k);
j = 3;
k = 74;
s1.add(j, k);
j = 4;
k = 73;
s1.add(j, k);
j = 2;
// Execute operation: remove
s1.remove(j, k);
// Verify ensures: <x> = #self[pos, pos+1)
Assert::IsTrue(k == 75, L"k = 77");
// Verify ensures: self = #self[0, pos) * #self[pos+1, |#self|)
toText(s1, x1);
Assert::IsTrue(x1 == "([77,76,74,73,0],4)");
// Verify restores parameter mode: restores pos
Assert::IsTrue(j == 2, L"j = 2");
} // UT06RemoveV3
// -----------------------------------------------------------------------------------
// length
// -----------------------------------------------------------------------------------
//! restores self
//! ensures: length = |self|
// -----------------------------------------------------------------------------------
TEST_METHOD(UT11LengthV1)
{
IntegerSequence s1;
Text x1;
Logger::WriteMessage(L"UT11LengthV1: s1.length();");
Logger::WriteMessage(L"\tincoming: s1 = ([0,0,0,0,0],0)");
Logger::WriteMessage(L"\toutgoing: s1 = ([0,0,0,0,0],0)");
// Verify ensures: length = |self|
Assert::IsTrue(s1.length() == 0, L"|s1| = 0");
// Verify restores parameter mode: restores self
toText(s1, x1);
Assert::IsTrue(x1 == "([0,0,0,0,0],0)", L"s1 = ([0,0,0,0,0],0)");
} // UT11LengthV1
TEST_METHOD(UT11LengthV2)
{
IntegerSequence s1;
Text x1;
Integer j = 1;
Logger::WriteMessage(L"UT11LengthV1: s1.length();");
Logger::WriteMessage(L"\tincoming: s1 = ([1,0,0,0,0],1)");
Logger::WriteMessage(L"\toutgoing: s1 = ([1,0,0,0,0],1)");
s1.add(0, j);
// Verify ensures: length = |self|
Assert::IsTrue(s1.length() == 1, L"|s1| = 1");
// Verify restores parameter mode: restores self
toText(s1, x1);
Assert::IsTrue(x1 == "([1,0,0,0,0],1)");
} // UT11LengthV2
TEST_METHOD(UT06ClearV1)
{
IntegerSequence s1;
Text x1;
Integer j, k;
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
s1.clear();
toText(s1, x1);
Assert::IsTrue(x1 == "([0,0,0,0,0],0)");
}
TEST_METHOD(UT06ReplaceEntryV1)
{
IntegerSequence s1;
Text x1;
Integer j, k;
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
k = 5;
s1.replaceEntry(j, k);
toText(k, x1);
Assert::IsTrue(k == 76);
toText(s1, x1);
Assert::IsTrue(x1 == "([77,5,0,0,0],2)");
}
TEST_METHOD(UT11EntryV1)
{
IntegerSequence s1;
Text x1;
Integer j = 1;
s1.add(0, j);
// Verify ensures: length = |self|
Assert::IsTrue(s1.entry(j) == 1);
// Verify restores parameter mode: restores self
toText(s1, x1);
Assert::IsTrue(x1 == "([1,0,0,0,0],1)");
}
TEST_METHOD(UT11AppendV1)
{
IntegerSequence s1,s2;
Text x1;
Integer j = 1;
s1.add(0, j);
j = 2;
s2.add(0, j);
j = 3;
s2.add(1, j);
s1.append(s2);
toText(s1, x1);
Assert::IsTrue(x1 == "([1,2,3,0,0],3)");
toText(s2, x1);
Assert::IsTrue(x1 == "([0,0,0,0,0],0)");
}
TEST_METHOD(UT11AppendV2)
{
IntegerSequence s1, s2;
Text x1;
Integer j = 1;
s1.add(0, j);
j = 2;
s2.add(0, j);
j = 3;
s2.add(1, j);
j = 4;
s2.add(2, j);
j = 5;
s2.add(3, j);
s1.append(s2);
toText(s1, x1);
Assert::IsTrue(x1 == "([1,2,3,4,5],5)");
toText(s2, x1);
Assert::IsTrue(x1 == "([0,0,0,0,0],0)");
}
TEST_METHOD(UT11SplitV1)
{
IntegerSequence s1, s2;
Text x1;
Integer j;
j = 1;
s1.add(0, j);
j = 2;
s2.add(0, j);
j = 3;
s2.add(1, j);
j = 4;
s2.add(2, j);
s2.split(1, s1);
toText(s1, x1);
Assert::IsTrue(x1 == "([3,4,0,0,0],2)");
toText(s2, x1);
Assert::IsTrue(x1 == "([2,0,0,0,0],1)");
}
TEST_METHOD(UT11SplitV2)
{
IntegerSequence s1, s2;
Text x1;
Integer j;
j = 1;
s1.add(0, j);
j = 2;
s2.add(0, j);
j = 3;
s2.add(1, j);
j = 4;
s2.add(2, j);
j = 5;
s2.add(3, j);
j = 5;
s2.add(4, j);
s2.split(2, s1);
toText(s1, x1);
Assert::IsTrue(x1 == "([4,5,5,0,0],3)");
toText(s2, x1);
Assert::IsTrue(x1 == "([2,3,0,0,0],2)");
}
TEST_METHOD(UT06RemainingCapacityV1)
{
IntegerSequence s1;
Text x1;
Integer j, k;
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
Assert::IsTrue(s1.remainingCapacity() == 3);
}
TEST_METHOD(UT06EqualsV1)
{
IntegerSequence s1,s2;
Text x1;
Integer j, k;
// Test set up
j = 0;
k = 77;
s1.add(j, k);
j = 1;
k = 76;
s1.add(j, k);
s2 = s1;
toText(s2, x1);
Assert::IsTrue(x1 == "([77,76,0,0,0],2)");
}
};
} | true |
21f4802fbe3261a1b8a1f48cadfd684622f73a5e | C++ | strengthen/LeetCode | /C++/761.cpp | UTF-8 | 2,961 | 3.15625 | 3 | [
"MIT"
] | permissive | __________________________________________________________________________________________________
sample 4 ms submission
class Solution {
public:
string makeLargestSpecial(string S) {
// like finding and reordering parenthesis sequences, recursively
if (S.empty()) return "";
vector<string> sv;
int cnt = 0, i = 0;
for (int j = 0; j < S.size(); j++) {
if (S[j] == '1') cnt++;
else cnt--;
if (cnt == 0) {
string s = '1' + makeLargestSpecial(S.substr(i+1, j-i-1)) + '0';
sv.push_back(s);
i = j+1;
}
}
sort(sv.begin(), sv.end(), greater<string>());
string res = "";
for (auto &s : sv) res += s;
return res;
}
};
__________________________________________________________________________________________________
sample 8668 kb submission
class Solution {
using uint = unsigned long long;
public:
uint table[64];
uint size ;
string makeLargestSpecial(string S) {
table[1] = 1;
for (int i = 2; i < 64; i++)
table[i] = (table[i - 1] << 1) + 1;
uint s = transform(S);
size = S.size();
uint max = s;
while (1)
{
s = max;
int flag = 0;
for (int i = 0; i + 1 < size; i++)
{
auto val = s & (uint(1) << size - i - 1);
if (!val)
continue;
int cnt = 0;
for (int j = i + 1; j < size; j++)
{
auto val = s & (uint(1) << size - j);
if (val)
cnt++;
else
{
if (--cnt < 0)
break;
}
val = s & (uint(1) << size - j - 1);
if (!val)
{
continue;
}
if (cnt == 0)
{
int jcnt = 0;
for (int k = j + 1; k <= size; k++)
{
auto val = s & (uint(1) << size - k);
if (!val)
{
if (--jcnt < 0)
break;
}
else
++jcnt;
if (jcnt == 0)
{
uint tp = swap(s, i, j, k);
if (tp > max)
{
max = tp;
flag = 1;
}
}
}
}
}
}
if (!flag)
break;
}
return transform(max);
}
string transform(uint s)
{
string str;
str.resize(size);
for (uint i = 0; i < size; i++)
{
if (s & uint(1) << i)
str[size - i - 1] = '1';
else
str[size - i - 1] = '0';
}
return str;
}
uint swap(uint s, int x, int y, int z)
{
uint a = table[y - x];
uint b = table[z - y];
uint pa = a << (size - y);
uint pb = b << (size - z);
uint ia = ~pa;
uint ib = ~pb;
uint ga = (pa & s) >> (size - y);
uint gb = (pb & s) >> (size - z);
s = s & ia;
s = s & ib;
uint rr = (gb << (y - x)) + ga;
s = s | (rr << (size - z));
return s;
}
uint transform(string S)
{
uint ret = 0;
for (const auto c : S)
{
ret = ret << 1;
if (c == '1')
ret += 1;
}
return ret;
}
};
__________________________________________________________________________________________________
| true |
daee9e45976ed9a20fd4f4facad994176f39d972 | C++ | DOOMSTERR/My_DSA_Learning | /Data Structures and Algorithm (C++)/Program and Codes/1_to_14_Programming_Topics_and_Questions/13_b_Reverse_of_a_number.cpp | UTF-8 | 487 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("Input.txt", "r", stdin);
freopen("Output.txt", "w", stdout);
#endif
cout << "Enter a no to be reversed" << endl;
int n;
cin >> n;
cout << n << endl;;
int last_digit, rev = 0 ;
while(n>0){
last_digit = n%10;
rev = rev*10 + last_digit;
n=n/10;
}
cout << "Reversed no. is " << rev << endl;
return 0;
} | true |
0d9a400c03e89c347fbaf01d8d1eb7c311d1b28e | C++ | BrandonRTL/graph-alg | /include/Vectorgraph.h | UTF-8 | 1,655 | 2.765625 | 3 | [] | no_license | #ifndef __TGRAPH_H__
#define __TGRAPH_H__
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
class graph
{
public:
std::vector<int> adj;
std::vector<int> nums;
std::vector<float> data;
graph(std::string filename)
{
filename = "../../" + filename;
std::ifstream file(filename);
int num_row, num_col, num_lines;
int sum_adj = 0;
bool is_symetric = 0;
std::string title;
std::getline(file, title);
is_symetric = title.find("symmetric");
while (file.peek() == '%') file.ignore(2048, '\n');
file >> num_row >> num_col >> num_lines;
std::vector<std::vector<int>> temp_adj(num_row);
std::vector<std::vector<float>> temp_data(num_row);
for (int l = 0; l < num_lines; l++)
{
double data;
int row, col;
file >> row >> col >> data;
temp_adj[row - 1].push_back(col - 1);
temp_data[row - 1].push_back(data);
if (is_symetric)
{
temp_adj[col - 1].push_back(row - 1);
temp_data[col - 1].push_back(data);
}
}
file.close();
nums.push_back(0);
for (int i = 0; i < num_row; i++)
{
for (int j = 0; j < temp_adj[i].size(); j++)
{
adj.push_back(temp_adj[i][j]);
data.push_back(temp_data[i][j]);
sum_adj++;
}
nums.push_back(sum_adj);
}
// for (int i = 0; i < adj.size(); i++)
// std::cout << adj[i] << " ";
}
};
class subtree
{
public:
int parent;
int rank;
subtree(int pr = 0, int r = 0)
{
parent = pr;
rank = r;
}
};
int find(std::vector<subtree>& subsets, int i);
void tree_union(std::vector<subtree>& subsets, int a, int b);
void boruvkas_mst(graph gr);
int find_source_by_adj_number(graph& gra, int i);
#endif | true |
27d9a15cec1d672072ee3fdf1206a385bdb16baf | C++ | vandalo/Terraria | /2DGame/02-Bubble/02-Bubble/Skull.cpp | UTF-8 | 5,522 | 2.59375 | 3 | [] | no_license | #include <cmath>
#include <iostream>
#include <GL/glew.h>
#include <GL/glut.h>
#include "Skull.h"
#include "Game.h"
#define JUMP_ANGLE_STEP 4
#define JUMP_HEIGHT 40
#define FALL_STEP 0
#define M_PI 3.14159265358979323846264338327950288
enum SkullAnims
{
STAND_LEFT, STAND_RIGHT, MOVE_LEFT, MOVE_RIGHT
};
void Skull::init(const glm::ivec2 &tileMapPos, ShaderProgram &shaderProgram)
{
//Creem els sprites necesaris
spritesheet.loadFromFile("images/bub.png", TEXTURE_PIXEL_FORMAT_RGBA);
sprite = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
bracD1 = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
bracD2 = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
bracE1 = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
bracE2 = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
maD = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
maE = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.25, 0.25), &spritesheet, &shaderProgram);
rotateSprite = (float)M_PI;
rotateBracD1 = 0;
rotateBracD2 = 0;
rotateBracE1 = 0;
rotateBracE2 = 0;
rotateMaD = 0;
rotateMaE = 0;
tileMapDispl = tileMapPos;
velocitat = 1;
//Setejem posicio inicial
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posSkull.x), float(tileMapDispl.y + posSkull.y)));
bracD1->setPosition(glm::vec2(float(tileMapDispl.x + posBracD1.x), float(tileMapDispl.y + posBracD1.y)));
bracD2->setPosition(glm::vec2(float(tileMapDispl.x + posBracD2.x), float(tileMapDispl.y + posBracD2.y)));
bracE1->setPosition(glm::vec2(float(tileMapDispl.x + posBracE1.x), float(tileMapDispl.y + posBracE1.y)));
bracE2->setPosition(glm::vec2(float(tileMapDispl.x + posBracE2.x), float(tileMapDispl.y + posBracE2.y)));
maD->setPosition(glm::vec2(float(tileMapDispl.x + posMaD.x), float(tileMapDispl.y + posMaD.y)));
maE->setPosition(glm::vec2(float(tileMapDispl.x + posMaE.x), float(tileMapDispl.y + posMaE.y)));
}
void Skull::update(int deltaTime)
{
sprite->update(deltaTime);
bracD1->update(deltaTime);
bracD2->update(deltaTime);
bracE1->update(deltaTime);
bracE2->update(deltaTime);
maD->update(deltaTime);
maE->update(deltaTime);
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posSkull.x), float(tileMapDispl.y + posSkull.y)));
bracD1->setPosition(glm::vec2(float(tileMapDispl.x + posBracD1.x), float(tileMapDispl.y + posBracD1.y)));
bracD2->setPosition(glm::vec2(float(tileMapDispl.x + posBracD2.x), float(tileMapDispl.y + posBracD2.y)));
bracE1->setPosition(glm::vec2(float(tileMapDispl.x + posBracE1.x), float(tileMapDispl.y + posBracE1.y)));
bracE2->setPosition(glm::vec2(float(tileMapDispl.x + posBracE2.x), float(tileMapDispl.y + posBracE2.y)));
maD->setPosition(glm::vec2(float(tileMapDispl.x + posMaD.x), float(tileMapDispl.y + posMaD.y)));
maE->setPosition(glm::vec2(float(tileMapDispl.x + posMaE.x), float(tileMapDispl.y + posMaE.y)));
}
void Skull::render()
{
sprite->render(rotateSprite);
bracD1->render(rotateBracD1);
bracD2->render(rotateBracD2);
bracE1->render(rotateBracE1);
bracE2->render(rotateBracE2);
maD->render(rotateMaD);
maE->render(rotateMaE);
}
void Skull::setTileMap(TileMap *tileMap)
{
map = tileMap;
}
void Skull::setPosition(const glm::vec2 &pos)
{
posSkull = pos;
sprite->setPosition(glm::vec2(float(tileMapDispl.x + posSkull.x), float(tileMapDispl.y + posSkull.y)));
}
void Skull::setPositionBracD1(const glm::vec2 &pos)
{
posBracD1 = pos;
bracD1->setPosition(glm::vec2(float(tileMapDispl.x + posBracD1.x), float(tileMapDispl.y + posBracD1.y)));
}
void Skull::setPositionBracD2(const glm::vec2 &pos)
{
posBracD2 = pos;
bracD2->setPosition(glm::vec2(float(tileMapDispl.x + posBracD2.x), float(tileMapDispl.y + posBracD2.y)));
}
void Skull::setPositionBracE1(const glm::vec2 &pos)
{
posBracE1 = pos;
bracE1->setPosition(glm::vec2(float(tileMapDispl.x + posBracE1.x), float(tileMapDispl.y + posBracE1.y)));
}
void Skull::setPositionBracE2(const glm::vec2 &pos)
{
posBracE2 = pos;
bracE2->setPosition(glm::vec2(float(tileMapDispl.x + posBracE2.x), float(tileMapDispl.y + posBracE2.y)));
}
void Skull::setPositionMaD(const glm::vec2 &pos)
{
posMaD = pos;
maD->setPosition(glm::vec2(float(tileMapDispl.x + posMaD.x), float(tileMapDispl.y + posMaD.y)));
}
void Skull::setPositionMaE(const glm::vec2 &pos)
{
posMaE = pos;
maE->setPosition(glm::vec2(float(tileMapDispl.x + posMaE.x), float(tileMapDispl.y + posMaE.y)));
}
int Skull::getX(){
return posSkull.x;
}
int Skull::getY(){
return posSkull.y;
}
void Skull::setPatrullar(bool bpatrullar){
//patrullar = bpatrullar;
}
void Skull::setEsMouDreta(bool besMouDreta){
//esMouDreta = besMouDreta;
}
void Skull::setVida(int vidaSkull){
vida = vidaSkull;
}
void Skull::setRadiPatrulla(int radi){
//radiPatrulla = radi;
}
void Skull::setRadiPErseguir(int radi){
//radiPerseguir = radi;
}
void Skull::setInitPosition(glm::vec2 pos){
xInicial = pos[0];
yInicial = pos[1];
}
void Skull::setVelocitat(int vel){
velocitat = vel;
}
void Skull::doPatrullar(){
}
void Skull::doPatrullarWithJump(){
}
void Skull::doPerseguir(){
}
void Skull::doPerseguirWithJump(){
}
float Skull::getDistancia(glm::vec2 posPlayer, glm::vec2 posSkull){
return sqrt(pow(posPlayer[0] - posSkull[0], 2) + pow(posPlayer[1] - posSkull[1], 2));
}
| true |
8b77086b87cf50bbfc7f4dd817b666fb7537fab5 | C++ | Greenka2016/labs | /9/lab9.cpp | UTF-8 | 2,136 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int n;
int main()
{
setlocale(LC_ALL, "Rus");
cout << "Введите кол-во строк: ";
cin >> n;
cin.ignore();
ofstream f1("F1.txt");
if (!f1.is_open())
{
cout << "Файл не открыт" << endl;
return 0;
}
string str;
for (int i = 0; i < n; i++)
{
getline(cin, str);
f1 << str << "\n";
}
f1.close();
ifstream file("F1.txt");
if (!file.is_open())
{
cout << "Файл не открыт" << endl;
return 0;
}
cout << "Содержание файла F1" << endl;
for (int i = 0; i < n; i++)
{
getline(file, str);
cout << str << endl;
}
file.close();
ifstream f("F1.txt");
ofstream f2("F2.txt");
if (!f.is_open() && !f2.is_open())
{
cout << "Файлы не открыт " << endl;
return 0;
}
int r = 0;
for (int i = 0; i < n; i++)
{
bool flag = false;
getline(f, str);
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '0' || str[i] == '1' || str[i] == '2' || str[i] == '3' || str[i] == '4' || str[i] == '5' || str[i] == '6' || str[i] == '6' || str[i] == '7' || str[i] == '8' || str[i] == '9')
{
flag = true;
}
}
if (flag == false)
{
f2 << str << "\n";
r++;
}
}
f.close();
f2.close();
ifstream F2("F2.txt");
if (!F2.is_open())
{
cout << "Файлы не открыт " << endl;
return 0;
}
cout << "Содержание файла F2" << endl;
int k = 0;
for (int i = 0; i < r; i++)
{
getline(F2, str);
if (str[0] == 'A')
{
k++;
}
cout << str << endl;
}
F2.close();
ifstream file2("F2.txt");
if (!file2.is_open())
{
cout << "Файлы не открыт " << endl;
return 0;
}
cout << "Количество строк, которые начинаются на букву «А» в файле F2: " << k << endl;
file2.close();
return 0;
}
| true |
55c8e20316ccd42f9d9587c0c8b9b873a973b424 | C++ | anirudhsingla8/Coding_Problems_in_C--1 | /MonkandtheMagicalCandyBags.cpp | UTF-8 | 1,647 | 3.109375 | 3 | [] | no_license | //
// Created by aveorenzhio on 11/7/19.
//
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int length=0,heapsize;
void max_heapify(unsigned long long int arr[],int i)
{
int l=(2*i);
int r=(2*i+1);
int largest;
if(l<=heapsize && arr[l]>arr[i])
{
largest=l;
}
else
{
largest=i;
}
if(r<=heapsize && arr[r]>arr[largest])
{
largest=r;
}
if(largest==i)
return;
if(largest!=i)
{
int swap=arr[i];
arr[i]=arr[largest];
arr[largest]=swap;
}
max_heapify(arr,largest);
}
//void build_maxheap(unsigned long long int arr[])
//{
// for(int k=floor(heapsize/2);k>=1;k--)
// {
// max_heapify(arr,k);
// }
//}
void increase_value(unsigned long long int arr[], int i, int val)
{
arr[i]=val;
while(i>1 && arr[i/2]<arr[i])
{
int temp=arr[i/2];
arr[i/2]=arr[i];
arr[i]=temp;
i=i/2;
}
}
void insert_element(unsigned long long int arr[], int val)
{
length+=1;
increase_value(arr,length,val);
}
int main()
{
unsigned long long int arr[100000];
int queries;
cin>>queries;
long long int size,minutes;
for(int k=1,sum;k<=queries;k++)
{
sum=0;
length=0;
cin>>size>>minutes;
for(int i=1,val;i<=size;i++)
{
cin>>val;
insert_element(arr,val);
}
heapsize=length;
for(int i=1;i<=minutes;i++)
{
sum=sum+arr[1];
arr[1]=floor(arr[1]/2);
max_heapify(arr,1);
}
cout<<sum<<endl;
}
}
| true |
666ffd6648a7f7137c9618970ad6fa1ec3f0a03a | C++ | mxbossard/laperco-capteurs | /poc_esp32_lora/PoC lora module/src/main.cpp | UTF-8 | 1,014 | 2.828125 | 3 | [] | no_license | #include <Arduino.h>
#include <U8x8lib.h>
#include <Wire.h>
#define GREENLED (25)
#define OLED_RESET U8X8_PIN_NONE
#define OLED_SDA (21)
#define OLED_SCL (22)
U8X8_SSD1306_128X64_NONAME_HW_I2C display = U8X8_SSD1306_128X64_NONAME_HW_I2C(OLED_SCL, OLED_SDA, OLED_RESET);
uint8_t col = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
display.begin(); // initialize U8x8 text library for selected display module
display.setFont(u8x8_font_victoriabold8_r); // set text font (8x8 pixels)
delay(1000);
pinMode(GREENLED, OUTPUT);
Serial.println("Hello");
display.clear();
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(GREENLED, LOW);
Serial.println("Green LED off");
delay(100);
digitalWrite(GREENLED, HIGH);
Serial.println("Green LED on");
display.drawString(0, col, "Hello, Max !"); // print text to screen (column 0, row 0)
delay(100);
//display.clearLine(col);
//display.clear();
col = col + 1 % 8;
} | true |
f148e0cdc2c490ee6807a1e0b688327fa486da7c | C++ | AcademyOfInteractiveEntertainment/AIEYear1Samples | /AI_FollowPath/PathFollower.h | UTF-8 | 716 | 3 | 3 | [] | no_license | #pragma once
#include <vector>
#include <glm/glm.hpp>
class PathFollower
{
public:
PathFollower();
void Update(float deltaTime);
void Draw();
void AddPoint(glm::vec2 point) { m_path.push_back(point); }
void SetPosition(float x, float y) { m_position.x = x; m_position.y = y; }
private:
// array of points describing a closed path
std::vector<glm::vec2> m_path;
glm::vec2 m_position;
glm::vec2 m_velocity;
float m_speed;
float m_acceleration;
glm::vec2 m_debugClosest;
glm::vec2 m_debugTarget;
glm::vec2 GetClosestPointOnPath(int& segment);
glm::vec2 GetPointAlongPath(glm::vec2 pos, int segment, float distanceAhead);
};
| true |
8c92e4ceca820c9c9aed4b18a5fabb2591dcf14c | C++ | csimons1/CSCI4448 | /OOAD_HW2/Part C/main.cpp | UTF-8 | 842 | 2.59375 | 3 | [] | no_license | // Christian Simons
// CSCI4448 - Project 2
// Part C
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include "Animal.cpp"
#include "Feline.cpp"
#include "Cat.cpp"
#include "Tiger.cpp"
#include "Lion.cpp"
#include "Pachyderm.cpp"
#include "Rhino.cpp"
#include "Elephant.cpp"
#include "Hippo.cpp"
#include "Canine.cpp"
#include "Dog.cpp"
#include "Wolf.cpp"
#include "Zoo.cpp"
//#include "ZooKeeper.cpp" // Gone, moved to observer pattern as a subject
#include "IObserve.cpp" // Interfaces and implementations of observer pattern
using namespace std;
int main(void)
{
Zoo z;
// Modified for Observer pattern
ZooKeeper *Alfred = new ZooKeeper(z);
ZooAnnouncer Bob(Alfred);
Alfred->wakeUp();
Alfred->rollCall();
Alfred->feed();
Alfred->exercise();
Alfred->close();
return 0;
}
| true |
566e42a3bb901d6700b99bfbd225ab4eb0de9144 | C++ | FabianWiebe/competitive-programming | /4/exploration/solution.cpp | UTF-8 | 1,400 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
#include <utility>
#include <unordered_set>
#include <fstream>
int main (void) {
std::ios::sync_with_stdio(false);
// std::ifstream in("largeSample.in");
// // std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
// std::cin.rdbuf(in.rdbuf());
int total_number;
std::cin >> total_number;
std::vector<std::vector<int>> graph;
std::vector<int> in_counter;
while (--total_number >= 0) {
int station_no, connection_no;
std::cin >> station_no >> connection_no;
if (connection_no <= 0) {
continue;
}
graph.resize(station_no);
in_counter.resize(station_no);
for (auto graph_itr = graph.begin(); graph_itr != graph.end(); ++graph_itr) {
*graph_itr = std::vector<int>();
}
for (int i = 0; i < connection_no; ++i) {
int start, end;
std::cin >> start >> end;
graph.at(start).push_back(end);
++in_counter[end];
}
std::vector<int> no_entries;
int counter = 0;
for (auto & entries : in_counter) {
if (entries == 0) {
no_entries.push_back(counter);
}
++counter;
}
while (no_entries.size() > 0) {
auto val = no_entries.back();
no_entries.pop_back();
std::cout << val << std::endl;
for (auto & vertex : graph[val]) {
if (--in_counter[vertex] == 0) {
no_entries.push_back(vertex);
}
}
}
}
return 0;
} | true |
f53429aac6ea83fd924bf72508b1dd8349d37ec8 | C++ | KevinPolez/Evolution | /src/Map.cpp | ISO-8859-1 | 3,032 | 3.484375 | 3 | [] | no_license | #include "Map.h"
#include "Seed.h"
Map::Map(int width, int height) : width(width), height(height), mapSize(width*height)
{
this->createGenerator();
int index;
for (index = 0; index < mapSize; index++)
{
data.insert(std::pair<int,int>(index,0));
}
}
Map::~Map()
{
}
void Map::createGenerator()
{
generator.seed(evo::Seed::seed);
}
/**
* Gnre du bruit
*/
void Map::generateNoize(int minValue, int maxValue)
{
this->configureUniformRandomGenerator(minValue,maxValue);
std::map<int,int>::iterator itr;
for (itr = data.begin(); itr != data.end(); itr++)
{
itr->second = this->random();
}
}
/**
* Gnre un bruit gaussian
*/
void Map::generateGaussianNoize()
{
}
/**
* Gnre un dgrad entre une ligne de dpart et une ligne d'arrive
*/
void Map::generateGradiant(int startValue, int stopValue, int startLine, int stopLine)
{
std::map<int,int>::iterator itr;
int step = stopLine - startLine;
int diff = (int) (stopValue - startValue) / step;
for (itr = data.begin(); itr != data.end(); itr++)
{
if ( getLine(itr->first) >= startLine
&& getLine(itr->first) <= stopLine )
{
itr->second = startValue + ( (getLine(itr->first) - startLine) * diff);
}
}
}
/**
* Applique un algorthime cellulaire
*/
void Map::generateCellularAutomata(int step)
{
}
void Map::configureUniformRandomGenerator(int minValue, int maxValue)
{
uniformIntDistribution.param(std::uniform_int_distribution<int>::param_type(minValue,maxValue));
}
/**
* Fourni un nombre alatoire selon une distribution uniforme
*/
int Map::random()
{
return uniformIntDistribution(generator);
}
int Map::getWidth()
{
return this->width;
}
int Map::getHeight()
{
return this->height;
}
/**
* Fourni la valeur d'une case
*/
int Map::get(int index)
{
return this->data[index];
}
/**
* Determine la valeur d'une case
*/
void Map::set(int index, int value)
{
this->data[index] = value;
}
/**
* Fourni la taille de la carte
*/
int Map::getMapSize()
{
return this->mapSize;
}
/**
* Insere une valeur dans le tableau de data
*/
void Map::insert(std::pair<int,int> d)
{
this->data.insert(d);
}
/**
* fourni la ligne correspondante
*/
int Map::getLine(int index)
{
return (int) index / height;
}
/**
* Determine si la case est sur le bord de la carte
*/
bool Map::isEdge(int index)
{
if ( isNorthEdge(index)
|| isSouthEdge(index)
|| isEastEdge(index)
|| isWestEdge(index) ) return true;
return false;
}
bool Map::isNorthEdge(int index)
{
if ( index < this->height ) return true;
return false;
}
bool Map::isSouthEdge(int index)
{
if ( index > this->width * (this->height -1)) return true;
return false;
}
bool Map::isEastEdge(int index)
{
if ( (index + 1) % this->width == 0 ) return true;
return false;
}
bool Map::isWestEdge(int index)
{
if ( index % this->width == 0 ) return true;
return false;
}
| true |
2df84bf7d0124f9c89c56cdfb17c41287d050726 | C++ | OC-MCS/p2finalproject-01-andhartman | /game/Ship.h | UTF-8 | 325 | 2.5625 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
//class for the ship
class Ship {
private:
Sprite ship;
Texture shipTexture;
const float DISTANCE = 5.0;
public:
Ship(Vector2f);
void move();
Vector2f getPosition();
void setPosition(Vector2f);
Sprite& draw();
}; | true |
cab939b02105ac7842fb531017def21ac0dcf6f9 | C++ | yoonBot/Computer-Science-and-Engineering | /CSE3013: CSE Lab and Design 1/3. Introduction to C++ and OOP/Assignment/main.cpp | UTF-8 | 183 | 2.90625 | 3 | [
"MIT"
] | permissive | #include "Str.h"
using namespace std;
int main()
{
Str a("I'm a girl");
cout << a.contents();
a="I'm a boy\n";
cout << a.compare("I'm a a") << endl;
return 0;
}
| true |
d8d7b4167a1e4fef45866226f88276b6e2e58fbc | C++ | programmingNinja/Interview-questions | /WellOrderedPasswords/printPassword/printPassword.cpp | UTF-8 | 484 | 3.09375 | 3 | [] | no_license | // printPassword.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
void printPass(string digits, int startInd, string res,int length)
{
if(res.length() == 4)
{
cout<<res<<"\n";
res="";
}
if(startInd == length)
return;
printPass(digits, startInd+1, res+digits[startInd], length);
printPass(digits, startInd+1, res, length);
}
int main()
{
string digs = "0123456789";
printPass(digs, 0, "", 10);
getch();
return 0;
}
| true |
29915f4890318d663918bf929de1c688c0438050 | C++ | studious-octo-doodle/Programming-Tutorial-in-C- | /5WorkingWithStrings.cpp | UTF-8 | 1,283 | 3.8125 | 4 | [] | no_license | #include <iostream> //configuration option so we can write our program
using namespace std; //configuration option
int main () //function... container...any lines we put in this container will get executed
{
string phrase = "Giraffe Academy";
cout << "hello"; //does not start a new line
cout << "my name is" << endl; //ends line
cout << "C++ is fun\n"; //\n will also end a line
cout <<"See, I am a new line" <<endl;
cout << phrase << endl;
cout << phrase.length(); //string function- which is a block of code which can perform a task for us, we have a lot of string function option just put "." after the string
cout <<phrase[2] <<endl; //Access the third letter (counting starts at 0)
phrase[0] = 'y'; cout <<phrase << endl; //we are changing the first letter
//We are also able to get some information from a string
cout << phrase.find("Academy", 0) <<endl; //input 8 because Academy starts at index 8
cout << phrase.find("ffe", 0) <<endl;
cout <<phrase.substr(8, 3) <<endl; //allows you to take a subset of the string, starting index 8, and then grab 3 letters
string phrasesub;
phrasesub= phrase.substr(6,4);
cout<< phrasesub<<endl;
return 0; //should include... it works without it though, but add it
} | true |
8cd922b017e5ef4aa2a44cff1185d7d373b46601 | C++ | FatihBAKIR/fs | /src/src/disk_block_device.cpp | UTF-8 | 2,182 | 3.078125 | 3 | [] | no_license | //
// Created by Chani Jindal on 11/18/17.
//
#include <fs270/disk_block_dev.hpp>
#include <fcntl.h>
#include <unistd.h>
#include <stdexcept>
namespace fs
{
int disk_block_dev::write(disk_block_dev::sector_id_t id, const void *data) noexcept
{
auto ptr = reinterpret_cast<const char *>(data);
if( id < 0 )
return -1;
uint64_t byte_offset = get_block_offset(id);
if( ( byte_offset + disk_block_dev::m_blk_size ) >= disk_block_dev::m_capacity )
return -1;
lseek( fd, byte_offset, SEEK_SET );
::write( fd, ptr, m_blk_size );
return 0;
}
int disk_block_dev::read(disk_block_dev::sector_id_t id, void *data) noexcept
{
auto ptr = reinterpret_cast< char *>(data);
if( id < 0 )
return -1;
uint64_t byte_offset = get_block_offset(id);
if( ( byte_offset + disk_block_dev::m_blk_size ) >= disk_block_dev::m_capacity )
return -1;
lseek( fd, byte_offset, SEEK_SET );
::read(fd, ptr, m_blk_size );
return 0;
}
disk_block_dev::disk_block_dev(const std::string &path, size_t size, uint16_t block_size)
{
m_capacity = size;
m_blk_size = block_size;
fd = open(path.c_str(), O_RDWR | O_CREAT, 0644);
//ftruncate(fd, size);
if(fd == -1){
perror("open: ");
throw std::runtime_error("can't open device!");
}
if (lseek(fd, size, SEEK_SET) == -1){
close(fd);
throw std::runtime_error("can't seek device!");
}
char buf[4096 * 2];
std::fill(std::begin(buf), std::end(buf), 0);
if(::write(fd, buf, block_size) < 0){
close(fd);
throw std::runtime_error("can't write device!");
}
}
uint64_t disk_block_dev::get_block_offset(disk_block_dev::sector_id_t sector) noexcept
{
return uint64_t (sector) * m_blk_size;
}
uint16_t disk_block_dev::get_block_size() const noexcept
{
return m_blk_size;
}
disk_block_dev::~disk_block_dev()
{
//not sure what to do
close(fd);
}
}
| true |
4241b0e872019d8ecbe4b1f0233a9f5791d3a3ee | C++ | ccitllz/zertcore5 | /zertco5/utils/updatelist/DynamicList.h | UTF-8 | 3,492 | 2.78125 | 3 | [] | no_license | /*
* DynamicList.h
*
* Created on: 2015年8月7日
* Author: Administrator
*/
#ifndef ZERTCORE_UTILS_UPDATELIST_DYNAMICLIST_H_
#define ZERTCORE_UTILS_UPDATELIST_DYNAMICLIST_H_
#include <pch.h>
#include <utils/types.h>
namespace zertcore { namespace utils {
template <class Value, std::size_t Size>
class DynamicList
{
const static std::size_t CACHE_SIZE = 3;
public:
typedef Value value_type;
typedef array<value_type, Size> container_type;
typedef container_type* container_ptr;
typedef array<container_ptr, 3> cache_type;
public:
DynamicList() : head_list_(nullptr), tail_list_(nullptr), head_index_(0), tail_index_(0) {
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
head_cache_log_[i] = head_cache_[i] = nullptr;
}
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
tail_cache_log_[i] = tail_cache_[i] = nullptr;
}
cache_head_index_ = cache_tail_index_ = 0;
}
~DynamicList() {
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
if (head_cache_log_[i])
delete head_cache_log_[i];
}
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
if (tail_cache_log_[i])
delete tail_cache_log_[i];
}
}
public:
void prepareHead() {
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
head_cache_log_[i] = head_cache_[i] = new container_type;
}
cache_head_index_ = CACHE_SIZE;
fetchHead();
}
void prepareTail() {
for (std::size_t i = 0; i < CACHE_SIZE; ++i) {
tail_cache_log_[i] = tail_cache_[i] = new container_type;
}
cache_tail_index_ = CACHE_SIZE;
fetchTail();
}
public:
bool addHead(const value_type& v) {
spinlock_guard_type guard(head_lock_);
// ZC_ASSERT(head_list_);
if (head_index_ >= Size) {
return false;
}
(*head_list_)[head_index_++] = v;
return true;
}
bool addTail(const value_type& v) {
spinlock_guard_type guard(tail_lock_);
// ZC_ASSERT(tail_list_);
if (tail_index_ >= Size) {
return false;
}
(*tail_list_)[tail_index_++] = v;
return true;
}
public:
container_ptr getHead(std::size_t& size) {
spinlock_guard_type guard(head_lock_);
container_ptr list = head_list_;
size = head_index_;
if (!head_index_) {
return nullptr;
}
fetchHead();
return list;
}
container_ptr getTail(std::size_t& size) {
spinlock_guard_type guard(tail_lock_);
container_ptr list = tail_list_;
size = tail_index_;
if (!tail_index_) {
return nullptr;
}
fetchTail();
return list;
}
private:
void fetchHead() {
ZC_DEBUG_ASSERT(cache_head_index_ > 0);
head_list_ = head_cache_[--cache_head_index_];
head_index_ = 0;
}
void fetchTail() {
ZC_DEBUG_ASSERT(cache_tail_index_ > 0);
tail_list_ = tail_cache_[--cache_tail_index_];
tail_index_ = 0;
}
public:
void releaseHead(container_ptr p) {
ZC_DEBUG_ASSERT(cache_head_index_ < CACHE_SIZE);
head_cache_[cache_head_index_++] = p;
}
void releaseTail(container_ptr p) {
ZC_DEBUG_ASSERT(cache_tail_index_ < CACHE_SIZE);
tail_cache_[cache_tail_index_++] = p;
}
private:
container_ptr head_list_,
tail_list_;
std::size_t head_index_,
tail_index_;
spinlock_type head_lock_,
tail_lock_;
cache_type head_cache_, head_cache_log_,
tail_cache_, tail_cache_log_;
std::size_t cache_head_index_,
cache_tail_index_;
};
}}
#endif /* UTILS_UPDATELIST_DYNAMICLIST_H_ */
| true |
4314914ac0eda73f3a28ec7e05c0dfafa888e99f | C++ | nileshkulkarni/AI_lab | /logic/formula.cpp | UTF-8 | 3,000 | 3.203125 | 3 | [] | no_license | #include "formula.h"
void destroyAxiom1(formula *f){
//assert((f!=NULL) && (!f->leaf) && (f->rhs) && (f->lhs) && (f->rhs->leaf));
delete(f->rhs);
delete(f);
}
void destroyAxiom2(formula *f){
//assert((f!=NULL) && (!f->leaf) && (f->rhs) && (f->lhs) && (f->rhs->leaf));
delete((f->lhs)->rhs);
delete(f->lhs);
delete((f->rhs)->lhs);
delete((f->rhs)->rhs);
delete(f->rhs);
delete(f);
}
void destroyAxiom3(formula *f){
delete(f->lhs->lhs);
delete(f->lhs);
delete(f);
}
bool Axiom3Form(formula *f){
if(f==NULL) return false;
if(f->leaf) return false;
if((f->lhs)->leaf) return false;
return ((f->lhs->rhs->val == 'F') && (f->rhs->val == 'F'));
}
bool Axiom2lhsForm(formula *f){
if(f==NULL) return false;
if(f->leaf) return false;
return (!f->rhs->leaf);
}
void formula::input(istream &in) {
in>>val;
leaf = true;
length = 1;
s.push_back(val);
if(val == '-'){
lhs = new formula;
rhs = new formula;
lhs->input(in);
rhs->input(in);
leaf = false;
length = lhs->length + rhs->length;
s = s + lhs->s + rhs->s;
}
}
void formula::inputInfix(istream &in){
char a;
in>>a;
if(a=='('){
formula *f1 = new formula;
f1->inputInfix(in);
in>>a;
formula *f2 = new formula;
f2->inputInfix(in);
if(a=='|'){
lhs = implication(f1,F);
rhs = f2;
}
if(a=='&'){
lhs = implication(f1,implication(f2,F));
rhs = F;
}
if(a=='-'){
lhs = f1;
rhs = f2;
}
val = '-';
leaf = false;
length = lhs->length + rhs->length;
in>>a;
s ="-" + lhs->s + rhs->s;
assert(a==')');
}
else{
length = 1;
leaf = true;
val = a;
s = "";
s.push_back(val);
lhs = NULL;
rhs = NULL;
}
}
string formula::stringify(){
string s;
s.push_back(val);
if(leaf == false){
assert((lhs!=NULL) && (rhs!=NULL));
s = s + lhs->stringify() + rhs->stringify();
}
return s;
}
void formula::print(ostream &out){
if(leaf == true){
out<<val;
return;
}
out<<"(";
lhs->print(out);
out<<val;
rhs->print(out);
out<<")";
}
bool equal(formula *A , formula *B){
if(A==NULL && B==NULL) return true;
if(A==NULL || B==NULL) return false;
if(A->val == B->val){
return (equal(A->lhs , B->lhs) && equal(A->rhs , B->rhs));
}
return false;
}
bool operator==(const formula A ,const formula B){
if(A.val != B.val) return false;
bool ret = equal(A.lhs,B.lhs) && equal(A.rhs , B.rhs);
return ret;
}
formula *implication(formula *A , formula *B){
formula *ret = new formula;
ret->val = '-';
ret->leaf = false;
ret->lhs = A;
ret->rhs = B;
ret->length = A->length + B->length;
ret->s = "-" + A->s + B->s;
return ret;
}
formula *Axiom1(formula *A , formula *B){
return implication(A , implication(B , A));
}
formula *Axiom2(formula *A , formula *B , formula *C){
return implication(implication(A , implication(B , C)) , implication(implication(A , B) , implication(A , C)));
}
formula *Axiom3(formula *A){
return implication(implication(implication(A , F) ,F) , A);
}
| true |
bd1815b211c6622298c2ab0f6ecfaf1ef6226cc3 | C++ | dlxj/doc | /lang/programming/cpp/src/main.cpp | UTF-8 | 3,800 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<sstream>
#include<cstdlib>
#include "text_rank.h"
#include "sentence_rank.h"
#include "text_utils.h"
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 5)
{
cout << "Usage: " << argv[0] << " <input_file> <choose_field> <method> <out_file>" << endl;
cout << "<method>: 1 -> keywords; 2 -> key sentences" << endl;
cout << "<choose_field>: if keywords, set as token field; if key sentences, set as content field" << endl;
return -1;
}
string input_file(argv[1]);
int choose_field = atoi(argv[2]);
int method = atoi(argv[3]);
string out_file(argv[4]);
if (method != 1 && method != 2)
{
cout << "<method>: 1 -> keywords; 2 -> key sentences" << endl;
return -1;
}
ifstream fin(input_file.c_str());
if (!fin.is_open())
{
cout << "fail to open file: " << input_file << endl;
return -1;
}
ofstream fout(out_file.c_str());
if (!fin.is_open())
{
cout << "fail to open file: " << out_file << endl;
return -1;
}
int window_length = 3;
int max_iter_num = 100;
double d = 0.85;
double least_delta = 0.0001;
size_t topN = 5;
TextRank ranker(window_length, max_iter_num, d, least_delta);
SentenceRank sent_ranker(window_length, max_iter_num, d, least_delta);
if (method == 1)
{
string line;
vector<string> fields;
vector<string> token_vec;
vector<pair<string, double> > keywords;
vector<pair<string, double> > keywords2;
while(getline(fin, line))
{
TextUtils::Split(line, "\t", fields);
const string &token_str = fields[choose_field];
TextUtils::Split(token_str, " ", token_vec);
ranker.ExtractKeyword(token_vec, keywords, topN);
ranker.ExtractHighTfWords(token_vec, keywords2, topN);
for(size_t i = 0; i < keywords.size(); ++i)
{
if (i != 0)
fout << ' ';
fout << keywords[i].first << '(' << keywords[i].second << ')';
}
fout << '\t';
for(size_t i = 0; i < keywords2.size(); ++i)
{
if (i != 0)
fout << ' ';
fout << keywords2[i].first << '(' << keywords2[i].second << ')';
}
fout << '\t' << line << endl;
}
}
if (method == 2)
{
string line;
vector<string> fields;
vector<string> sent_vec;
vector<string> bigram_vec;
vector<pair<string, double> > key_sents;
bool is_utf8 = true;
while(getline(fin, line))
{
TextUtils::Split(line, "\t", fields);
const string &content = fields[choose_field];
TextUtils::SplitToSentence(content, g_seperator_str, sent_vec, is_utf8);
map<string, vector<string> > sentence_token_map;
for (size_t i = 0; i < sent_vec.size(); ++i)
{
//cout << "sent: " << sent_vec[i] << endl;
TextUtils::ExtractNgram(sent_vec[i], 2, is_utf8, bigram_vec);
if (bigram_vec.empty())
continue;
sentence_token_map.insert(make_pair(sent_vec[i], bigram_vec));
}
sent_ranker.ExtractKeySentence(sentence_token_map, key_sents, topN);
for(size_t i = 0; i < key_sents.size(); ++i)
{
if (i != 0)
fout << ' ';
fout << key_sents[i].first << '(' << key_sents[i].second << ')';
}
fout << '\t' << line << endl;
}
}
fin.close();
fout.close();
return 0;
}
| true |
31643a025df46b12232d69a490dfaf13d0937571 | C++ | valbok/twitcher.exmpl | /api/ITwitcher.h | UTF-8 | 1,037 | 3.09375 | 3 | [] | no_license | /**
* @author VaL Doroshchuk <valbok@gmail.com>
* @package Twitcher
*/
#pragma once
#include <string>
#include <vector>
#include <stdint.h>
namespace twitcher {
using PostTexts = std::vector<std::string>;
using Topics = std::vector<std::string>;
/**
* The twitcher service interface.
*
* This allows adding and deleting users, adding and retrieving posts
* and getting trending topics.
*/
class ITwitcher {
public:
virtual ~ITwitcher() {}
virtual void addUser(const std::string &userName) = 0;
virtual void addPost(const std::string &userName,
const std::string &postText,
uint64_t timestamp) = 0;
virtual void deleteUser(const std::string &userName) = 0;
virtual PostTexts getPostsForUser(const std::string &userName) const = 0;
virtual PostTexts getPostsForTopic(const std::string &topic) const = 0;
virtual Topics getTrendingTopics(uint64_t fromTimestamp,
uint64_t toTimestamp) const = 0;
};
} // namespace twitcher
| true |
600d4c00f838c47ecca7275f860e131263170a6b | C++ | smamir/oop-course | /Lab/Lab 2/621.cpp | UTF-8 | 3,214 | 3.515625 | 4 | [] | no_license | //Airline Reservations System
#include<iostream>
using namespace std;
int capacity[10] = {0};
int main()
{
int option,option2,total_seat=10,f=0,e=0;
while(total_seat>0)
{
cout<<"Please type 1 for 'first class'"<<endl;
cout<<"Please type 2 for 'economy'"<<endl;
cin>>option;
switch(option)
{
case 1:
for(int i=0;i<5;i++)
{
if(capacity[i]==0)
{
capacity[i]=1;
total_seat--;
f++;
cout<<"\n____boarding pass____"<<endl;
cout<<"Seat No. "<<i+1<<" "<<"Section: first class\n\n"<<endl;
break;
}
if(f==5)
{
cout<<"First class section is full."<<endl;
cout<<"Would you like to be transferred to economy?\n1 for Yes, 2 for no:";
cin>>option2;
if(option2==1)
{
for(int i=5;i<10;i++)
{
if(capacity[i]==0)
{
capacity[i]=1;
total_seat--;
e++;
cout<<"\n____boarding pass____"<<endl;
cout<<"Seat No. "<<i+1<<" "<<"Section: economy class\n\n"<<endl;
break;
}
if(e==5)
{
cout<<"No more seat available."<<endl;
break;
}
}
}
else if(option2==2)
{
cout<<"Next flight leaves in 3 hours."<<endl;
break;
}
}
}
break;
case 2:
for(int i=5;i<10;i++)
{
if(capacity[i]==0)
{
capacity[i]=1;
total_seat--;
e++;
cout<<"\n____boarding pass____"<<endl;
cout<<"Seat No. "<<i+1<<" "<<"Section: economy class\n\n"<<endl;
break;
}
if(e==5)
{
cout<<"Economy class section is full."<<endl;
break;
}
}
break;
default:
cout<<"\nWrong Input\n\n"<<endl;
}
if(total_seat==0)
cout<<"\n\nNo more seat on the plane!"<<endl;
}
return 0;
}
| true |
40035c2fa2f9b5e6cf901c06b5fda768626ad1e1 | C++ | idleyui/leetcode | /solution/0297_Serialize_and_Deserialize_Binary_Tree.cpp | UTF-8 | 2,426 | 3.140625 | 3 | [] | no_license | #include "alg.h"
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode *root) {
if (!root) return "";
queue<TreeNode *> q;
q.push(root);
string rt = "[";
TreeNode *next = nullptr, *last = root;
int level_size = q.size(), cnt = 0;
while (!q.empty()) {
auto node = q.front();
rt = rt + (node ? (to_string(node->val) + ",") : "null,");
if (node) {
q.push(node->left ? node->left : nullptr);
q.push(node->right ? node->right : nullptr);
if (node->left || node->right) next = node->right ? node->right : node->left;
}
q.pop();
if (node == last || ++cnt == level_size) {
if (!next) break;
last = next;
next = nullptr;
level_size = q.size();
cnt = 0;
}
}
// cout << rt;
return rt.substr(0, rt.size() - 1) + "]";
}
// Decodes your encoded data to tree.
TreeNode *deserialize(string data) {
if (data == "") return nullptr;
vector<TreeNode *> lst = _split(data.substr(1, data.size() - 2));
queue<TreeNode *> q;
q.push(lst[0]);
for (int i = 1; i < lst.size();) {
auto node = q.front();
if (!node) {
q.pop();
continue;
}
if (i >= lst.size()) break;
node->left = lst[i++];
q.push(node->left);
if (i >= lst.size()) break;
node->right = lst[i++];
q.push(node->right);
q.pop();
}
return lst[0];
}
vector<TreeNode *> _split(string s, string delimiter = ",") {
size_t pos = 0;
string token;
vector<TreeNode *> rt;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
if (token[0] == 'n') rt.push_back(nullptr);
else rt.push_back(new TreeNode(stoi(token)));
s.erase(0, pos + delimiter.length());
}
if (s[0] == 'n') rt.push_back(nullptr);
else rt.push_back(new TreeNode(stoi(s)));
return rt;
}
};
int main() {
for (int i = 0; i < 5; ++i) {
if (i < 5) {
if (i > 3) break;
}
cout << i;
}
} | true |
0399d8ef588d5bb3f38197642bae34531455639a | C++ | AxeAndBlanka/algorithms | /WeightedGraph/src/allSP.cpp | UTF-8 | 2,020 | 3.125 | 3 | [] | no_license | // All-pairs shortest paths, Dijkstra's algorithm
/*#include <vector>
#include "SPT.cpp"
#include "DenseGraphWeight.cpp"
template <class T>
class allSP
{
public:
allSP(const SparseGraphWeight<T>& g) :
g(g), a(g.V())
{
for (int i = 0; i < g.V(); ++i)
a[i] = new SPT<T>(g, i);
}
Edge<T>* pathR(int s, int t) const { return a[s]->pathR(); }
double dist(int s, int t) const { return a[s]->dist(t); }
private:
const SparseGraphWeight<T>& g;
std::vector< SPT<T>* > a;
};
//Floyd's algorithm
template <class T>
class allSPDense
{
public:
allSPDense(const DenseGraphWeight<T>& g) :
g(g), p(g.V()), d(g.V())
{
int V = g.V();
for (int i = 0; i < V; ++i)
{
p[i].reserve(V);
for (int j = 0; j < V; ++j)
p[i][j] = 0;
d[i].assign(V, V);
}
for (int s = 0; s < V; ++s)
for (int t = 0; t < V; ++t)
{
if (g.edge(s, t))
{
p[s][t] = g.edge(s, t);
d[s][t] = g.edge(s, t)->w();
}
for (int s = 0; s < V; ++s)
d[s][s] = 0;
for (int i = 0; i < V; ++i)
for (int s = 0; s < V; ++s)
if (p[s][i])
for (int t = 0; t < V; ++t)
if (s != t)
if (d[s][t] > d[s][i] + d[i][t])
{
p[s][t] = p[s][i];
d[s][t] = d[s][i] + d[i][t];
}
}
}
Edge<T>* path(int s, int t) const { return p[s][t]; }
double dist(int s, int t) const { return d[s][t]; }
private:
const DenseGraphWeight<T>& g;
std::vector< std::vector< Edge<T>* > > p;
std::vector< std::vector<double> > d;
};
#include <iostream>
int main()
{
int N, M;
std::cin >> N >> M;
int x, y, r;
SparseGraphWeight<int> gS(N, true);
for (int i = 0; i < M; ++i)
{
std::cin >> x >> y >> r;
Edge<int>* eS = new Edge<int>(x - 1, y - 1, r);
gS.addEdge(eS);
}
allSP<int> resS(gS);
int Q;
std::cin >> Q;
int a, b;
for (int i = 0; i < Q; ++i)
{
std::cin >> a >> b;
int r = resS.dist(a - 1, b - 1);
std::cout << r << std::endl;
}
}*/
| true |
052415a49c7cbeca9978c734a0a3deed7870eae0 | C++ | AleksandraPaustovskaya/HomeWork | /первый сем/3.3/3.3/3.3.cpp | UTF-8 | 2,636 | 3.34375 | 3 | [] | no_license | //Найти наиболее часто встречающийся элемент в массиве быстрее, чем за O(n2 ).
//Если таких элементов несколько, надо вывести любой из них.
#include <stdio.h>
int partition(int array[], int lo, int hi)
{
int pivot = array[hi];
int i = lo;
for (int j = lo; j < hi; j++)
{
if (array[j] <= pivot)
{
int swap = array[i];
array[i] = array[j];
array[j] = swap;
i = i++;
}
}
int swap = array[i];
array[i] = array[hi];
array[hi] = swap;
return i;
}
void sort(int array[], int start, int end)
{
if (start < end)
{
int p = partition(array, start, end);
sort(array, start, p - 1);
sort(array, p + 1, end);
}
}
void search(int array[], int size, int answer[])
{
for (int i = 1; i < size; i++)
{
int help = 1;
while (array[i] == array[i - 1])
{
help++;
if (answer[0] < help)
{
answer[0] = help;
answer[1] = array[i];
}
i++;
}
}
}
bool test()
{
int checkArray[100]{ 10, 50, 30, 0, 9, 4, 15, 10, 6, 0 };
sort(checkArray, 0, 9);
for (int i = 1; i < 10; i++)
{
if (checkArray[i - 1] > checkArray[i])
{
return false;
}
}
int answer[2]{1, checkArray[1]};
search(checkArray, 10, answer);
if (answer[0] != 2)
{
return false;
}
if (answer[1] != 0)
{
return false;
}
for (int i = 90; i >= 0; i--)
{
checkArray[90 - i] = i;
}
checkArray[0] = 0;
checkArray[10] = 0;
sort(checkArray, 0, 90);
for (int i = 1; i < 90; i++)
{
if (checkArray[i - 1] > checkArray[i])
{
return false;
}
}
search(checkArray, 90, answer);
if (answer[0] != 3)
{
return false;
}
if (answer[1] != 0)
{
return false;
}
for (int i = 0; i <= 50; i = i + 2)
{
checkArray[i] = 7;
}
sort(checkArray, 0, 90);
for (int i = 1; i < 90; i++)
{
if (checkArray[i - 1] > checkArray[i])
{
return false;
}
}
search(checkArray, 90, answer);
if (answer[0] != 27)
{
return false;
}
if (answer[1] != 7)
{
return false;
}
for (int i = 0; i <= 30; i++)
{
checkArray[i] = checkArray[i] % 8;
}
sort(checkArray, 0, 30);
for (int i = 1; i <= 30; i++)
{
if (checkArray[i - 1] > checkArray[i])
{
return false;
}
}
return true;
}
int main()
{
if (!test())
{
return 1;
}
printf("Enter size of array, please\n");
int size = 0;
scanf("%d", &size);
printf("Enter array, please\n");
int array[1000]{};
for (int i = 0; i < size; i++)
{
scanf("%d", &array[i]);
}
sort(array, 0, size - 1);
int answer[2]{1, array[0]};
search(array, size, answer);
printf("\n answer = %d \n", answer[1]);
return 0;
} | true |
b6b2acbf6d0eceacb3222844224440c00bd30575 | C++ | Straw-b/Cpp_Code | /test0730/test0730/test.cpp | GB18030 | 4,891 | 3.84375 | 4 | [] | no_license | #include <iostream>
using namespace std;
#if 0
// Student俴һѧȺ
struct Student
{
// ԣѧĻϢ
char _name[20];
char _gender[3];
int _age;
char _school[20];
void SetStudentInfo(char name[], char gender[], int age, char school[])
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
strcpy(_school, school);
}
void PrintStudentInfo()
{
cout << _name << "-" << _gender << "-" << _age << "-" << _school << endl;
}
// Ϊѧɶ
// Է˯ϿΡдҵԡ--->һ㶼ֵͨ
void Eat()
{
cout << "úóԷ" << endl;
}
void Sleep()
{
cout << "˯~~~" << endl;
}
};
int main()
{
Student s1, s2, s3; //
s1.SetStudentInfo("ܴ", "", 5, "");
s2.SetStudentInfo("ܶ", "ĸ", 4, "");
s3.SetStudentInfo("ǿ", "", 28, "ɭִѧ");
s1.PrintStudentInfo();
s2.PrintStudentInfo();
s3.PrintStudentInfo();
s1.Eat();
s1._age = 10;
s1.PrintStudentInfo();
return 0;
}
#endif
#if 0
class Student
{
private:
char _name[20];
char _gender[3];
int _age;
char _school[20];
public:
void SetStudentInfo(char name[], char gender[], int age, char school[])
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
strcpy(_school, school);
}
void PrintStudentInfo()
{
cout << _name << "-" << _gender << "-" << _age << "-" << _school << endl;
}
void Eat()
{
cout << "ú÷" << endl;
}
void Sleep()
{
cout << "ZZZ~~~" << endl;
}
};
int main()
{
Student s1, s2;
s1.SetStudentInfo("ܴ", "", 5, "");
s2.SetStudentInfo("ܶ", "ĸ", 4, "");
s1.PrintStudentInfo();
s2.PrintStudentInfo();
// s1._age = 10; // private Ա(ڡStudent)
return 0;
}
#endif
// C++4еľֲȫռ䡢
#if 0
void TestFunc()
{}
namespace N
{
void TestFunc(int a)
{}
}
class Test
{
public:
void TestFunc(double d)
{}
};
#endif
// еijԱֻԱʹãԱ൱Աȫֱ
#if 0
class Test
{
public:
void SetTest(int a)
{
_a = a;
cout << &_a << endl;
}
void PrintTest()
{
cout << _a << endl;
cout << &_a << endl;
}
private:
int _a;
// óԱȿSetTestʹãҲPrintTestʹ
// ˣԱͿԿԱȫֱ
};
// ע⣺ԱͿԿԱȫֱ---Ǻȫֱ
// ȫֱʹ֮ǰҪж
int g_a = 10; // ǰ
void TestFunc()
{
cout << g_a << endl;
}
int main()
{
Test t;
t.SetTest(10);
t.PrintTest();
TestFunc();
cout << g_a << endl;
return 0;
}
#endif
// һѧ
// ѧѧһȺ𣬿Խѧһµͣѧͬ
#if 0
class Student
{
public:
char _name[20];
char _gender[3];
int _age;
char _school[20];
public:
void SetStudentInfo(char name[], char gender[], int age, char school[])
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
strcpy(_school, school);
}
void PrintStudentInfo()
{
cout << _name << "-" << _gender << "-" << _age << "-" << _school << endl;
}
};
int main()
{
//Student._age = 10;
//ʧܣΪStudentһѧ𣬼
//ѧȺ𣺾--->û
//ͨѧͣѧʵ(ѧһѧ)һѧ֡Ա
Student s; // sʵĽsһѧ
s._age = 10;
return 0;
}
#endif
#if 1
class Student
{
public: // Ա
void SetStudentInfo(char name[], char gender[], int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void PrintStudentInfo()
{
cout << _name << "-" << _gender << "-" << _age << endl;
}
public: // Ա
char _name[20];
char _gender[3];
int _age;
};
int main()
{
Student s1, s2, s3;
// ҪStudentжҪ֪жЩԱ
s1.SetStudentInfo("ܴ", "", 5);
s2.SetStudentInfo("ܶ", "ĸ", 4);
s3.SetStudentInfo("ǿ", "", 28);
s1.PrintStudentInfo();
s2.PrintStudentInfo();
cout << sizeof(s1) << endl;
return 0;
}
#endif
| true |
cafcc24031951825cf8c57ec9a8118f5e1b62691 | C++ | olee12/uva_onlinejudge_solutions | /Codes/371 - Ackermann Functions.cpp | UTF-8 | 700 | 2.546875 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
long long int l,h;
long long int count=0,sum=0,i,j,k,max=0,n;
while(scanf("%lld %lld",&l,&h)==2 && l && h)
{
sum=0,max=0;
k=0;
if(l>h) l^=h^=l^=h;
for(i=l; i<=h; i++)
{
n=i;
count=0;
while(1)
{
if(n%2 != 0) n = 3*n+1;
else n/=2;
count++;
if(n==1) break;
}
if(count>k) sum=i,k=count;
}
printf("Between %lld and %lld, %lld generates the longest sequence of %lld values.\n",l,h,sum,k);
}
return 0;
}
| true |
e27d8ff69857da81fe2109d043c913b2dcb17ec2 | C++ | SvetlanaINBO318/labs | /laba6/main3.cpp | UTF-8 | 934 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
int age;
int nogi;
string food;
public:
Animal(int age,int nogi,string food) {
this->food=food;
this->age = age;
this->nogi = nogi;
}
virtual void action() = 0;
};
class Dog: public Animal {
private:
int speed_NAPADENIA;
public:
Dog(int age, int nogi, string food ,int speed_NAPADENIA) : Animal(age,nogi,food) {
this->speed_NAPADENIA = speed_NAPADENIA;
}
void action() {
cout << "RUN" << endl;
}
};
class Cat: public Animal {
private:
int OPASNOST;
public:
Cat(int age,int nogi,string food, int OPASNOST): Animal(age,nogi,food) {
this->OPASNOST=OPASNOST;
}
void action() {
cout << "WATCH" << endl;
}
};
| true |
1db8ec8d3b67c213c4a116601c3e6b7b6260d98b | C++ | colinxy/ProjectEuler | /Cpp/pe234.cpp | UTF-8 | 1,190 | 3.46875 | 3 | [] | no_license | /*
* poject euler 234: Semidivisible numbers
*
*/
#include <iostream>
#include <cmath>
#include "mathutil.h"
using namespace std;
using Mathutil::prime_under;
using Mathutil::sum;
const int64_t N = 999966663333L;
const int sqrtN = (int) sqrt(N);
int64_t subsum(int64_t p1, int64_t p2) {
int64_t p1_sq = p1*p1;
int64_t p2_sq = p2*p2;
int64_t p1_sum = sum(p1_sq + p1, p2_sq, p1);
int64_t p2_sum = sum(p1_sq - p1_sq % p2 + p2, p2_sq - p2, p2);
return p1_sum + p2_sum - 2 * p1 * p2;
}
int main() {
vector<int> primes;
primes.reserve(sqrtN);
prime_under(primes, sqrtN+1);
// cout << sqrtN << endl;
// cout << primes.size() << endl;
// cout << primes[primes.size()-1] << endl;
int64_t semidiv_sum(0);
for (size_t i = 0; i < primes.size()-1; ++i) {
semidiv_sum += subsum(primes[i], primes[i+1]);
}
// last prime 999983
// first prime after that is 1000003
// deal with extra
int64_t p1 = 999983;
int64_t p2 = 1000003;
// observation p1 * p2 < N
semidiv_sum += sum(p1*p1 + p1, N, p1);
semidiv_sum += sum(p1*p1 - p1*p1%p2 + p2, N, p2);
cout << semidiv_sum << endl;
return 0;
}
| true |
2027581f69a8a39af62dc08e8219c6ac56855b21 | C++ | L4WLI3T/Algorithm-Visualizer | /Home/ArrayHelper.cpp | UTF-8 | 461 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "GL/freeglut.h"
#include "GL/gl.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#include <unistd.h>
void randomizeArray(int* arr, int length)
{
for(int i = length - 1; i > 0; --i)
{
std::swap(arr[i], arr[rand() % (i+1)]);
}
}
void printArray(int* arr, int length)
{
for(int i = 0; i < length; ++i)
{
printf("%i", arr[i]);
if(i < length - 1)
{
printf(",");
}
}
printf("\n");
}
| true |
0468f55a5ed831f590c8375e9f9ef91b34d21fc7 | C++ | vikrant1433/coding | /leetcode/maximum-product-of-word-lengths/maximum-product-of-word-lengths.cpp | UTF-8 | 731 | 2.921875 | 3 | [] | no_license | using namespace std;
#include <bits/stdc++.h>
#define LL long long
#define MOD (1000000000+7)
class Solution {
public:
int maxProduct(vector<string>& w) {
vector<bitset<26> > v(w.size());
for(int i=0; i< v.size(); i++) {
for(char c: w[i]) v[i].set(c-'a');
}
int ans = 0;
for(int i = 0; i < w.size(); i++) {
for(int j = i+1; j < w.size(); j++) {
if((v[i]&v[j]).none()) ans = max(ans ,(int) w[i].size() * (int)w[j].size());
}
}
return ans;
}
};
int main(int argc, char const *argv[]) {
Solution s;
vector<string> v = {"abcw","baz","foo","bar","xtfn","abcdef"};
cout<<s.maxProduct(v)<<endl;;
return 0;
}
| true |
85fc8dc0e99bbbab869695c0005274ca87047c82 | C++ | LeeSuHa98/kumoh-code | /kumoh-code-2017/C++/#1 알고리즘/자료구조/#6 Linked List/4 - 3. 이중 연결 리스트 (낫 헤더)/IoHandler.h | UTF-8 | 435 | 2.8125 | 3 | [] | no_license | #pragma once
#include "BookList.h"
class IoHandler
{
public:
IoHandler() {}
~IoHandler() {}
// operations for menu handling
int getMenu();
void putMenu();
// operations for getting & putting object
Book* getBook();
// operations for getting or putting simple value
int getInteger(string msg);
string getString(string msg);
void putString(string msg) { cout << msg.c_str() << endl; }
void putNewLine() { cout << endl; }
}; | true |
76a500404aa60764a0709ff4012d00b489ba1649 | C++ | WonderCsabo/RPN-calculator | /image.cpp | UTF-8 | 1,354 | 3.34375 | 3 | [] | no_license | /**Image loading from files, and drawing to screen.**/
#include "image.hpp"
#include <graphics.hpp>
#include <fstream>
using namespace genv;
using namespace std;
std::vector<std::vector<std::vector<Color> > > Image::imgs;
Image::Image(vector<string> filenames)
{
vector<vector<Color> > v; //temp matrix for the actual image
for(unsigned int i=0; i<filenames.size(); i++)
{
ifstream f(filenames[i].c_str());
unsigned int n, m;
if(f)
{
f >> n >> m; // read the sizes
v.resize(m); // resizing the matrix
for (unsigned int i = 0; i < m; i++)
v[i].resize(n);
for (unsigned int i = 0; i < v.size(); i++)
for (unsigned int j = 0; j < v[i].size(); j++)
f >> v[i][j].R >> v[i][j].G >> v[i][j].B;
// read the 3 color components of the pixel
}
f.close();
imgs.push_back(v); //add the image the the vector
}
}
void Image::DrawImage(int x, int y, int type)
{
for (unsigned int i = 0; i < imgs[type].size(); i++)
for (unsigned int j = 0; j < imgs[type][i].size(); j++)
gout << move_to(j+x, i+y) // transpose the matrix
<< color(imgs[type][i][j].R, imgs[type][i][j].G, imgs[type][i][j].B)
<< dot;
// drawing the actual pixel
}
| true |
a4e70f05c20674eb8b8d40318b2735c12090f854 | C++ | WSJI0/BOJ | /1000-9999/1240.cpp | UTF-8 | 1,161 | 2.625 | 3 | [] | no_license | //1240 노드 사이의 거리
#include <bits/stdc++.h>
using namespace std;
unordered_map<int, vector<int>> graph;
int cost[1001][1001];
int bfs(int a, int b){
queue<pair<int, int>> q; q.push(pair<int, int>(a, 0));
unordered_map<int, bool> visited;
visited[q.front().first]=1;
while(!q.empty()){
pair<int, int> node=q.front(); q.pop();
for(int i=0; i<graph[node.first].size(); i++){
if(graph[node.first][i]==b){
return node.second+cost[node.first][graph[node.first][i]];
}
else if(!visited[graph[node.first][i]]){
q.push(pair<int, int>(graph[node.first][i], node.second+cost[node.first][graph[node.first][i]]));
visited[node.first]=1;
}
}
}
}
int main(void){
ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n, m, a, b, c;
cin>>n>>m;
for(int i=0; i<n-1; i++){
cin>>a>>b>>c;
graph[a].push_back(b);
graph[b].push_back(a);
cost[a][b]=c;
cost[b][a]=c;
}
while(m--){
int i, j;
cin>>i>>j;
cout<<bfs(i, j)<<"\n";
}
} | true |
0124fe05074734c60c18f14445d845905771d546 | C++ | songjihu/C_PTA | /B1022.cpp | UTF-8 | 523 | 2.578125 | 3 | [] | no_license | /*#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n = 0;
int i = 0, j = 0;
long long x1 = 0, x2 = 0, r = 0;
int x3 = 0;
int answer[100000];
for (i = 0; i < 100000; i++) {
answer[i] = 0;
}
scanf("%lld%lld%d", &x1, &x2, &x3);
r = x1 + x2;
i = 100000;
while (r != 0) {
i--;
answer[i] = r % x3;
r = r / x3;
}
if (i != 100000) {
for (; i < 100000; i++) {
printf("%d", answer[i]);
}
}
else
{
printf("0");
}
return 0;
}
*/ | true |
5e82778c91a4203f44394df8e3986b35cc4297f3 | C++ | Lhw-686/Study | /数据结构/2_栈和队列/3_顺序队列.cpp | GB18030 | 2,342 | 3.90625 | 4 | [] | no_license | #include <iostream>
#define MAXSIZE 100
using namespace std;
typedef int ElemType;
typedef struct{
ElemType data[MAXSIZE];
int front;
int rear;
}Queue;
void InitQueue(Queue &Q){
Q.front = Q.rear = 0;
}
bool isEmpty(Queue Q){
return Q.front == Q.rear;
}
bool Push(Queue &Q, ElemType e){
if(Q.rear + 1 == MAXSIZE) return false;
Q.data[++Q.rear] = e;
return true;
}
bool Pop(Queue &Q, ElemType &e){
if(isEmpty(Q)) return false;
e = Q.data[++Q.front];
return true;
}
bool GetHead(Queue Q, ElemType &e){
if(isEmpty(Q)) return false;
e = Q.data[Q.front+1];
return true;
}
int main(){
Queue Q;
bool run = true;
while (run){
cout << "====================" << endl;
cout << "1.InitQueue" << endl;
cout << "2.isEempty" << endl;
cout << "3.Push" << endl;
cout << "4.Pop" << endl;
cout << "5.GetHead" <<endl;
cout << "0.exit" << endl;
cout << "====================" << endl;
int order, i;
ElemType e;
bool flag;
cin >> order;
switch (order){
case 1:
InitQueue(Q);
cout << "ʼɹ" << endl;
break;
case 2:
cout << isEmpty(Q) << endl;
break;
case 3:
cout << "ҪӵԪֵ:";
cin >> e;
flag = Push(Q, e);
if(flag){
cout << "ӳɹ" << endl;
}else{
cout << "ʧܣ" << endl;
}
break;
case 4:
flag = Pop(Q, e);
if (flag){
cout << "ӳɹӵԪֵΪ" << e << endl;
}else{
cout << "ʧܣ" << endl;
}
break;
case 5:
flag = GetHead(Q, e);
if(flag){
cout << "ͷԪΪ" << e << endl;
}else{
cout << "ȡͷԪʧܣ" << endl;
}
break;
case 0:
run = false;
cout << "˳" << endl;
break;
default:
cout << "룡" << endl;
break;
}
}
return 0;
} | true |
9975f9cad0bc55a13556515634c8f78ae4c34095 | C++ | alantess/QtSimple | /integrate/signals/usr.h | UTF-8 | 1,304 | 2.875 | 3 | [
"MIT"
] | permissive | #ifndef USR_H
#define USR_H
#include <iostream>
#include <QObject>
#include <QString>
#include <QProperty>
#include <QDate>
class usr: public QObject
{
Q_OBJECT
//--> hide
Q_PROPERTY( QString name READ name WRITE setName NOTIFY nameChanged )
// We don't want to be able to change the age from QML, hence the read only age
// Further, notice that age is not an instance variable.
Q_PROPERTY( int age READ age NOTIFY ageChanged )
Q_PROPERTY( Role role READ role NOTIFY roleChanged )
Q_PROPERTY( bool loggedIn READ loggedIn WRITE setLoggedIn NOTIFY loginChanged )
public:
enum Role { Developer = 0, Tester = 1, ProjectManager = 2 };
Q_ENUM( Role )
//--> hide
explicit usr(const QString name = QString(), const QDate& birthday = QDate(), Role role = Developer);
QString name() const;
void setName(const QString& name );
int age() const;
Role role() const;
void setRole(Role);
bool loggedIn() const;
void setLoggedIn(bool loggedIn);
public slots:
void changeRole();
signals:
void nameChanged();
void ageChanged();
void roleChanged();
void loginChanged(bool loggedIn);
private:
QString m_name;
QDate m_birthDay;
Role m_role;
bool m_loggedIn = false;
//<-- hide
};
#endif // USR_H
| true |
cf3803e4b092104bef19ade1dc2c5ee343f099d9 | C++ | solecity/Flip_AndroidGame | /code/Credits_Scene.hpp | UTF-8 | 3,610 | 3.015625 | 3 | [] | no_license | /*
* MENU SCENE
* Copyright © 2020+ Mariana Moreira
*/
#ifndef CREDITS_SCENE_HEADER
#define CREDITS_SCENE_HEADER
#include <memory>
#include <basics/Atlas>
#include <basics/Canvas>
#include <basics/Point>
#include <basics/Scene>
#include <basics/Size>
#include <basics/Texture_2D>
#include <basics/Timer>
#include "Sprite.hpp"
using namespace basics;
using namespace std;
namespace flip
{
using basics::Atlas;
using basics::Canvas;
using basics::Point2f;
using basics::Size2f;
using basics::Graphics_Context;
using basics::Texture_2D;
class Credits_Scene : public basics::Scene
{
/**
* Represents the different scene states.
*/
enum State
{
LOADING,
READY
};
static const char * credits_path; ///< Path of the credits texture
static const char * button_path; ///< Path of the home button
private:
State state; ///< Scene state
bool suspended; ///< true - when the scene is working on background and vice versa
unsigned canvas_width; ///< Width of the window where the scene is drawn
unsigned canvas_height; ///< Height of the window where the scene is drawn
shared_ptr< Texture_2D > credits_texture; ///< Texture with the credits image
shared_ptr< Texture_2D > button_texture; ///< Texture with the home button image
shared_ptr< Sprite > home_button; ///< Home button sprite
public:
/**
* Only initialize the attributes that must be initialized the first time when the scene is created from scratch.
*/
Credits_Scene ();
/**
* This method calls the Directory to know the screen resolution of the scene
* @return size in coordinates that the scene is using
*/
basics::Size2u get_view_size () override
{
return { canvas_width, canvas_height };
}
/**
* Initiate all attributes that need to be loaded every time this scene starts
* @return
*/
bool initialize () override;
/**
* This method calls the Directory when the scene changes to second plan
*/
void suspend () override
{
suspended = true;
}
/**
* This method calls the Directory when the scene changes to first plan
*/
void resume () override
{
suspended = false;
}
/**
* This method is automatically invoked once per frame when events directed to the scene are accumulated.
*/
void handle (basics::Event & event) override;
/**
* This method is automatically invoked once every frame so the scene can update its state
*/
void update (float time) override;
/**
* This method is automatically invoked once every frame so the scene draws its content
*/
void render (Graphics_Context::Accessor & context) override;
};
}
#endif
| true |
2a444ae0bd8daf62aab6caa0878e90721de76544 | C++ | VadosLight/interpreter | /executor.cpp | WINDOWS-1251 | 2,075 | 3 | 3 | [] | no_license | /*
Executor.cpp
, .
*/
#include "stdafx.h"
#include "executor.h"
#include "name_table.h"
#include "label_table.h"
#include "lexical_analizer.h"
#include "commands.h"
void register_commands() {
// name_table.cpp
NT.RegisterCommand("FOR",new CmdFor);
NT.RegisterCommand("GOTO",new CmdGoto);
NT.RegisterCommand("IF",new CmdIf);
NT.RegisterCommand("INPUT",new CmdInput);
NT.RegisterCommand("LET",new CmdExpression);
NT.RegisterCommand("NEXT",new CmdNext);
NT.RegisterCommand("PRINT",new CmdPrint);
}
//
bool execute_command(Parser &parser) {
Lexem lex = parser.get_last();
if ( lex.type == LT_End )
return false;
switch(lex.type) {
case LT_Identifier:
{
if (!NT.ProcessCommand(parser))
throw "Can't process command";
}
break;
case LT_EOL:
parser.get_lexem();
break;
case LT_Number:
parser.get_lexem();
break;
default:
throw "Very Sad syntax";
}
return true;
}
//
void scan_for_labels(Parser& parser)
{
bool prev_lexem_is_EOL(true);
while (parser.get_lexem().type != LT_End) {
if ( prev_lexem_is_EOL && parser.get_last().type == LT_Number ) {
unsigned int label(static_cast<unsigned int>(parser.get_last().value));
parser.get_lexem();
LT.AddLabel(label,parser.Hold());
}
prev_lexem_is_EOL = (parser.get_last().type == LT_EOL);
}
}
//
void execute_script(std::istream& in) {
//
register_commands();
Parser parser(in);
//
scan_for_labels(parser);
parser.Reset();
parser.get_lexem();
while (execute_command(parser));
std::cout << "End of the program" << std::endl;
}
| true |
12edac0681bf3ddd881cab7327258b4ccc4be2fd | C++ | sunshinenny/Study-Practice | /大一实训-制作外卖系统-C语言/Search.cpp | GB18030 | 891 | 2.65625 | 3 | [] | no_license | #include"Type.h"
#include"Function.h"
//----------------------------------------------
int Search_o_ID(SqList L,string e)// Ųѯ
{
int i;int f=0;
for(i=0;i<L.length;i++)
{
if(e==L.elem[i].M.o_ID)
{PrintList(L,i);f=1;break;}
}
if(i==L.length&&f==0)
cout<<"ûд˶"<<endl<<endl;
return i;
}
int Search_p_name(SqList L,string e)//ѯ
{
int i;int f=0;
for(i=0;i<L.length;i++)
{
if(e==L.elem[i].M.p_name)
{PrintList(L,i);f=1;}
}
if(i==L.length&&f==0)
cout<<"ûд˶"<<endl<<endl;
}
int Search_p_phone(SqList L,string e)//˵ĵ绰ѯ
{
int i;int f=0;
for(i=0;i<L.length;i++)
{
if(e==L.elem[i].M.p_phone)
{PrintList(L,i);f=1;}
}
if(i==L.length&&f==0)
cout<<"ûд˶"<<endl<<endl;
}
| true |
5a3add7508b8fbf6c5623574119bf937e68f8a0b | C++ | oliverxyy/gem5-source-code-learning | /src/mem/protocol/DMA_State.cc | UTF-8 | 1,771 | 2.9375 | 3 | [] | no_license | /** \file DMA_State.hh
*
* Auto generated C++ code started by /home/oliverxyy/program/gem5-stable/src/mem/slicc/symbols/Type.py:550
*/
#include <cassert>
#include <iostream>
#include <string>
#include "base/misc.hh"
#include "mem/protocol/DMA_State.hh"
using namespace std;
// Code to convert the current state to an access permission
AccessPermission DMA_State_to_permission(const DMA_State& obj)
{
switch(obj) {
case DMA_State_READY:
return AccessPermission_Invalid;
case DMA_State_BUSY_RD:
return AccessPermission_Busy;
case DMA_State_BUSY_WR:
return AccessPermission_Busy;
default:
panic("Unknown state access permission converstion for DMA_State");
}
}
// Code for output operator
ostream&
operator<<(ostream& out, const DMA_State& obj)
{
out << DMA_State_to_string(obj);
out << flush;
return out;
}
// Code to convert state to a string
string
DMA_State_to_string(const DMA_State& obj)
{
switch(obj) {
case DMA_State_READY:
return "READY";
case DMA_State_BUSY_RD:
return "BUSY_RD";
case DMA_State_BUSY_WR:
return "BUSY_WR";
default:
panic("Invalid range for type DMA_State");
}
}
// Code to convert from a string to the enumeration
DMA_State
string_to_DMA_State(const string& str)
{
if (str == "READY") {
return DMA_State_READY;
} else if (str == "BUSY_RD") {
return DMA_State_BUSY_RD;
} else if (str == "BUSY_WR") {
return DMA_State_BUSY_WR;
} else {
panic("Invalid string conversion for %s, type DMA_State", str);
}
}
// Code to increment an enumeration type
DMA_State&
operator++(DMA_State& e)
{
assert(e < DMA_State_NUM);
return e = DMA_State(e+1);
}
| true |
7134711a51f78c115f8644a13f4413aecfe2eda4 | C++ | hihihippp/TimedText | /test/Text/TestStringBuilder.cpp | UTF-8 | 12,663 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive | //
// Copyright (c) 2013 Caitlin Potter and Contributors
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include <TimedText/StringBuilder.h>
#include <gtest/gtest.h>
using namespace TimedText;
// Make sure that we aren't allocating anything when constructing
// with the default constructor.
TEST(StringBuilder,InitializeEmpty)
{
StringBuilder sb;
EXPECT_EQ(&StringBuilder::empty, sb.d);
}
// Make sure we allocate the correct ammount when constructing
// with the capacity constructor. (The length should be zero)
TEST(StringBuilder,InitializeWithCapacity)
{
bool result;
StringBuilder sb(500,result);
EXPECT_TRUE(result);
EXPECT_EQ(500,sb.capacity());
EXPECT_EQ(0,sb.length());
}
TEST(StringBuilder,InitializeWithString)
{
String string("Hello, world!");
bool result;
StringBuilder sb(string, result);
EXPECT_TRUE(result);
EXPECT_STREQ("Hello, world!", string.text());
EXPECT_EQ(13, sb.length());
}
TEST(StringBuilder,ResizeData)
{
StringBuilder sb;
EXPECT_TRUE(sb.resizeData(100));
EXPECT_LE(100, sb.capacity());
EXPECT_EQ(100, sb.length());
EXPECT_TRUE(sb.resizeData(200));
EXPECT_LE(200, sb.capacity());
EXPECT_EQ(200, sb.length());
EXPECT_TRUE(sb.resizeData(-1));
EXPECT_GE(16, sb.capacity());
EXPECT_EQ(0, sb.length());
}
TEST(StringBuilder,Reserve)
{
StringBuilder sb;
EXPECT_TRUE(sb.reserve(100));
EXPECT_EQ(100, sb.capacity());
EXPECT_EQ(0, sb.length());
}
TEST(StringBuilder,Expand)
{
char expectedText[] =
" "
" "
" "
" ";
StringBuilder sb;
// Expanding by 100 is essentially like appending 100 spaces
// to the end of the buffer
EXPECT_TRUE(sb.expand(100));
EXPECT_EQ(101, sb.length());
//EXPECT_EQ('\0', sb.text()[100]);
EXPECT_STREQ(expectedText, sb.text());
}
TEST(StringBuilder,SetText)
{
String notEmpty("Hello, world!");
String empty("", 0);
StringBuilder sb;
EXPECT_TRUE(sb.setText(notEmpty));
EXPECT_EQ(13, sb.length());
EXPECT_STREQ("Hello, world!", sb.text());
EXPECT_TRUE(sb.setText(empty));
EXPECT_EQ(0, sb.length());
EXPECT_STREQ("", sb.text());
}
// Check that append operation works correctly
TEST(StringBuilder,Append)
{
bool result;
StringBuilder sb(128,result);
EXPECT_TRUE(result);
EXPECT_TRUE(sb.append("Phnglui"));
EXPECT_EQ(7, sb.length());
EXPECT_TRUE(sb.append(' '));
EXPECT_EQ(8, sb.length());
EXPECT_TRUE(sb.append("mglw nafh Cthulhu R'lyeh wgah nagl", -1));
EXPECT_EQ(42, sb.length());
EXPECT_TRUE(sb.append(" fhtag", 6));
EXPECT_EQ(48, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtag", sb.text());
EXPECT_TRUE(sb.append('n'));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.append(NULL, 0));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
}
TEST(StringBuilder,Prepend)
{
bool result;
StringBuilder sb(128, result);
EXPECT_TRUE(result);
EXPECT_TRUE(sb.prepend(" fhtagn"));
EXPECT_EQ(7, sb.length());
EXPECT_STREQ(" fhtagn", sb.text());
EXPECT_TRUE(sb.prepend(" wgah nagl", -1));
EXPECT_EQ(17, sb.length());
EXPECT_STREQ(" wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.prepend("hnglui mglw nafh Cthulhu R'lyeh", 31));
EXPECT_EQ(48, sb.length());
EXPECT_STREQ("hnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.prepend('P'));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.prepend(NULL, 0));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
}
TEST(StringBuilder,Insert)
{
bool result;
StringBuilder sb(128, result);
EXPECT_TRUE(sb.insert(0, "Phnglui nafh wgah fhtagn"));
EXPECT_EQ(24, sb.length());
EXPECT_STREQ("Phnglui nafh wgah fhtagn", sb.text());
EXPECT_TRUE(sb.insert(8, "mglw ", -1));
EXPECT_EQ(29, sb.length());
EXPECT_STREQ("Phnglui mglw nafh wgah fhtagn", sb.text());
EXPECT_TRUE(sb.insert(18, "thulhu R'lyeh ", 14));
EXPECT_EQ(43, sb.length());
EXPECT_STREQ("Phnglui mglw nafh thulhu R'lyeh wgah fhtagn", sb.text());
EXPECT_TRUE(sb.insert(18, 'C'));
EXPECT_EQ(44, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah fhtagn", sb.text());
EXPECT_TRUE(sb.insert(38, "nagl "));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.insert(40,NULL,0));
EXPECT_EQ(49, sb.length());
EXPECT_STREQ("Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
EXPECT_TRUE(sb.insert(-1,"Hello!"));
EXPECT_TRUE(sb.insert(0,"",0));
EXPECT_TRUE(sb.insert(0, sb.text(), 8));
EXPECT_STREQ("Phnglui Phnglui mglw nafh Cthulhu R'lyeh wgah nagl fhtagn", sb.text());
StringBuilder s2(3200, result);
EXPECT_TRUE(result);
char tmp[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char insert[] = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba";
char expected[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char expected2[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
EXPECT_TRUE(s2.insert(0, tmp));
EXPECT_EQ(208,s2.length());
EXPECT_TRUE(s2.insert(208,tmp));
EXPECT_EQ(416,s2.length());
EXPECT_TRUE(s2.insert(208, insert));
EXPECT_EQ(624,s2.length());
EXPECT_STREQ(expected, s2.text());
EXPECT_TRUE(s2.insert(312,s2.text(), s2.length()));
EXPECT_STREQ(expected2, s2.text());
EXPECT_EQ(1248, s2.length());
}
TEST(StringBuilder,IndexOf)
{
bool result;
StringBuilder sb(String("Hello, World!"), result);
EXPECT_TRUE(result);
EXPECT_EQ(-1, sb.indexOf(NULL, 0, 0));
EXPECT_EQ(-1, sb.indexOf("Hello", 5, 5));
EXPECT_EQ(-1, sb.indexOf('H', 5));
EXPECT_EQ(2, sb.indexOf("llo", -1));
EXPECT_EQ(5, sb.indexOf(','));
EXPECT_EQ(7, sb.indexOf(String("World!")));
EXPECT_EQ(-1, sb.indexOf("World!!", 7));
EXPECT_EQ(-1, sb.indexOf(""));
}
TEST(StringBuilder,ReplaceAllNOOP)
{
// Test that we don't do anything on null ops
StringBuilder sb; // Empty
EXPECT_TRUE(sb.replaceAll("Foo", "Bar"));
const char *sameSearchAndReplace = "Foo";
EXPECT_TRUE(sb.replaceAll(sameSearchAndReplace,sameSearchAndReplace));
}
TEST(StringBuilder,ReplaceAllEqualLengths)
{
bool result;
// Replacement and search string equal lengths (best case)
StringBuilder sb(30000,result);
EXPECT_TRUE(result);
StringBuilder sb2(30000,result);
EXPECT_TRUE(result);
sb.append("Hello, Waldo");
sb2.append("Hello, Doggy");
for(int i=0; i<2048; ++i) {
EXPECT_TRUE(sb.insert(0, "Hello, Waldo"));
EXPECT_TRUE(sb2.insert(0, "Hello, Doggy"));
}
EXPECT_TRUE(sb.replaceAll("Waldo","Doggy"));
EXPECT_EQ(sb2.length(), sb.length());
EXPECT_STREQ(sb2.text(), sb.text());
}
TEST(StringBuilder,ReplaceAllSmallerSearch)
{
// Replacement smaller than search string (middle case)
bool result;
StringBuilder sb(30000,result);
EXPECT_TRUE(result);
StringBuilder sb2(30000,result);
EXPECT_TRUE(result);
sb.append("Hello Tortoise");
sb2.append("Hello Donkey");
for(int i=0; i<2048; ++i) {
EXPECT_TRUE(sb.insert(0, "Hello, Tortoise"));
EXPECT_TRUE(sb2.insert(0, "Hello, Donkey"));
}
EXPECT_TRUE(sb.replaceAll("Tortoise", "Donkey"));
EXPECT_EQ(sb2.length(), sb.length());
EXPECT_STREQ(sb2.text(), sb.text());
}
TEST(StringBuilder,ReplaceAllBiggerSearch)
{
// Replacement larger than search string (worst case)
bool result;
StringBuilder sb(30000,result);
EXPECT_TRUE(result);
StringBuilder sb2(30000,result);
EXPECT_TRUE(result);
sb.append("Hello World");
sb2.append("Hello Donkey");
for(int i=0; i<2048; ++i) {
EXPECT_TRUE(sb.insert(0, "Hello World"));
EXPECT_TRUE(sb2.insert(0, "Hello Donkey"));
}
EXPECT_TRUE(sb.replaceAll("World", "Donkey"));
EXPECT_STREQ(sb2.text(), sb.text());
}
TEST(StringBuilder,ReplaceAllUCS4Replacement)
{
// Search for string, replace with UCS4 character
bool result;
StringBuilder sb(64, result);
EXPECT_TRUE(result);
EXPECT_TRUE(sb.append("Hello, World!"));
EXPECT_TRUE(sb.replaceAll("Hello", 0x55E8));
EXPECT_TRUE(sb.replaceAll("World", 0x4E16));
EXPECT_EQ(9, sb.length());
EXPECT_STREQ("\xe5\x97\xa8, \xe4\xb8\x96!", sb.text());
}
TEST(StringBuilder,ReplaceAllUCS4Search)
{
// Search for UCS4 character, replace with string
bool result;
StringBuilder sb(64, result);
EXPECT_TRUE(result);
EXPECT_TRUE(sb.append("\xe5\x97\xa8, \xe4\xb8\x96!"));
EXPECT_TRUE(sb.replaceAll(0x55E8, "Hello"));
EXPECT_TRUE(sb.replaceAll(0x4E16, "World"));
EXPECT_EQ(13, sb.length());
EXPECT_STREQ("Hello, World!", sb.text());
}
TEST(StringBuilder,ReplaceAllUCS4)
{
// Search for UCS4 character, replace with UCS4 character
bool result;
StringBuilder sb(64, result);
EXPECT_TRUE(result);
EXPECT_TRUE(sb.append("\xe5\xa5\xbd\xe5\xa4\xa9")); // 好天
EXPECT_TRUE(sb.replaceAll(0x597D,0x574F)); // 坏天
EXPECT_EQ(6, sb.length());
EXPECT_STREQ("\xe5\x9d\x8f\xe5\xa4\xa9", sb.text());
}
| true |
68cea9d1d65714f90f2d078ad35a4aa8b7f1d95e | C++ | tmothupr/tacitpixel | /include/tp/stack.h | UTF-8 | 5,270 | 2.9375 | 3 | [
"BSD-2-Clause",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | /*
* Copyright (C) 1999-2013 Hartmut Seichter
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef TPSTACK_H
#define TPSTACK_H 1
#include <tp/types.h>
/**
\brief a simple stack container
The tpStack container is a substitute to STL stack.
It has a different API but
Performance issues are tackled.
*/
template <typename T> class tpStack {
public:
typedef T element_type;
typedef T* iterator;
typedef const T* const_iterator;
static const tpUInt element_size = sizeof(T);
//! standard constructor.
tpStack();
//! copy constructor
tpStack(const tpStack& stack);
//! d'tor
~tpStack();
/**
\brief put value on the top of the stack
\param val value to be copied on the top of the stack.
Copies the value on top of the stack. It also increments
the preoccupied memory space on request.
*/
void push(T val);
/**
\brief removes value from the top of the stack
\return returns the value of the top element
Copies the value of the top element of the stack
and removes it from the stack.
*/
void pop();
/**
\brief copies the value of the top of the stack
\return value of the top element in the stack
Copies the value of the top element of the stack.
Elements keep untouched.
*/
T getTop();
const T& getTop() const;
/**
\brief assignment from other stack
Copies the elements of another stack to this one.
*/
void operator = (const tpStack& stack);
/**
\brief removes all elements from the stack
Removes all elements from the stack and frees the
memory occupied by the stack.
*/
void empty();
/**
\brief checks if the stack is empty
\return TRUE if the stack is empty, otherwise FALSE
Checks if this stack is empty.
*/
bool isEmpty() const;
/**
\brief get the actual size of the stack
\return number of elements in the stack
Get the number of elements of the stack.
*/
tpUInt getSize() const;
tpUInt getMaxSize() const;
T* begin() { return mData; }
const T* begin() const { return mData; }
T* end() { return mData + mSize; }
const T* end() const { return mData + mSize; }
T& front() { return *begin(); }
const T& front() const { return *begin(); }
T& back() { return *(end() - 1); }
const T& back() const { return *(end() - 1); }
protected:
void grow(tpUInt size);
T* mData;
tpUInt mCapacity;
tpUInt mSize;
};
// ---------------------------------------------------
template <typename T> inline tpStack<T>::tpStack()
: mData(0),
mCapacity(0),
mSize(0)
{
}
template <typename T> inline tpStack<T>::tpStack(const tpStack<T>& stack)
: mData(0),
mCapacity(0),
mSize(0)
{
*this = stack;
}
template <typename T> inline tpStack<T>::~tpStack()
{
empty();
}
template <typename T> inline void tpStack<T>::pop()
{
--mSize;
}
template <typename T> inline void tpStack<T>::push(T val)
{
// should use a better growing strategy
if (mSize <= mCapacity) grow(mSize + 2);
mData[mSize] = val;
++mSize;
}
template <typename T> inline T tpStack<T>::getTop()
{
return mData[mSize - 1];
}
template <typename T> inline const T& tpStack<T>::getTop() const
{
return mData[mSize - 1];
}
template <typename T> inline void tpStack<T>::operator = (const tpStack& stack)
{
grow(stack.mSize);
T* src = stack.mData;
T* dest = mData;
for (tpULong i = 0; i < mSize; ++i)
{
*dest = *src;
++dest;
++src;
}
}
template <typename T> inline void tpStack<T>::grow(tpUInt size)
{
if ((size <= mCapacity) || (!size)) return;
T* _temp = new T[size];
T* src = mData;
T* dest = _temp;
for (tpUInt i = 0; i < mSize;++i)
{
*dest = *src;
++dest;
++src;
}
if (mData) delete [] mData;
mCapacity = size;
mData = _temp;
}
template <typename T> inline bool tpStack<T>::isEmpty() const
{
return 0 == mSize;
}
template <typename T> inline void tpStack<T>::empty()
{
if (mData) delete [] mData;
mData = 0;
mSize = 0;
mCapacity = 0;
}
template <typename T> inline tpUInt tpStack<T>::getSize() const
{
return mSize;
}
template <typename T> inline tpUInt tpStack<T>::getMaxSize() const
{
return mCapacity;
}
#endif
| true |
346c3ce9dd2567ef5784feb73d4e3566af0087e8 | C++ | hugo-maker/til | /sams_teach_yourself_cpp/lesson05/listing5_03.cpp | UTF-8 | 931 | 4.03125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
cout << "Enter two integers:" << endl;
int num1 = 0, num2 = 0;
cin >> num1;
cin >> num2;
bool is_equal = (num1 == num2);
cout << "Result of equality test: " << is_equal << endl;
bool is_unequal = (num1 != num2);
cout << "Result of inequality test: " << is_unequal << endl;
bool is_greter_than = (num1 > num2);
cout << "Result of " << num1 << " > " << num2;
cout << " test: " << is_greter_than << endl;
bool is_less_than = (num1 < num2);
cout << "Result of " << num1 << " < " << num2;
cout << " test: " << is_less_than << endl;
bool is_greater_than_equals = (num1 >= num2);
cout << "Result of " << num1 << " >= " << num2;
cout << " test: " << is_greater_than_equals << endl;
bool is_less_than_equals = (num1 <= num2);
cout << "Result of " << num1 << " <= " << num2;
cout << " test: " << is_less_than_equals << endl;
return 0;
}
| true |
71cbab5f855d280de59d008f0dcfd759646e1dfe | C++ | gerardogtn/PracticaFinalSO | /RoundRobinScheduler.hpp | UTF-8 | 2,768 | 3.0625 | 3 | [] | no_license | // Copyright 2016
#ifndef ROUNDROBINSCHEDULER_H
#define ROUNDROBINSCHEDULER_H
#include <iostream>
#include <list>
#include "processComparison.hpp"
#include "SchedulerStep.hpp"
#include "Process.hpp"
class RoundRobinScheduler {
private:
const int quanta;
const int PROCESS_NUMBER;
double currentTime;
double waitingTime = 0.0;
double turnaroundTime = 0.0;
std::list<Process> processes;
Process* last = nullptr;
std::list<Process> getReadyQueue() {
std::list<Process> readyQueue;
for (Process p : processes) {
if (p.getArrivalTime() <= currentTime) {
readyQueue.push_back(p);
}
}
return readyQueue;
}
void updateWaitingTime(double wait) {
std::list<Process> readyQueue = getReadyQueue();
waitingTime += readyQueue.size() * wait;
}
void onProcessNotReady(Process* next) {
if (last == nullptr) {
last = next;
processes.push_back(*next);
} else if (*last == *next) {
currentTime = next->getArrivalTime();
processes.push_front(*next);
last = nullptr;
}
}
void onBurstProcess(const Process& process) {
updateClock(process.getDuration());
turnaroundTime += currentTime - process.getArrivalTime();
}
void onReduceProcessDuration(Process* process) {
updateClock(quanta);
process->reduceDuration(quanta);
processes.push_back(*process);
}
void updateClock(double time) {
currentTime += time;
updateWaitingTime(time);
}
public:
explicit RoundRobinScheduler(int quanta, std::list<Process> processes)
: quanta(quanta), PROCESS_NUMBER(processes.size()), processes(processes) {
this->processes.sort(compareByArrivalTime);
currentTime = this->processes.front().getArrivalTime();
}
virtual ~RoundRobinScheduler() {}
std::list<SchedulerStep> getSteps() {
std::list<SchedulerStep> steps = std::list<SchedulerStep>();
while (!processes.empty()) {
Process next = processes.front();
processes.pop_front();
double previousTime = currentTime;
if (next.getArrivalTime() > currentTime) {
onProcessNotReady(&next);
continue;
} else if (next.getDuration() <= quanta) {
onBurstProcess(next);
} else {
onReduceProcessDuration(&next);
}
SchedulerStep step(next.getName(), previousTime,
currentTime, getReadyQueue());
steps.push_back(step);
}
return steps;
}
double getAverageWaitTime() {
return waitingTime / PROCESS_NUMBER;
}
double getAverageTurnAroundTime() {
return turnaroundTime / PROCESS_NUMBER;
}
SchedulerResult getResult() {
return SchedulerResult(getAverageWaitTime(), getAverageTurnAroundTime());
}
};
#endif // ROUNDROBINSCHEDULER_H
| true |
db0a9e6e58e9833219e80a86ac7e7fc9dcc287b1 | C++ | hudvin/lightroom-mintaka | /lr-qt/untitled/csvreader.cpp | UTF-8 | 898 | 2.59375 | 3 | [] | no_license | #include "csvreader.h"
#include <pathutils.h>
#include <QFile>
#include <QDebug>
#include <QTextStream>
#include <QIODevice>
#include <QStringList>
CSVReader::CSVReader(){
}
void CSVReader::load(){
//QList<Entry> entries;
QString path = PathUtils::getAppTmpDir()+"/"+ENTRIES_FILE_NAME;
QFile inputFile(path);
if (inputFile.open(QIODevice::ReadOnly)){
QTextStream in(&inputFile);
while ( !in.atEnd() ){
QStringList tokens = in.readLine().split(",");
PhotoEntry entry(-1,tokens[0], tokens[1]);
entries<<entry;
qDebug()<<tokens;
}
inputFile.close();
}
}
bool CSVReader::isUUIDInList(QString uuid){
foreach(PhotoEntry entry, entries){
if(entry.uuid==uuid){
return true;
}
}
return false;
}
QList<PhotoEntry> CSVReader::getEntries(){
return entries;
}
| true |
cddcc2c2f8fa65029103e9327a171b6a537560c8 | C++ | alaswell/CS253-FA17 | /PA3/Histogram.cpp | UTF-8 | 6,123 | 3.5625 | 4 | [] | no_license | #include <Histogram.h>
/*! \file Histogram.cpp: implements the Histogram class */
/// Evaluation operator.
/// Takes a Histogram and counts all instances of distinct strings
/// within the .histogram and stores them as a key_value_pair in the .map
void Histogram::Eval (Histogram& Hist) {
/* for each string in histogram
* find it in kvm and increment
* if not found, std::map::operator[] will zero-initialize
*/
for(auto &s : Hist.histogram) ++Hist.key_value_map[s];
}
/// Input operator. Format is string string ... str,
/// where all strings are delineated by whitespace.
/// Any other format causes the input stream to fail.
bool Histogram::Read (istream& istr, vector<string>& histogram)
{
string word; // temp var for holding the word
bool empty = true; // the vector starts out empty
bool punctADD = false; // flag for added inside loop
bool punctFnd = false; // flag for if punctuation was found
if(istr.fail()) return false; // input file did not open correctly
// store all the words in the file in a single vector
while(istr >> word) {
if(empty) empty = false; // there is at least one string in the file
if(punctADD) punctADD = false; // reset this flag
if(punctFnd) punctFnd = false; // reset this flag
for(unsigned int i = 0; i < word.length(); i++) {
// for every char in word check if it is punctuation
if(ispunct(word.at(i))) {
// punctuation found
// CHECK FOR EXCEPTIONS
char c = word.at(i);
// apostrophes don't count
if(c == '\'') {} // do nothing
// numbers don't count
else if(c == ',') {
if(i != 0 && (i+1 != word.length())) {
if(isdigit(word.at(i-1)) && isdigit(word.at(i+1))) {} // do nothing
else punctFnd = true;
}
else punctFnd = true;
}
// periods only count in certain instances
else if(c == '.') {
if(i+1 != word.length()) {
if(isdigit(word.at(i+1))) {
if(i == 0 || isdigit(word.at(i-1))) {}
else punctFnd = true;
}
else punctFnd = true;
}
else punctFnd = true;
}
else { punctFnd = true; } // no exceptions
if(punctFnd) {
if(i > 0) {
// there is a preceeding string
histogram.push_back(word.substr(0, i)); // add that string to hist
word = word.substr(i); //cut out the added string
}
// word[0].ispunct() = true
if(word.length() == 1) {
// it's a single string containing a punctuation char
// can just add it to histogram
histogram.push_back(word);
punctADD = true;
break;
}
else
word = Histogram::parsePunctuation(word, this->GetHist());
}
}
// keep checking char's in this word
if(punctADD) break;
if(punctFnd) {
i = 0; // ispunct(word.at(0)) == false
punctFnd = false; // reset flag
}
}
// we have checked each char in this word
// for(char c : word) ispunct(c) = false
if(!punctADD && word.length() > 0)
histogram.push_back(word);
}
// if not at eof, the value was not a valid string
if(istr.eof() != 1) {
cerr << "Error Histogram.Read() : File contents are invalid." << endl;
return false;
}
// if the file was empty we should error
if(empty) {
cerr << "Error Histogram.Read() : Empty file" << endl;
return false;
}
return true; // eof
}
/// Write operator.
/// Typical output operator. Takes an ostream& and a map<string, int>
/// dumps the key_value_pairs to the ostream provided
/// Erros on an empty map<string, int>
bool Histogram::Write(ostream& ostr, map<string, int>& kvm) const
{
if (ostr.fail()) return false; // output did not open correctly
if(kvm.size() < 1) {
cerr << "Error Histogram.Write() : Empty map" << endl;
return false;
}
// dump the totals to the ostream
for(auto s : kvm) ostr << s.first << " " << s.second << "\n";
return true;
}
/// Parse Punctuation.
/// Takes a string and a vector<string>&
/// searches the str and parses out any punctuation
/// returns a string such that ispunct(str[0]) = FALSE
string Histogram::parsePunctuation(string word, vector<string>& histogram) {
// ispunct(word[0]) = true
// word.length() > 1 = true
char c = word[1];
// the word either contains a single char
unsigned int strlen = 1;
if(ispunct(c)) {
// or it contains a string of char's
while(ispunct(c)) {
// CHECK FOR EXCEPTIONSi
if(c == '\'') break; // apostrophes don't count
strlen++;
if(strlen == word.length()) break;
c = word[strlen];
}
}
// PARSE IT
histogram.push_back(word.substr(0,strlen)); // ...?!Oops! adds "...?!" to hist
word = word.substr(strlen); // ...?!Oops! => Oops!
return word;
}
void Histogram::findCapitals(vector<string>& histogram){
for(unsigned int i = 0; i < histogram.size(); i++) {
// for each string in the vector
string word = histogram.at(i);
bool firstWord = false;
// if the word is capitalized
if(isupper(word[0])) {
if(i == 0) {
firstWord = true;
// first word is special, but still has exceptions
for(unsigned int j = 1; j < word.length(); j++) {
char c = word[j];
if(isupper(c) || isdigit(c)) { firstWord = false; }
}
if(firstWord) {
word = "+" + word;
histogram.at(i) = word;
}
}
else {
// get the previous word
string prev = histogram.at(i-1);
if(ispunct(prev[0])) {
if(firstWord) firstWord = false; // rest the flag
// check for regexp
for(auto c : prev)
if(c == '.' || c == '?' || c == '!') firstWord = true;
if(firstWord) {
// EXCEPTOIN:
// if the word has another upperCase letter or a digit;
// it's an acronym
for(unsigned int j = 1; j < word.length(); j++) {
char c = word[j];
if(isupper(c) || isdigit(c)) { firstWord = false; }
}
// IF a word is capatalized, is the first word in a sentence
// is not an acronym, and does not contain a digit;
// mark is as ambiguous by prepending a '+' sign
if(firstWord) {
word = "+" + word;
histogram.at(i) = word;
}
}
}
}
}
}
}
| true |
4549a39ed362aaae734b3a1d7802bdfb8b2b2098 | C++ | hhYanGG/Acid | /Sources/Models/VertexModel.cpp | UTF-8 | 2,273 | 3.0625 | 3 | [
"MIT"
] | permissive | #include "VertexModel.hpp"
namespace acid
{
VertexModel::VertexModel(const Vector3 &position, const Vector2 &uv, const Vector3 &normal, const Vector3 &tangent) :
IVertex(),
m_position(position),
m_uv(uv),
m_normal(normal),
m_tangent(tangent)
{
}
VertexModel::VertexModel(const VertexModel &source) :
IVertex(),
m_position(source.m_position),
m_uv(source.m_uv),
m_normal(source.m_normal),
m_tangent(source.m_tangent)
{
}
VertexModel::~VertexModel()
{
}
void *VertexModel::GetData(std::vector<IVertex *> &vertices)
{
size_t dataSize = GetSize() * vertices.size();
void *data = new void *[dataSize];
std::vector<VertexModel> thisVector = std::vector<VertexModel>();
for (auto &vertex : vertices)
{
thisVector.emplace_back(*((VertexModel *) vertex));
}
memcpy(data, thisVector.data(), dataSize);
return data;
}
VertexInput VertexModel::GetVertexInput()
{
std::vector<VkVertexInputBindingDescription> bindingDescriptions(1);
// The vertex input description.
bindingDescriptions[0].binding = 0;
bindingDescriptions[0].stride = sizeof(VertexModel);
bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
std::vector<VkVertexInputAttributeDescription> attributeDescriptions(4);
// Position attribute.
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[0].offset = offsetof(VertexModel, m_position);
// UV attribute.
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[1].offset = offsetof(VertexModel, m_uv);
// Normal attribute.
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[2].offset = offsetof(VertexModel, m_normal);
// Tangent attribute.
attributeDescriptions[3].binding = 0;
attributeDescriptions[3].location = 3;
attributeDescriptions[3].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[3].offset = offsetof(VertexModel, m_tangent);
return VertexInput(bindingDescriptions, attributeDescriptions);
}
}
| true |
e6393d3d1a8d435271d43a61342b6dddb4b96c5b | C++ | EdgarOlv/Arduino_Projects | /Teclado-Capacitivo/Teclado-Capacitivo.ino | UTF-8 | 1,387 | 2.859375 | 3 | [] | no_license | #include <CapacitiveSensor.h>
//Resistor ligando os pinos 4 e 2 (sender=2, receiver=3)
CapacitiveSensor sensor = CapacitiveSensor(2,7);
CapacitiveSensor sensor2 = CapacitiveSensor(2,4);
int buzzer = 11;
int SENSIBILIDADE = 900; //Frontreira que defini entre tocar ou nao
bool ligado = 0; //Indica se a lampada esta ligada ou nao
int total = 0; //Valor colhido pelo pino receptor
void setup()
{
pinMode(buzzer,OUTPUT);
Serial.begin(9600); //Saida serial
}
void loop()
{
long total = sensor.capacitiveSensor(30); //Le valor no pino receptor
long total2 = sensor2.capacitiveSensor(30); //Le valor no pino receptor
//Verifica se valor lido eh maior ou nao que a fronteira definida
/*if (total > SENSIBILIDADE) {
ligado = !ligado;
if (ligado)
Serial.println("LAMPADA LIGADA");
else
Serial.println("LAMPADA DESLIGADA");
//Delay que simula o tempo de mudar intensidade do led no interruptor
for (int i=255; i>1; i--) {
delay(5);
}
}
if(total>30)
tone(8,200,50);
if(total2>1000)
tone(8,600,50);
// if(total3>1000)
//tone(8,900,50);
*/
Serial.println();
Serial.print(total);
Serial.print(" - ");
Serial.print(total2);
delay(100);
}
| true |
f4c6e163e3433483c2a54340f5bbe6f4248c73fb | C++ | xucheng1010/forest | /linux/3/sys_file.h | GB18030 | 1,082 | 3 | 3 | [] | no_license | #ifndef FOREST_SYS_FILE_H_
#define FOREST_SYS_FILE_H_
//װļIOϵͳãṩͬĶд
#include <fcntl.h>
#include <unistd.h>
#include "file_interface.h"
namespace forest
{
class SysFile : public FileInterface
{
public:
SysFile();
~SysFile();
public:
//ļ
virtual bool Open(const std::string& path);
//ļ
virtual bool Create(const std::string& path);
//رļ
virtual void Close();
//ȡ
virtual int Read(char* buffer, int length);
//д
virtual int Write(const char* buffer, int length);
//ϴ
virtual void Flush();
//ǷЧ
virtual bool Valid() const;
private:
void Clear();
private:
int filedes_; //ļ
off_t read_off_set_; //ƫ
std::string path_; //ļ·
};
inline bool SysFile::Valid() const
{
return -1 != filedes_;
}
inline void SysFile::Clear()
{
if (Valid())
{
close(filedes_);
}
filedes_ = -1;
read_off_set_ = 0;
path_ = "";
}
}
#endif
| true |
1c242f384c6cf46ada587a5df10c9f7413ad7ceb | C++ | NeutralNoise/lol_script | /lolVM/fetch/fetch_mov.cpp | UTF-8 | 1,135 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "fetch_mov.h"
#include "fetch_stack.h"
void fetchMovRegToReg(cpu * c) {
c->instruction.first = *(c->memory + c->pc + 1);
c->instruction.second = *(c->memory + c->pc + 2);
}
void fetchMoveRegToMem(cpu * c) {
c->instruction.first = *(c->memory + c->pc + 1);
c->instruction.second = *(uint32*)(c->memory + c->pc + 2);
}
void fetchMoveMemToReg(cpu * c) {
c->instruction.first = *(uint32*)(c->memory + c->pc + 1);
c->instruction.second = *(c->memory + c->pc + 5);
c->instruction.third = *(c->memory + c->pc + 6);
}
void fetchConstToReg(cpu * c) {
c->instruction.first = *(c->memory + c->pc + 1);
c->instruction.second = *(int*)(c->memory + c->pc + 2);
}
void fetchConstToMem(cpu * c) {
c->instruction.first = *(uint32*)(c->memory + c->pc + 1);
c->instruction.second = *(int32*)(c->memory + c->pc + 5);
}
void fetchRegToStack(cpu * c) {
//Does the same thing.
fetchStackRegPush(c);
}
void fetchStackToReg(cpu * c) {
//what reg to put it in.
c->instruction.first = (char)*(c->memory + c->pc + 1);
//where we are getting the data from in the stack.
c->instruction.second = *(uint32*)(c->memory + c->pc + 2);
}
| true |
404da9d9c96881491b20afe5ae2687315436c8e2 | C++ | GabrielEstevam/icpc_contest_training | /uri/uri_cpp/estruturas_e_bibliotecas/p1709.cpp | UTF-8 | 443 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int rec(int pos, int n, long long cont);
int main() {
int N;
while (cin >> N)
printf("%d\n", rec(2, N, 1));
return 0;
}
int rec(int pos, int n, long long cont) {
if (pos == 1)
return cont;
if (pos <= n/2)
return rec(pos*2, n, cont+1);
return rec((pos-n/2-1)*2+1, n, cont+1);
}
| true |
551d42cd6113bb0606826a5e86938d97bb4039cf | C++ | SentientCoffee/Primordial | /src/LevelLoader.cpp | UTF-8 | 5,906 | 2.640625 | 3 | [
"MIT"
] | permissive | #include "LevelLoader.h"
#include "Cappuccino/CappMacros.h"
#include "Cappuccino/HitBox.h"
#include <Cappuccino/PointLight.h>
#include <fstream>
#include <string>
LevelLoader::LevelLoader(const char* filename)
{
char tempName[256] = "";
bool moreFile = true;
FILE* file = fopen(filename, "r");
if (file == nullptr) {
printf("Failed to open file \"%s\"!\n", filename);
moreFile = false;
}
while (moreFile)
{
char line[1024] = "";
const int lineNumber = fscanf(file, "%s", line);
if (lineNumber == EOF){//if end of file
break;
}
if (strcmp(line, "o") == 0){//if new object
int errorThing = fscanf(file, "%s\n", tempName);//get name of object
CAPP_ASSERT(errorThing, "Failed to read object name");
}
else if (strcmp(line, "v") == 0){//if vertex
glm::vec3 vertex;
int errorThing = fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
CAPP_ASSERT(errorThing, "Failed to read vertex data");
_tempVerts.push_back(vertex);
}
else if (strcmp(line, "s") == 0 && strcmp(tempName, "") != 0) {
if (tempName[0] == 'E'){
DoorLoc newDoor;
std::string rotationString = tempName;
rotationString = rotationString.substr(rotationString.find_first_of('_')+1,rotationString.find_last_of('_')-5);
newDoor._rotation = std::stof(rotationString);
newDoor._exitBox._size = glm::vec3(2.0f, 4.0f, 1.0f);
newDoor._exitBox._position = findCenter();
newDoor._exitBox._position.y += 1;
_exits.push_back(newDoor);
}
else if (tempName[0] == 'D') {
_entrance._exitBox._size = glm::vec3(2.0f, 4.0f, 4.0f);
_entrance._exitBox._position = findCenter();
_entrance._exitBox._position.y += 1;
}
else if (tempName[0] == 'L'){
_lights.emplace_back(findCenter(), tempName[1] == 'S' ? 1.0f : 0.0f);
}
else if (tempName[0] == 'R'){
_respawnPoint = findCenter();
}
else if (tempName[0] == 'M'){
_shopLocation = findCenter();
}
else if (tempName[0] == 'C'){
chests.push_back(findCenter());
}
else if (tempName[0] == 'G')
{
_lifts.push_back(GravLift(Cappuccino::HitBox(findCenter(), findBox()), 100.0f));
}
else if (tempName[0] == 'H')
{
_hurtboxes.push_back(HurtBox(Cappuccino::HitBox(findCenter(), findBox()), 40000.0f));
}
else if (tempName[0] == 'T') {
_teleporterLoc.emplace_back(findCenter());
}
_tempVerts.clear();
}
}
}
void LevelLoader::rotate(float rotation)
{
for (unsigned i = 0; i < _exits.size(); i++)
_exits[i]._exitBox.rotateBox(rotation);
_entrance._exitBox.rotateBox(rotation);
if (rotation / 90.0f == 1.0f){
_respawnPoint = glm::vec3(_respawnPoint.z, _respawnPoint.y, -_respawnPoint.x);
_shopLocation = glm::vec3(_shopLocation.z, _shopLocation.y, -_shopLocation.x);
}
else if (rotation / 90.0f == 2.0f){
_respawnPoint.x *= -1;
_respawnPoint.z *= -1;
_shopLocation.x *= -1;
_shopLocation.z *= -1;
}
else if (rotation / 90.0f == 3.0f){
_respawnPoint = glm::vec3(-_respawnPoint.z, _respawnPoint.y, _respawnPoint.x);
_shopLocation = glm::vec3(-_shopLocation.z, _shopLocation.y, _shopLocation.x);
}
for (unsigned i = 0; i < _lights.size(); i++) {
if (rotation / 90.0f == 1.0f) {
_lights[i] = { _lights[i].z, _lights[i].y, -_lights[i].x, _lights[i].w };
}
else if (rotation / 90.0f == 2.0f) {
_lights[i].x *= -1;
_lights[i].z *= -1;
}
else if (rotation / 90.0f == 3.0f) {
_lights[i] = { -_lights[i].z, _lights[i].y, _lights[i].x, _lights[i].w };
}
}
for (unsigned i = 0; i < chests.size(); i++){
if (rotation / 90.0f == 1.0f) {
chests[i] = glm::vec3(chests[i].z, chests[i].y, -chests[i].x);
}
else if (rotation / 90.0f == 2.0f) {
chests[i].x *= -1;
chests[i].z *= -1;
}
else if (rotation / 90.0f == 3.0f) {
chests[i] = glm::vec3(-chests[i].z, chests[i].y, chests[i].x);
}
}
for (unsigned i = 0; i < _lifts.size(); i++) {
_lifts[i]._areaOfAffect.rotateBox(rotation);
}
for (unsigned i = 0; i < _hurtboxes.size(); i++) {
_hurtboxes[i]._hurtBox.rotateBox(rotation);
}
for (unsigned i = 0; i < _teleporterLoc.size(); i++) {
if (rotation / 90.0f == 1.0f) {
_teleporterLoc[i]._position = glm::vec3(_teleporterLoc[i]._position.z, _teleporterLoc[i]._position.y, -_teleporterLoc[i]._position.x);
}
else if (rotation / 90.0f == 2.0f) {
_teleporterLoc[i]._position *= -1;
_teleporterLoc[i]._position.z *= -1;
}
else if (rotation / 90.0f == 3.0f) {
_teleporterLoc[i]._position = glm::vec3(-_teleporterLoc[i]._position.z, _teleporterLoc[i]._position.y, _teleporterLoc[i]._position.x);
}
}
}
glm::vec3 LevelLoader::findCenter()
{
glm::vec3 tempHigh = _tempVerts[0];
glm::vec3 tempLow = _tempVerts[0];
for (unsigned int i = 0; i < _tempVerts.size(); i++)
{
if (_tempVerts[i].x > tempHigh.x)
tempHigh.x = _tempVerts[i].x;
if (_tempVerts[i].y > tempHigh.y)
tempHigh.y = _tempVerts[i].y;
if (_tempVerts[i].z > tempHigh.z)
tempHigh.z = _tempVerts[i].z;
if (_tempVerts[i].x < tempLow.x)
tempLow.x = _tempVerts[i].x;
if (_tempVerts[i].y < tempLow.y)
tempLow.y = _tempVerts[i].y;
if (_tempVerts[i].z < tempLow.z)
tempLow.z = _tempVerts[i].z;
}
return glm::vec3(tempHigh.x / 2 + tempLow.x / 2,
(tempHigh.y / 2 + tempLow.y / 2)-2,
tempHigh.z / 2 + tempLow.z / 2);
}
glm::vec3 LevelLoader::findBox()
{
glm::vec3 tempHigh = _tempVerts[0];
glm::vec3 tempLow = _tempVerts[0];
for (unsigned int i = 0; i < _tempVerts.size(); i++)
{
if (_tempVerts[i].x > tempHigh.x)
tempHigh.x = _tempVerts[i].x;
if (_tempVerts[i].y > tempHigh.y)
tempHigh.y = _tempVerts[i].y;
if (_tempVerts[i].z > tempHigh.z)
tempHigh.z = _tempVerts[i].z;
if (_tempVerts[i].x < tempLow.x)
tempLow.x = _tempVerts[i].x;
if (_tempVerts[i].y < tempLow.y)
tempLow.y = _tempVerts[i].y;
if (_tempVerts[i].z < tempLow.z)
tempLow.z = _tempVerts[i].z;
}
return glm::vec3(tempHigh - tempLow);
}
| true |
d95cea99f8add45bae1702b078a209829ac7c464 | C++ | Syllllvia/MagicConch | /src/MagicConch/MTime.h | UTF-8 | 601 | 3.15625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <time.h>
#include <Windows.h>
class MTime
{
public:
MTime(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
static MTime to_MTime(std::string &ntime); //将如“2019.6.1”这样的合法输入转为时间类实例
std::string getTimeString(char segment = '.'); //将MTime转化为string语句,用于输出(默认分隔符为'.')
int remainingTime(); //返回传入时间(比今天晚)距离今天还有多久,不包含当天
bool operator==(MTime &b);
bool operator>(MTime &b);
private:
int year;
int month;
int day;
}; | true |
1cedf6f6556963bd24acd5a295e93dfd08c3c8dd | C++ | vhirtham/GDL | /gdl/base/tolerance.h | UTF-8 | 5,269 | 3.3125 | 3 | [] | no_license | #pragma once
#include "gdl/base/fundamentalTypes.h"
#include "gdl/base/simd/utility.h"
namespace GDL
{
//! @brief Class to check if two values are equal with a certain tolerance.
//! @tparam _registerType: Register type or data type for non sse types
//! @tparam _numComparedValuesSSE: Specifies how many values (starting with the first element) of a sse register should
//! be compared. For non sse types this value should be set to 0 (specialized case).
//! @remark There is also the Approx class which has a quiet similar purpose. The major difference is, that the approx
//! has a dynamic tolerance while this class only has a fixed tolerance
template <typename _registerType, U32 _numComparedValuesSSE = simd::numRegisterValues<_registerType>>
class alignas(simd::alignmentBytes<_registerType>) Tolerance
{
static_assert(simd::IsRegisterType<_registerType>, "Type is no valid sse register type");
static_assert(_numComparedValuesSSE <= simd::numRegisterValues<_registerType>,
"_numComparedValues > Number of register elements.");
alignas(simd::alignmentBytes<_registerType>) _registerType mValue;
alignas(simd::alignmentBytes<_registerType>) _registerType mTolerance;
public:
Tolerance() = delete;
Tolerance(const Tolerance&) = default;
Tolerance(Tolerance&&) = default;
Tolerance& operator=(const Tolerance&) = default;
Tolerance& operator=(Tolerance&&) = default;
~Tolerance() = default;
//! @brief ctor
//! @param value: Register of values that should be compared to other values
//! @param tolerance: Tolerances for the comparison (Can be different for each element)
Tolerance(_registerType value, _registerType tolerance);
//! @brief ctor
//! @tparam _type: Data type of the tolerance
//! @param value: Register of values that should be compared to other values
//! @param tolerance: Tolerance value for all comparisons of the register
template <typename _type>
Tolerance(_registerType value, _type tolerance);
//! @brief Compares if the rhs values are inside a certain tolerance to the stored values
//! @param rhs: Right hand side values
//! @return Returns true if all rhs values are inside the tolerance. False otherwise
inline bool operator==(_registerType rhs) const;
//! @brief Compares if the rhs values are NOT inside a certain tolerance to the stored values
//! @param rhs: Right hand side values
//! @return Returns true if one or more rhs values are not inside the tolerance. False otherwise
inline bool operator!=(_registerType rhs) const;
};
//! @brief Spezialization of the Tolerance class for non sse types
//! @tparam _type: Data type
template <typename _type>
class Tolerance<_type, 0>
{
static_assert(std::is_integral<_type>::value || std::is_floating_point<_type>::value,
"Tolerance can only be used with integer and floating point types.");
_type mValue;
_type mTolerance;
public:
Tolerance() = delete;
Tolerance(const Tolerance&) = default;
Tolerance(Tolerance&&) = default;
Tolerance& operator=(const Tolerance&) = default;
Tolerance& operator=(Tolerance&&) = default;
~Tolerance() = default;
//! @brief ctor
//! @param value: Value that should be compared to other values
//! @param tolerance: Tolerance for the comparison
constexpr Tolerance(const _type value, const _type tolerance);
//! @brief Compares if the rhs value is inside a certain tolerance to the stored value
//! @param rhs: Right hand side value
//! @return True / false
constexpr bool operator==(_type rhs) const;
//! @brief Compares if the rhs value is NOT inside a certain tolerance to the stored value
//! @param rhs: Right hand side value
//! @return True / false
constexpr bool operator!=(_type rhs) const;
};
//! @brief Compares if the rhs value is inside a certain tolerance to the stored value of the Tolerance class.
//! Have a look at the specific class template (sse or not) for more details.
//! @tparam _typeLhs: Type of the lhs value
//! @tparam _typeTolerance: Type of the value stored inside of the Tolerance class
//! @tparam _numComparedValuesSSE: Number of compared values of the Tolerance class
//! @param lhs: Left hand side value
//! @param rhs: Right hand side value
//! @return True / false
template <typename _typeLhs, typename _typeTolerance, U32 _numComparedValuesSSE>
constexpr bool operator==(const _typeLhs lhs, const Tolerance<_typeTolerance>& rhs);
//! @brief Compares if the rhs value is NOT inside a certain tolerance to the stored value of the Tolerance class.
//! Have a look at the specific class template (sse or not) for more details.
//! @tparam _typeLhs: Type of the lhs value
//! @tparam _typeTolerance: Type of the value stored inside of the Tolerance class
//! @tparam _numComparedValuesSSE: Number of compared values of the Tolerance class
//! @param lhs: Left hand side value
//! @param rhs: Right hand side value
//! @return True / false
template <typename _typeLhs, typename _typeTolerance, U32 _numComparedValuesSSE>
constexpr bool operator!=(const _typeLhs lhs, const Tolerance<_typeTolerance>& rhs);
} // namespace GDL
#include "gdl/base/tolerance.inl"
| true |
b77d14ae7a5a454422e0a2421b095ec9e5bddbf9 | C++ | Akheon23/dcp | /examples/Tools.h++/rw7/manual/tmplcard.cpp | WINDOWS-1252 | 3,880 | 2.796875 | 3 | [] | no_license | /*
* This example is from the Tools.h++ manual, version 7
*
* Copyright (c) 1989-1999 Rogue Wave Software, Inc. All Rights Reserved.
*
* This computer software is owned by Rogue Wave Software, Inc. and is
* protected by U.S. copyright laws and other laws and by international
* treaties. This computer software is furnished by Rogue Wave Software,
* Inc. pursuant to a written license agreement and may be used, copied,
* transmitted, and stored only in accordance with the terms of such
* license and with the inclusion of the above copyright notice. This
* computer software or any other copies thereof may not be provided or
* otherwise made available to any other person.
*
* U.S. Government Restricted Rights. This computer software is provided
* with Restricted Rights. Use, duplication, or disclosure by the
* Government is subject to restrictions as set forth in subparagraph (c)
* (1) (ii) of The Rights in Technical Data and Computer Software clause
* at DFARS 252.227-7013 or subparagraphs (c) (1) and (2) of the
* Commercial Computer Software Restricted Rights at 48 CFR 52.227-19,
* as applicable. Manufacturer is Rogue Wave Software, Inc., 5500
* Flatiron Parkway, Boulder, Colorado 80301 USA.
*/
/* Note: This example requires the C++ Standard Library */
#ifdef RW_NO_STL
#error This example is for users with access to the C++ Standard Library
#else
#include <iostream.h>
#include <algorithm>
#include <rw/tvordvec.h>
#include <stdcomp.h>
#ifndef RWSTD_NO_NAMESPACE
using namespace std;
#endif
//MSVC 6.0 requires this separate declaration of Card and the << operator
//struct Card;
//ostream& operator<<(ostream& ostr, const Card& c);
struct Card {
char rank;
char suit;
bool operator== (const Card& c) const
{ return rank == c.rank && suit == c.suit; }
bool operator< (const Card& c) const
{ return rank < c.rank; }
Card() { }
Card(char r, char s) : rank(r), suit(s) { }
// print a card: '3-H' = three of hearts, 'A-S' = ace of spades
friend ostream& operator<<(ostream& ostr, const Card& c)
{ return (ostr << c.rank << "-" << c.suit << " "); }
};
/*
* A generator class - return Cards in sequence
*/
class DeckGen {
int rankIdx; // indexes into static arrays below
int suitIdx;
static const char Ranks[13];
static const char Suits[4];
public:
DeckGen() : rankIdx(-1), suitIdx(-1) { }
// generate the next Card
Card operator()()
{
rankIdx = (rankIdx + 1) % 13;
if (rankIdx == 0)
// cycled through ranks, move on to next suit:
suitIdx = (suitIdx + 1) % 4;
return Card(Ranks[rankIdx], Suits[suitIdx]);
}
};
const char DeckGen::Suits[4] = {'S', 'H', 'D', 'C' };
const char DeckGen::Ranks[13] = {'A', '2', '3', '4',
'5', '6', '7', '8',
'9', 'T', 'J', 'Q', 'K' };
int main(){
// Tools.h++ collection:
RWTValOrderedVector<Card> deck;
RWTValOrderedVector<Card>::size_type pos;
Card aceOfSpades('A','S');
Card firstCard;
// Use standard library algorithm to generate deck:
generate_n(back_inserter(deck.std()), 52, DeckGen());
cout << endl << "The deck has been created" << endl;
// Use Tools.h++ member function to find card:
pos = deck.index(aceOfSpades);
cout << "The Ace of Spades is at position " << pos+1 << endl;
// Use standard library algorithm to shuffle deck:
random_shuffle(deck.begin(), deck.end());
cout << endl << "The deck has been shuffled" << endl;
// Use Tools.h++ member functions:
pos = deck.index(aceOfSpades);
firstCard = deck.first();
cout << "Now the Ace of Spades is at position " << pos+1
<< endl << "and the first card is " << firstCard << endl;
return 0;
}
/* Output:
The deck has been created
The Ace of Spades is at position 1
The deck has been shuffled
Now the Ace of Spades is at position 37
and the first card is Q-D
*/
#endif //#ifdef RW_NO_STL
| true |
7919c9c93f2b0adce13a80a6fc05aeb061de2341 | C++ | tito-kimbo/Online-Judge-Solutions | /AceptaElReto/EDA_AceptaElReto_215/EDA_AceptaElReto_215/Source.cpp | UTF-8 | 977 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <vector>
std::istream & operator>>(std::istream & in, std::vector<int> & v) {
int aux;
in >> aux;
while (aux != -1) {
v.push_back(aux);
in >> aux;
}
return in;
}
//BUILDING A TREE SHOULD BE EXTREMELY SIMILAR
void createPostOrder(std::vector<int> const& pre, std::vector<int> const& in, int & index, bool & first) {
int i = 0;
++index;
while (in[i] != pre[index]) {
++i;
} //THIS WILL ALWAYS OCCUR AND i < limSup
//When to go left?
createPostOrder(pre, in, index, first); //LEFT
//When to go right?
createPostOrder(pre, in, index, first); //RIGHT
if (!first) std::cout << ' ';
std::cout << in[i];
first = false;
}
bool resolver() {
bool f = true;
std::vector<int> preOrder, inOrder;
int index = -1;
std::cin >> preOrder;
if (preOrder.size() != 0) {
std::cin >> inOrder;
createPostOrder(preOrder, inOrder, index, f);
std::cout << '\n';
return true;
}
return false;
}
int main() {
while (resolver());
} | true |
d31774f42524224fc54bce1dcfa8084ceb0c4752 | C++ | LazyShpee/IndieStudial | /IndieStudial/Sources/Vehicle.cpp | UTF-8 | 7,751 | 2.515625 | 3 | [] | no_license | #include "Vehicle.hpp"
#include <cstdio>
Vehicle::Car::Car(float x, float y, float heading) {
this->position = Vector::Vec2(x, y);
this->heading = heading;
this->absVel = 0.f;
this->yawRate = 0.f;
this->steer = 0.f;
this->steerAngle = 0.f;
this->smoothSteer = true;
this->safeSteer = true;
this->inertia = 0.f;
this->wheelBase = 0.f;
this->axleWeightRatioFront = 0.f;
this->axleWeightRatioRear = 0.f;
this->cfg = NULL;
}
Vehicle::Car::~Car() {}
void Vehicle::Car::doPhysics(float dt) {
float sn = sin(this->heading);
float cs = cos(this->heading);
// Get velocity in local car coordinates
this->velocity_c.x = cs * this->velocity.x + sn * this->velocity.y;
this->velocity_c.y = cs * this->velocity.y - sn * this->velocity.x;
// Weight on axles based on centre of gravity and weight shift due to forward/reverse acceleration
float axleWeightFront = cfg->mass * (this->axleWeightRatioFront * cfg->gravity - cfg->weightTransfer * this->accel_c.x * cfg->cgHeight / this->wheelBase);
float axleWeightRear = cfg->mass * (this->axleWeightRatioRear * cfg->gravity + cfg->weightTransfer * this->accel_c.x * cfg->cgHeight / this->wheelBase);
// Resulting velocity of the wheels as result of the yaw rate of the car body.
// v = yawrate * r where r is distance from axle to CG and yawRate (angular velocity) in rad/s.
float yawSpeedFront = cfg->cgToFrontAxle * this->yawRate;
float yawSpeedRear = -cfg->cgToRearAxle * this->yawRate;
// Calculate slip angles for front and rear wheels (a.k.a. alpha)
float slipAngleFront = atan2(this->velocity_c.y + yawSpeedFront, std::abs(this->velocity_c.x)) - GMath::sign(this->velocity_c.x) * this->steerAngle;
float slipAngleRear = atan2(this->velocity_c.y + yawSpeedRear, std::abs(this->velocity_c.x));
float tireGripFront = cfg->tireGrip;
float tireGripRear = cfg->tireGrip * (1.0 - !!(core::Receiver::inputs & I_EBRAKE) * (1.0 - cfg->lockGrip)); // reduce rear grip when ebrake is on
float frictionForceFront_cy = GMath::clamp(-cfg->cornerStiffnessFront * slipAngleFront, -tireGripFront, tireGripFront) * axleWeightFront;
float frictionForceRear_cy = GMath::clamp(-cfg->cornerStiffnessRear * slipAngleRear, -tireGripRear, tireGripRear) * axleWeightRear;
// Get amount of brake/throttle from our inputs
float brake = GMath::min(!!(core::Receiver::inputs & I_BRAKE) * cfg->brakeForce + !!(core::Receiver::inputs & I_EBRAKE) * cfg->eBrakeForce, cfg->brakeForce);
float throttle = !!(core::Receiver::inputs & I_THROTTLE) * (cfg->engineForce) - (cfg->engineForce / cfg->reverseForce) * !!(core::Receiver::inputs & I_REVERSE);
// Resulting force in local car coordinates.
// This is implemented as a RWD car only.
float tractionForce_cx = throttle - brake * GMath::sign(this->velocity_c.x);
float tractionForce_cy = 0;
float dragForce_cx = -cfg->rollResist * this->velocity_c.x - cfg->airResist * this->velocity_c.x * std::abs(this->velocity_c.x);
float dragForce_cy = -cfg->rollResist * this->velocity_c.y - cfg->airResist * this->velocity_c.y * std::abs(this->velocity_c.y);
// total force in car coordinates
float totalForce_cx = dragForce_cx + tractionForce_cx;
float totalForce_cy = dragForce_cy + tractionForce_cy + cos(this->steerAngle) * frictionForceFront_cy + frictionForceRear_cy;
// acceleration along car axes
this->accel_c.x = totalForce_cx / cfg->mass; // forward/reverse accel
this->accel_c.y = totalForce_cy / cfg->mass; // sideways accel
// acceleration in world coordinates
this->accel.x = cs * this->accel_c.x - sn * this->accel_c.y;
this->accel.y = sn * this->accel_c.x + cs * this->accel_c.y;
// update velocity
this->velocity.x += this->accel.x * dt;
this->velocity.y += this->accel.y * dt;
this->absVel = this->velocity.len();
// calculate rotational forces
float angularTorque = (frictionForceFront_cy + tractionForce_cy) * cfg->cgToFrontAxle - frictionForceRear_cy * cfg->cgToRearAxle;
// Sim gets unstable at very slow speeds, so just stop the car
if( std::abs(this->absVel) < 0.5 && !throttle )
{
this->velocity.x = this->velocity.y = this->absVel = 0;
angularTorque = this->yawRate = 0;
}
float angularAccel = angularTorque / this->inertia;
this->yawRate += angularAccel * dt;
this->heading += this->yawRate * dt;
// finally we can update position
this->position.x += this->velocity.x * dt;
this->position.y += this->velocity.y * dt;
}
void Vehicle::Car::update(float dtms) {
float dt = dtms;
int steerInput = !!(core::Receiver::inputs & I_LEFT) - !!(core::Receiver::inputs & I_RIGHT);
if (this->smoothSteer)
this->steer = this->applySmoothSteer(steerInput, dt);
else
this->steer = steerInput;
if (this->safeSteer)
this->steer = this->applySafeSteer(this->steer);
this->steerAngle = this->steer * this->cfg->maxSteer;
this->doPhysics(dt);
}
float Vehicle::Car::applySmoothSteer(float steerInput, float dt) {
float steer = 0.f;
if (std::abs(steerInput) > 0.001)
steer = GMath::clamp(this->steer + steerInput * dt * 2.0, -1.0, 1.0);
else
{
if (this->steer > 0.f)
steer = GMath::max(this->steer - dt * 1.f, 0.f);
else if (this->steer < 0.f)
steer = GMath::min(this->steer + dt * 1.f, 0.f);
}
return (steer);
}
float Vehicle::Car::applySafeSteer(float steerInput) {
float avel = GMath::min(this->absVel, 250.f);
float steer = steerInput * (1.0 - (avel / 280.f));
return (steer);
}
Vehicle::Config *Vehicle::Car::getConfig() const {
return (this->cfg);
}
void Vehicle::Car::setConfig(Vehicle::Config *cfg) {
this->cfg = cfg;
this->inertia = this->cfg->mass * this->cfg->inertiaScale;
this->wheelBase = this->cfg->cgToFrontAxle + this->cfg->cgToRearAxle;
this->axleWeightRatioFront = this->cfg->cgToRearAxle / this->wheelBase; // % car weight on the front axle
this->axleWeightRatioRear = this->cfg->cgToFrontAxle / this->wheelBase; // % car weight on the rear axle
}
Vehicle::Config *Vehicle::getDefaultConfig() {
Config *cfg = new Vehicle::Config;
cfg->gravity = 9.81; // m/s^2
cfg->mass = 1200.f; // kg
cfg->inertiaScale = 1.0; // Multiply by mass for inertia
cfg->halfWidth = 0.8; // Centre to side of chassis (metres)
cfg->cgToFront = 2.0; // Centre of gravity to front of chassis (metres)
cfg->cgToRear = 2.0; // Centre of gravity to rear of chassis
cfg->cgToFrontAxle = 1.25; // Centre gravity to front axle
cfg->cgToRearAxle = 1.25; // Centre gravity to rear axle
cfg->cgHeight = 0.55; // Centre gravity height
cfg->wheelRadius = 0.3; // Includes tire (also represents height of axle)
cfg->wheelWidth = 0.2; // Used for render only
cfg->tireGrip = 2.0; // How much grip tires have
cfg->lockGrip = 0.7; // % of grip available when wheel is locked
cfg->engineForce = 8000.f;
cfg->reverseForce = 3.f;
cfg->brakeForce = 12000.f;
cfg->eBrakeForce = cfg->brakeForce / 2.5;
cfg->weightTransfer = 0.2; // How much weight is transferred during acceleration/braking
cfg->maxSteer = 0.6; // Maximum steering angle in radians
cfg->cornerStiffnessFront = 5.0;
cfg->cornerStiffnessRear = 5.2;
cfg->airResist = 2.5; // air resistance (* vel)
cfg->rollResist = 8.0;
return (cfg);
}
void Vehicle::Car::setPosition(const Vector::Vec2 & pos)
{
this->position = pos;
}
void Vehicle::Car::setHeading(float heading)
{
this->heading = heading;
}
Vector::Vec2 Vehicle::Car::getPosition() const
{
return (this->position);
}
float Vehicle::Car::getHeading() const
{
return (this->heading);
}
void Vehicle::Car::calmezVous(float, float force)
{
this->velocity.x /= -force;
this->velocity.y /= -force;
}
| true |