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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
4e8da9ad95f05524b06cbf86259e68955795bdb2 | C++ | drguildo/csolutions | /chap19/exercise9.cpp | UTF-8 | 1,974 | 3.765625 | 4 | [] | no_license | #include <iostream>
class Node {
public:
Node(int);
int getValue(void);
Node *getPrev(void);
void setPrev(Node *);
private:
int value;
Node *prev;
};
Node::Node(int n) {
value = n;
prev = 0;
}
int Node::getValue(void) {
return value;
}
Node *Node::getPrev(void) {
return prev;
}
void Node::setPrev(Node *p) {
prev = p;
}
class Queue {
public:
Queue(void);
void insert(int);
void remove(void);
int first(void);
int last(void);
int isEmpty(void);
private:
Node *f;
Node *l;
};
Queue::Queue(void) {
f = 0;
l = 0;
}
void Queue::insert(int n) {
Node *new_node = new Node(n);
if (f == 0) {
f = new_node;
l = f;
} else {
l->setPrev(new_node);
l = new_node;
}
}
void Queue::remove(void) {
Node *cur = f;
if (isEmpty()) {
std::cout << "error: stack is empty" << std::endl;
return;
}
if (cur->getPrev() == 0) {
delete cur;
f = 0;
l = 0;
return;
}
while (cur->getPrev()->getPrev() != 0) {
cur = cur->getPrev();
}
l = cur;
delete cur->getPrev();
l->setPrev(0);
}
int Queue::first(void) {
if (isEmpty()) {
std::cout << "error: stack is empty" << std::endl;
return -1;
}
return f->getValue();
}
int Queue::last(void) {
if (isEmpty()) {
std::cout << "error: stack is empty" << std::endl;
return -1;
}
return l->getValue();
}
int Queue::isEmpty(void) {
return f == 0;
}
int main(void) {
int i;
Queue q;
std::cout << q.first() << std::endl;
for (i = 2; i != 12; i += 2) {
q.insert(i);
std::cout << q.last() << std::endl;
}
std::cout << "--" << std::endl;
while (!q.isEmpty()) {
std::cout << q.last() << std::endl;
q.remove();
}
return 0;
}
| true |
953c36d6ae7422fd31c75b3c63a69dc5c488f92e | C++ | 1ud0v1c/OpenGL | /mesh.h | UTF-8 | 567 | 2.65625 | 3 | [] | no_license | #ifndef MESH_H
#define MESH_H
#include <iostream>
#include <vector>
#include <glm/glm.hpp>
#include "vertex.h"
class Mesh {
public:
void addVertex(Vertex v);
void addIbo(unsigned int pos);
void addIbos(unsigned int pos, unsigned int pos2, unsigned int pos3);
void displayUvs();
std::vector<unsigned int> getIbos();
std::vector<glm::vec3> getPositions();
std::vector<glm::vec4> getColors();
std::vector<glm::vec3> getNormals();
std::vector<glm::vec2> getUvs();
private:
std::vector<Vertex> vbos;
std::vector<unsigned int> ibos;
};
#endif
| true |
f5304545902b55157ce52e1b01b60748ff6ed5d8 | C++ | dolf0204/SPA | /ComplexNumber.cpp | UTF-8 | 562 | 3.234375 | 3 | [] | no_license | #include"ComplexNumber.h"
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
ComplexNumber::ComplexNumber(int a, int b)
{
this->a = a;
this->b = b;
}
ComplexNumber::ComplexNumber(){}
void ComplexNumber::set_real(int a)
{
this->a = a;
}
void ComplexNumber::set_imaginary(int b)
{
this->b = b;
}
ComplexNumber::ComplexNumber(ComplexNumber jedan, ComplexNumber dva)
{
this->a = jedan.a + dva.a;
this->b = jedan.b+ dva.b;
}
string ComplexNumber::get()
{
stringstream sstr;
sstr << a << "+" << b << "i";
return sstr.str();
}
| true |
07afc6dd0414734dba1ea8c7761d6cd376186fef | C++ | phughes18/Lab_Manager | /labmanager.cpp | UTF-8 | 7,954 | 3.671875 | 4 | [] | no_license | /*********************************************************************
CISC 2000 Fordham University Fall 2019
Instructor: Vincent Mierlak
HW 5. Computer Lab Logging Program.
This program uses dynamic arrays to store login information for
four computer labs. Each of the four labs is referenced by the labs[] array
which is indexed from 0-3. Each element of the labs[] arrays is a
pointer to a dynamic array whose size is the number of computers in that
lab.
Written by: Peter Hughes
Last modified on: 10/5/19
Known bugs: none
*********************************************************************/
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
// Type definition for an int * pointer
typedef int* IntPtr;
// Global constant
constexpr int NUMLABS = 4;
// Function prototypes
/*
Creates the dynamic arrays for the labs.
@param labs: the array of labs,
@param labsizes: contains the size (or number of computers) of each lab
This dictates the size of the dynamic array.
@precondition: labsize[0] is the # of computers in lab1,
labsize[1] is the # of computers in lab2, ...
@postcondition: labs[0] points to lab1's array (of size given by labsize[0])
labs[1] points to lab2's array (of size given by labsize[1])
...
*/
void create_arrays(IntPtr labs[], int labsizes[]);
/*
Releases the memory we allocated with "new".
*/
void free_arrays(IntPtr labs[]);
/*
Displays the status of all labs (who is logged into which computer).
*/
void show_labs(IntPtr labs[], int labsizes[]);
// ======================
// login:
// Simulates a user login by asking for the login info from
// the console.
// ======================
void login(IntPtr labs[], int labsizes[]);
// ======================
// logoff:
// Searches through the arrays for the input user ID and if found
// logs that user out.
// ======================
void logoff(IntPtr labs[], int labsizes[]);
// ======================
// search:
// Searches through the arrays for the input user ID and if found
// outputs the station number.
// ======================
void search(IntPtr labs[], int labsizes[]);
int main()
{
IntPtr labs[NUMLABS]; // store the pointers to the dynamic array for each lab
int labsizes[NUMLABS]; // Number of computers in each lab
int choice = -1;
cout <<"Welcome to the LabMonitorProgram!\n";
// Prompt the user to enter labsizes
cout <<"Please enter the number of computer stations in each lab:\n";
for (int i=0; i< NUMLABS; i++)
{
do
{
cout <<"How many computers in Lab "<< i+1<<"? ";
cin >> labsizes[i];
} while (labsizes[i]<0);
}
// Create ragged array structure
create_arrays(labs, labsizes);
// Main Menu
while (choice != 0)
{
cout << endl;
show_labs(labs, labsizes);
cout << "MAIN MENU" << endl;
cout << "0) Quit" << endl;
cout << "1) Simulate login" << endl;
cout << "2) Simulate logoff" << endl;
cout << "3) Search" << endl;
cin >> choice;
if (choice == 1)
{
login(labs, labsizes);
}
else if (choice == 2)
{
logoff(labs, labsizes);
}
else if (choice == 3)
{
search(labs, labsizes);
}
}
free_arrays(labs); // Free memory before exiting
return 0;
}
void create_arrays(IntPtr labs[], int labsizes[])
{
//TODO: My function initiates pointers for each index of the labs array and
// assigns them to a new array the size of however many computers are in the
// lab. The function then goes through each of the four arrays, assigning
// every value to -1 so that each of the computers appear as empty.
// Hint: for each of the 4 labs, dynamically
// allocate an int array of size given by the number of computers in the lab.
// Initialize each element in the array to -1 (meaning an unused computer).
// Store the array in labs.
for (int i = 0; i < 4; i++)
{
labs[i] = new int[labsizes[i]];
for (int j = 0; j < labsizes[i]; j++)
{
labs[i][j] = -1;
}
}
}
/* TODO: This function frees the dynamic memory allocated when each of the
* labs[] array indexes were assigned to point to their own seperate array.
* These commands use the keyword delete followed by bracket operators and the
* name of each array in order to open the memory.
*/
void free_arrays(IntPtr labs[])
{
//TODO BY STUDENT
delete [] labs[0];
delete [] labs[1];
delete [] labs[2];
delete [] labs[3];
}
void show_labs(IntPtr labs[], int labsizes[])
{
int i;
int j;
cout << "LAB STATUS" << endl;
cout << "Lab # Computer Stations" << endl;
for (i=0; i < NUMLABS; i++)
{
cout << i+1 << " ";
for (j=0; j < labsizes[i]; j++)
{
cout << (j+1) << ": ";
if (labs[i][j] == -1)
{
cout << "empty ";
}
else
{
cout << setfill('0') << setw(4) << labs[i][j] << " ";
}
}
cout << endl;
}
cout << endl;
return;
}
void login(IntPtr labs[], int labsizes[])
{
int id, lab, num = -1;
// read user id
do
{
cout << "Enter the 4 digit ID number of the user logging in:" << endl;
cin >> id;
} while ((id < 0) || (id > 9999));
// read the lab number
do
{
cout << "Enter the lab number the user is logging in from (1-" <<
NUMLABS << "):" << endl;
cin >> lab;
} while ((lab < 0) || (lab > NUMLABS));
//read computer number
do
{
cout << "Enter computer station number the user is logging in to " <<
"(1-" << labsizes[lab-1] << "):" << endl;
cin >> num;
} while ((num < 0) || (num > labsizes[lab-1]));
// Check to see if this station is free
if (labs[lab-1][num-1]!=-1)
{
cout << "ERROR, user " << labs[lab-1][num-1] <<
" is already logged into that station." << endl;
return;
}
// Assign this station to the user
labs[lab-1][num-1] = id;
return;
}
void logoff(IntPtr labs[], int labsizes[])
{
int id, i,j;
// Get input from the keyboard, validating data ranges
do
{
cout << "Enter the 4 digit ID number of the user to find:" << endl;
cin >> id;
} while ((id < 0) || (id > 9999));
for (i=0; i<NUMLABS; i++) // check for each lab
{
for (j=0; j<labsizes[i]; j++) //if the user is using any computer in the lab
{
if (labs[i][j]==id) //if so, log the user off...
{
// Log the user off by setting the entry to -1
labs[i][j] = -1;
cout << "User " << id << " is logged off." << endl;
return;
}
}
}
cout << "That user is not logged in." << endl;
return;
}
/* TODO: The search function asks the user for the ID number of the user they
* would like to locate. It then searches each of the four stations for a
* matching ID by testing the equality between each of the ID values in the
* labs[] array and the user input ID. If the ID is found, the function
* returns the station number and computer number where the matching value
* was found.
*/
void search(IntPtr labs[], int labsizes[])
{
//TODO BY STUDENT
int entry_id;
cout << "Enter the four digit ID of the user to find: ";
cin >> entry_id;
cout << endl;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < labsizes[i]; j++)
{
if (*(labs[i]+j) == entry_id)
{
cout << "User " << entry_id << " is at Lab " << i+1;
cout << " Computer " << j+1 << endl;
}
}
}
}
| true |
100eb19cc979929eb988fec8ab3cd36a62753020 | C++ | lucaslavandeira/siu_guaramini | /src/server_Course.cpp | UTF-8 | 1,305 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <utility>
#include <set>
#include "server_Course.h"
#include "server_Lock.h"
Course::Course(int subject_id, int course_id, std::string name,
int teacher_id, int quota) :
subject_id(subject_id),
course_id(course_id),
name(name),
teacher_id(teacher_id),
quota(quota)
{
}
int Course::get_course() const {
return course_id;
}
bool Course::subscribe(int student_id) {
if (get_remaining_spots() == 0) {
return false;
}
if (students.find(student_id) != students.end()) {
return false;
}
students.insert(student_id);
return true;
}
bool Course::unsubscribe(int student_id) {
if (get_remaining_spots() == 0) {
return false;
}
unsigned long erased = students.erase(student_id);
return erased != 0;
}
std::string Course::get_name() const {
return name;
}
int Course::get_teacher() const {
return teacher_id;
}
int Course::get_remaining_spots() const {
return (int) (quota - students.size());
}
bool Course::is_subscribed(int student_id) const {
return students.find(student_id) != students.end();
}
int Course::get_subject() const {
return subject_id;
}
const std::set<int>& Course::get_students() const {
return students;
}
| true |
8ae604ee34c2f8745989f7731235b64139ef0748 | C++ | defacto2k15/TinTorrent | /TinTorrent/View/StoppedResourcesScreen.cpp | UTF-8 | 2,475 | 2.625 | 3 | [] | no_license | #include "StoppedResourcesScreen.h"
#include <iostream>
#include <ncurses.h>
StoppedResourcesScreen::StoppedResourcesScreen(std::string name, Kernel *k) : Screen(name, k)
{
choisePos = 0;
pageNumber = 1;
ProgramInfoProvider infoProvider = kernel->getProgramInfoProvider();
localResources = infoProvider.getRevertedResources();
}
void StoppedResourcesScreen::drawScreen()
{
printw( "<- Q-powrót \n" );
printw( "Zakazane zasoby: %d [Strona %d/%d]\n", localResources.size(),
pageNumber, localResources.size()/PAGE_SIZE+1 );
printw( "%20s%12s\n", "Nazwa:", "Rozmiar:" );
std::vector<Resource>::iterator resEnd = (pageNumber * PAGE_SIZE < localResources.size() ? localResources.begin() + (pageNumber-1)*PAGE_SIZE + PAGE_SIZE : localResources.end());
int i = 0;
for(std::vector<Resource>::iterator it = localResources.begin()+(pageNumber-1)*PAGE_SIZE;
it != resEnd; ++it)
{
std::string resourceName = StringHelp::toUtf8((*it).getResourceName());
if(i == choisePos) { attron( A_UNDERLINE); attron(COLOR_PAIR(2)); }
printw( "%20.20s%12d\n", resourceName.c_str(),
(*it).getResourceSize());
attroff( A_UNDERLINE); attron(COLOR_PAIR(3));
i++;
}
}
std::string StoppedResourcesScreen::inputHandle()
{
int input = getch();
switch(input) {
case KEY_DOWN:
if((unsigned)++choisePos >= (pageNumber*PAGE_SIZE < localResources.size() ? PAGE_SIZE : localResources.size()-(pageNumber-1)*PAGE_SIZE)) choisePos = 0;
break;
case KEY_UP:
choisePos--;
if(choisePos < 0) choisePos = (pageNumber*PAGE_SIZE < localResources.size() ? PAGE_SIZE-1 : localResources.size()-(pageNumber-1)*PAGE_SIZE-1);
break;
case KEY_RIGHT:
if(pageNumber < localResources.size()/PAGE_SIZE+1) pageNumber++;
break;
case KEY_LEFT:
if(pageNumber > 1) pageNumber--;
break;
case KEY_F(5):
{
choisePos = 0;
ProgramInfoProvider infoProvider = kernel->getProgramInfoProvider();
localResources = infoProvider.getRevertedResources();
break;
}
case 113: // KEY_Q
return "main_menu";
}
return "";
}
void StoppedResourcesScreen::refresh()
{
ProgramInfoProvider infoProvider = kernel->getProgramInfoProvider();
localResources = infoProvider.getRevertedResources();
if((unsigned)choisePos > (pageNumber*PAGE_SIZE < localResources.size() ? PAGE_SIZE : localResources.size()-(pageNumber-1)*PAGE_SIZE)) choisePos = (pageNumber*PAGE_SIZE < localResources.size() ? PAGE_SIZE-1 : localResources.size()-(pageNumber-1)*PAGE_SIZE-1);
} | true |
2133c6fd7036a9bf7b6ba5353020a6257bef6304 | C++ | Onetaway/My-Cpp-Way | /My Cpp Way/STL/Friend.h | UTF-8 | 729 | 2.578125 | 3 | [] | no_license | //
// Friend.h
// My Cpp Way
//
// Created by sanlen on 9/3/14.
// Copyright (c) 2014 Onetaway. All rights reserved.
//
#ifndef __My_Cpp_Way__Friend__
#define __My_Cpp_Way__Friend__
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
class Friend {
public:
Friend();
~Friend(){
}
void setAge(int friendAge) {
age = friendAge;
}
void setHeight(float friendHeight) {
height = friendHeight;
}
void setName(string friendName) {
name = friendName;
}
void prinfFriendInfo();
private:
int age;
float height;
string name;
};
#endif /* defined(__My_Cpp_Way__Friend__) */
| true |
f9eb9771bd09c8a7c27049ea7b9059b4856955a8 | C++ | Armando437121/OrnelasArmado_CIS5_SUMMER2016 | /CLASS/search/main.cpp | UTF-8 | 1,598 | 3.359375 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Armando Ornelas
* Created on July 11th, 2016, 1:20 PM
* Purpose: Template
*/
//System Libraries
#include <iostream> //Input/Output Library
#include <cstdlib> //Random
#include <iomanip> //Formatting
#include <ctime> //Time
using namespace std; //Namespace of the System Libraries
//User Libraries
//Global Constants
//Function Prototypes
int random(int,int);//Random number with a begin and end point
void filAray(int [],int);//Ordered Random 4 digit numbers
void prntAry(int [],int,int);
int binSrch(int [],)
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
srand(static_cast<unsigned int>(time(0)));
//Declare Variables
const int SIZE=100;
int array[SIZE];
//Input Data
filAray(array,SIZE);
//Process the Data
//Output the processed Data
prntAry(array,SIZE,10);
//Exit Stage Right!
return 0;
}
int binSrch(int a[],int n,int val){
//Declare Variables
int beg=0, end=n-1;
//Loop until we find
do{
int middle=(end+beg)/2;
if(a[middle]==val)return middle;
else(a[middle]<val)
end=middle;
}while(end>=beg);
return -1;
}
int linSrch(int a[],)
void prntAry(int a[],int n,int val){
for(int i=0;i<n;i++){
if(a[i]==val)return i;
}
return -1;
}
void filAray(int a[],int n)
{
int step=10;
for(int i=0, beg=1000;i<n;i++,beg+=step){
a[i]=trandom(beg,beg+step);
}
}
int random(int beg,int end)
{
return rand()%(end-beg+1)+beg;
}
| true |
78f2369904caa0fffc4d2cc762ba2298c37a6c1a | C++ | briangreeley/11_Virtual_BaseClassPointers_Employee_Manager | /src/Employee.h | UTF-8 | 375 | 2.953125 | 3 | [] | no_license | /*
* Employee.h
*
* Created on: Nov 6, 2017
* Author: keith
*/
#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_
#include <string>
class Employee {
public:
Employee(std::string theName, float thePayRate);
virtual ~Employee();
std::string getName()const;
float pay(float hoursWorked) const;
protected:
std::string name;
float payrate;
};
#endif /* EMPLOYEE_H_ */
| true |
d1a84684b843be5dfdc75f57c1539158aaa60bdb | C++ | weidaru/logo_detection | /logo_detection_dev/include/LogoletSimulator.h | UTF-8 | 980 | 2.703125 | 3 | [] | no_license | #include <opencv/cv.h>
#include <vector>
#include <tr1/memory>
#ifndef LOGOLETSIMULATOR_H
#define LOGOLETSIMULATOR_H
class dataEntry;
struct Logolet
{
dataEntry* toDataEntry(int size, double target);
double* toArray(int size);
int x, y ,width, height, rowIndex, colIndex;
cv::Mat data;
};
struct LogoPosition
{
LogoPosition(): x(0), y(0), width(0), height(0) {}
int x, y, width, height;
};
class LogoletSimulator
{
public:
typedef std::tr1::shared_ptr<Logolet> t_logolet_ptr;
typedef std::vector<t_logolet_ptr > t_data_vector;
public:
LogoletSimulator(cv::Mat m, int w, int h);
LogoletSimulator& setSource(cv::Mat);
cv::Mat& getSource();
t_data_vector& getDataVector();
int getWidth();
int getHeight();
int getRowCount();
int getColCount();
private:
t_data_vector datas;
cv::Mat source;
int width, height;
};
#endif //LOGOLETSIMULATOR_H
| true |
03dfa25ad9ddf4fc2a4d1b9757842b0c02ddadd1 | C++ | emanuelpeg/codigoCpp2019 | /tp5/colecction/TP2-POO/lista.cpp | UTF-8 | 1,501 | 3.4375 | 3 | [
"Apache-2.0"
] | permissive | #include "lista.h"
#include <iostream>
using namespace std;
Lista::Lista(){
cantidad=0;
}
Lista::Lista(int valor)
{
acceso = new nodo;
acceso->dato=valor;
acceso->sig=NULL;
cantidad=1;
}
Lista::~Lista(){
nodo *borro=acceso;
nodo *x;
while (borro!=NULL) {
x=borro->sig;
delete borro;
borro=x;
}
}
bool Lista::alta(int valor)
{
nodo *aux=acceso;
nodo *ant=NULL;
while(aux!=NULL) {
ant=aux;
aux=aux->sig;
}
aux=new nodo;
aux->dato=valor;
aux->sig=NULL;
if (ant!=NULL) ant->sig=aux;
else acceso=aux;
cantidad++;
return true;
}
bool Lista::baja(int e) {
nodo *aux=acceso;nodo *ant=NULL;
while ((aux->dato!=e) and (aux!=NULL)) {
ant=aux;
aux=aux->sig;
if (aux==NULL) return false;
}
if (ant!=NULL) ant->sig=aux->sig;
else acceso=aux->sig;
delete aux;
cantidad--;
return true;
}
void Lista::recorrer() {
nodo *aux=acceso;
while(aux!=NULL) {
cout<<aux->dato<<" ";
aux=aux->sig;
}
}
int Lista::getSize() {
return cantidad;
}
int Lista::getValue(int valor) {
nodo *aux=acceso;
for (int i=0; i<valor; i++) {
aux=aux->sig;
}
return aux->dato;
}
bool Lista::contains(int n) {
nodo *aux=acceso;
while(aux!=NULL) {
if (aux->dato==n) return true;
aux=aux->sig;
}
return false;
}
| true |
d2f6cc86906d0f1b5044d1abb6b398e039ea2a12 | C++ | wileyw/opencv_swig | /test_function.cpp | UTF-8 | 1,472 | 2.578125 | 3 | [] | no_license | #include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <cctype>
#include <iostream>
#include <iterator>
#include <stdio.h>
#include "test_function.hpp"
using namespace std;
using namespace cv;
string cascadeName = "haarcascade_frontalface_alt.xml";
vector<FaceLocation> detectFaces(vector<char>& jpg, double scale)
{
vector<FaceLocation> faceLocations;
Mat img = imdecode(jpg, CV_LOAD_IMAGE_COLOR);
if ( img.data == NULL) {
cerr << "Image loading error." << endl;
return faceLocations;
}
CascadeClassifier cascade;
if( !cascade.load( cascadeName ) ){
cerr << "ERROR: Could not load classifier cascade" << endl;
return faceLocations;
}
int i = 0;
double t = 0;
vector<Rect> faces;
Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
cvtColor( img, gray, CV_BGR2GRAY );
resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
cascade.detectMultiScale( smallImg, faces,
1.1, 2, CV_HAAR_SCALE_IMAGE, Size(30, 30) );
faceLocations.resize(faces.size());
for( int i = 0; i < faces.size(); i++){
faceLocations[i].x = faces[i].x;
faceLocations[i].y = faces[i].y;
faceLocations[i].width = faces[i].width;
faceLocations[i].height = faces[i].height;
}
return faceLocations;
}
| true |
42b231f0357271ada2f55de9f934b4ef02752c48 | C++ | lzhou835/leetcode | /164.Maximum_Gap.cpp | UTF-8 | 825 | 2.59375 | 3 | [] | no_license | class Solution {
public:
int maximumGap(vector<int>& nums) {
if(nums.size()<2) return 0;
int mn=INT_MAX, mx=INT_MIN, n=nums.size();
for(auto a:nums){
mn=min(mn, a);
mx=max(mx, a);
}
int size=(mx-mn)/n+1;
int cnt=(mx-mn)/size+1;
vector<int> bmin(cnt, INT_MAX);
vector<int> bmax(cnt, INT_MIN);
set<int> s;
for(int i=0;i<n;i++){
int id=(nums[i]-mn)/size;
bmin[id]=min(bmin[id], nums[i]);
bmax[id]=max(bmax[id], nums[i]);
s.insert(id);
}
int pre=0, res=0;
for(int i=1;i<cnt;i++){
if(!s.count(i)) continue;
res=max(res, bmin[i]-bmax[pre]);
pre=i;
}
return res;
}
};
| true |
5a834e2a800ea861dc41df60b8f3423512127478 | C++ | 20143104/KMU | /2017-1/c++/project/tetris02/main.cpp | UTF-8 | 2,053 | 2.578125 | 3 | [] | no_license | #include"main.h"
#include<time.h>
#include<ncurses.h>
#include<fstream>
#include <stdio.h>
#include<iostream>
#include <unistd.h>
using namespace std;
int changefilekey(char cur_key){
if(cur_key=='l')
return 1;
else if(cur_key=='r')
return 2;
else if(cur_key=='g')
return 3;
else if(cur_key=='d')
return 4;
}
int main(int argc, char* argv[]){
ifstream instream;
char name[100]={};
int id;
bool isgameover=true;
if(argc>1){
instream.open(argv[1]);
//instream>>name>>id;
}
Tetris t;
t.updateScreen(); //초기 게임 화면
int startkey = getch();
if(startkey==10){ //enter키 시작
Block gameblock;
Score sc;
int board[10][20]={0,}; //게임판 생성
gameblock.Oblock(board); // 초기 블록 생성
t.updateboardpane(board); //화면 표시
while(isgameover){
if(!(gameblock.Checkdown(board))){ //내려갈 곳 없으면
t.isFullline(board,sc);//줄 다차면 블럭 제거후 밑으로 내린 후 점수 계산
if(t.isGameover(board))//생성될수 없으면 게임오버
break;
gameblock.Oblock(board);//블럭 생성
}
t.updateboardpane(board);//보드판 갱신
if(argc>1){//인풋값이 있으면
char cur_key;
instream>>cur_key;
if(cur_key=='q')
break;
int change=changefilekey(cur_key);//문자를 정수로 치환
t.play(board,gameblock,change);
usleep(500000);
}
else{//키보드로 부터 입력 받아
while(1){
halfdelay(5);
int ch = getch();
if(ch==ERR){ // 키보드로부터 입력이 없으면
if(gameblock.Checkdown(board))
gameblock.Movedown(board);
else
break;
t.updateboardpane(board);
}
if(ch == 113){
isgameover = false;
break;
}
t.play(board,gameblock,ch);
}
}
}
cbreak();
t.printEnd(sc);
int outkey = getch();
}
return 0;
}
| true |
12553d212365b56b7b30757462973ab6d19c22e4 | C++ | evgenypanin/Stiven_Prata_book_cpp | /chapter_7/3.cpp | UTF-8 | 1,399 | 3.484375 | 3 | [] | no_license | #include <iostream>
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
void show_struct(const box *razmer);
void mul_volume(box *structing);
void fill_struct(box *structing);
int main()
{
using namespace std;
box expenses;
fill_struct(&expenses);
show_struct(&expenses);
mul_volume(&expenses);
show_struct(&expenses);
return 0;
}
void fill_struct(box *structing)
{
using namespace std;
cout << "Enter the maker: ";
cin.getline(structing->maker, 40);
cout << "Enter the height: ";
cin >> structing->height;
cout << "Enter the width: ";
cin >> structing->width;
cout << "Enter the length: ";
cin >> structing->length;
cout << "Enter the volume: ";
cin >> structing->volume;
cin.get();
}
void mul_volume(box *structing)
{
std::cout << "Mull three data in structing.volume\n";
structing->volume = structing->height * structing->length * structing->width;
}
void show_struct(const box *structing)
{
std::cout << "Full struct Box\n";
std::cout << "Maker: " << structing->maker << "\n"
<< "Height: " << structing->height << "\n"
<< "Width: " << structing->width << "\n"
<< "Length: " << structing->length << "\n"
<< "Volume: " << structing->volume << "\n";
}
| true |
f32690f98ee3b53569c7b50cb50173dc22971e02 | C++ | SunNEET/LeetCode | /Array/15_3Sum.cpp | UTF-8 | 1,709 | 3.453125 | 3 | [] | no_license | class Solution {
// 跟前一題2sum是類似的作法,先枚舉一個數字,再直接去找能滿足的情況
// 這題就是直接找j+k = -i,所以用two pointer表示j跟k
// 從前後開始往內找是因為有排序過以後,可以保證a[j+1]>=a[j]而a[k-1]<=a[k]
// 因此,當我們找出來的a[i]+a[j]+a[k]的值<0的話,就去遞增j,可以保證sum增加/不變
// 反之就遞減k,保證sum變小/不變,以此來逼近0,就能在O(n)內找出有可能的j+k組合。
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> ans;
if(nums.size()<=2) return ans;
std::sort(nums.begin(), nums.end());
for(int i=0;i<nums.size()-2;i++) {
int j = i+1;
int k = nums.size()-1;
while(j < k) {
if(nums[i]+nums[j]+nums[k] == 0) {
vector<int> tmp;
tmp.push_back(nums[i]);
tmp.push_back(nums[j]);
tmp.push_back(nums[k]);
ans.push_back(tmp);
j++; k--;
//調過重複的答案,因為排序過了,遞增遞減直到不是重複的a[j]或a[k]就好
while(j<k && nums[j] == nums[j-1]) j++;
while(j<k && nums[k] == nums[k+1]) k--;
} else if(nums[i]+nums[j]+nums[k] < 0) {
j++;
} else {
k--;
}
}
//如果下個枚舉的還是一樣的數,就跳過
while(i<nums.size()-2 && nums[i] == nums[i+1]) i++;
}
return ans;
}
}; | true |
4d1712eba265c7179beddea2bad6a83d88c0805f | C++ | royforlinux/pi2jamma-fe | /src/core/file/FilePath.hpp | UTF-8 | 658 | 2.65625 | 3 | [] | no_license | #pragma once
#include "core/StringSpan.hpp"
#include <vector>
#include <string>
#define PATH_SEP_STR "/"
const char PATH_SEP_CHAR = '/';
std::string joinPath(const std::initializer_list<StringSpan>& parts);
std::vector<std::string> splitPath(StringSpan stringSpan);
std::string getPathEntryName(StringSpan stringSpan);
inline std::string joinPath(
StringSpan s1,
StringSpan s2)
{
return joinPath({s1,s2});
}
inline std::string joinPath(
StringSpan s1,
StringSpan s2,
StringSpan s3)
{
return joinPath({s1,s2,s3});
}
inline std::string joinPath(
StringSpan s1,
StringSpan s2,
StringSpan s3,
StringSpan s4)
{
return joinPath({s1,s2,s3,s4});
}
| true |
2d6e257939d29d2af93138c9b85638c57f57e84b | C++ | gura-lang/gurax | /src/lib/VType_Object.cpp | UTF-8 | 6,262 | 2.53125 | 3 | [] | no_license | //==============================================================================
// VType_Object.cpp
//==============================================================================
#include "stdafx.h"
namespace Gurax {
//------------------------------------------------------------------------------
// Help
//------------------------------------------------------------------------------
static const char* g_docHelp_en = u8R"""(
# Overview
# Predefined Variable
${help.ComposePropertyHelp(Object, `en)}
# Operator
# Cast Operation
${help.ComposeConstructorHelp(Object, `en)}
${help.ComposeMethodHelp(Object, `en)}
)""";
//------------------------------------------------------------------------------
// Implementation of constructor
//------------------------------------------------------------------------------
// Object() {block?}
Gurax_DeclareConstructor(Object)
{
Declare(VTYPE_Color, Flag::None);
DeclareBlock(BlkOccur::ZeroOrOnce);
AddHelp(Gurax_Symbol(en), u8R"""(
Creates an `Object` instance.
)""");
}
Gurax_ImplementConstructor(Object)
{
// Function body
return argument.ReturnValue(processor, new Value_Object());
}
//------------------------------------------------------------------------------
// Implementation of method
//------------------------------------------------------------------------------
// Object#__clone__()
Gurax_DeclareMethod(Object, __clone__)
{
Declare(VTYPE_Any, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Creates a cloned object.
)""");
}
Gurax_ImplementMethod(Object, __clone__)
{
// Target
auto& valueThis = GetValueThis(argument);
// Arguments
RefPtr<Value> pValue(valueThis.Clone());
if (pValue) return pValue.release();
Error::Issue(ErrorType::ValueError, "failed to create a cloned object");
return Value::nil();
}
// Object#__instanceOf__(vtype as VType)
Gurax_DeclareMethod(Object, __instanceOf__)
{
Declare(VTYPE_Bool, Flag::None);
DeclareArg("vtype", VTYPE_VType, ArgOccur::Once, ArgFlag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
Returns `true` if the object is an instance of the specified `vtype`.
)""");
}
Gurax_ImplementMethod(Object, __instanceOf__)
{
// Target
auto& valueThis = GetValueThis(argument);
// Arguments
ArgPicker args(argument);
const VType& vtype = args.Pick<Value_VType>().GetVTypeThis();
// Function body
return new Value_Bool(valueThis.IsInstanceOf(vtype));
}
// Object##__prop__(symbol as Symbol):map {block?}
Gurax_DeclareHybridMethod(Object, __prop__)
{
Declare(VTYPE_Bool, Flag::Map);
DeclareArg("symbol", VTYPE_Symbol, ArgOccur::Once, ArgFlag::None);
DeclareBlock(BlkOccur::ZeroOrOnce);
AddHelp(Gurax_Symbol(en), u8R"""(
Returns the value of the specified property.
)""");
}
Gurax_ImplementHybridMethod(Object, __prop__)
{
// Target
auto& valueThis = GetValueThis(argument);
// Arguments
ArgPicker args(argument);
const Symbol* pSymbol = args.PickSymbol();
// Function body
RefPtr<Value> pValue(valueThis.DoGetProperty(pSymbol, argument.GetAttr(), false));
if (!pValue) return Value::nil();
return argument.ReturnValue(processor, pValue.release());
}
// Object#__str__()
Gurax_DeclareClassMethod(Object, __str__)
{
Declare(VTYPE_String, Flag::None);
StringStyle::DeclareAttrOpt(*this);
AddHelp(Gurax_Symbol(en), u8R"""(
Converts the object to a string.
)""");
}
Gurax_ImplementClassMethod(Object, __str__)
{
// Target
auto& valueThis = GetValueThis(argument);
// Argument
StringStyle::Flags flags = StringStyle::ToFlags(argument);
// Function body
return new Value_String(valueThis.ToString(StringStyle(flags)));
}
//------------------------------------------------------------------------------
// Implementation of property
//------------------------------------------------------------------------------
// Object##__id__
Gurax_DeclareHybridProperty_R(Object, __id__)
{
Declare(VTYPE_VType, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
The object ID.
)""");
}
Gurax_ImplementHybridPropertyGetter(Object, __id__)
{
auto& valueThis = GetValueThis(valueTarget);
return new Value_String(String().Format("#%p", &valueThis));
}
// Object##__vtype__
Gurax_DeclareHybridProperty_R(Object, __vtype__)
{
Declare(VTYPE_VType, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
The value type of this object.
)""");
}
Gurax_ImplementHybridPropertyGetter(Object, __vtype__)
{
auto& valueThis = GetValueThis(valueTarget);
VType& vtype = valueThis.IsType(VTYPE_VType)?
Value_VType::GetVTypeThis(valueThis) : valueThis.GetVTypeCustom();
return new Value_VType(vtype);
}
// Object##__vtypeInh__
Gurax_DeclareHybridProperty_R(Object, __vtypeInh__)
{
Declare(VTYPE_VType, Flag::None);
AddHelp(Gurax_Symbol(en), u8R"""(
The value type of this object's parent class.
)""");
}
Gurax_ImplementHybridPropertyGetter(Object, __vtypeInh__)
{
auto& valueThis = GetValueThis(valueTarget);
VType& vtype = valueThis.IsType(VTYPE_VType)?
Value_VType::GetVTypeThis(valueThis) : valueThis.GetVTypeCustom();
VType& vtypeInh = vtype.GetVTypeInh();
if (vtypeInh.IsInvalid()) return Value::nil();
return new Value_VType(vtypeInh);
}
//------------------------------------------------------------------------------
// VType_Object
//------------------------------------------------------------------------------
VType_Object VTYPE_Object("Object");
void VType_Object::DoPrepare(Frame& frameOuter)
{
// Add help
AddHelp(Gurax_Symbol(en), g_docHelp_en);
// Declaration of VType
Declare(VType::Invalid, Flag::Immutable, Gurax_CreateConstructor(Object));
// Assignment of method
Assign(Gurax_CreateMethod(Object, __clone__));
Assign(Gurax_CreateMethod(Object, __instanceOf__));
Assign(Gurax_CreateMethod(Object, __prop__));
Assign(Gurax_CreateMethod(Object, __str__));
// Assignment of property
Assign(Gurax_CreateProperty(Object, __id__));
Assign(Gurax_CreateProperty(Object, __vtype__));
Assign(Gurax_CreateProperty(Object, __vtypeInh__));
}
//------------------------------------------------------------------------------
// Value_Object
//------------------------------------------------------------------------------
VType& Value_Object::vtype = VTYPE_Object;
String Value_Object::ToString(const StringStyle& ss) const
{
return String().Format("<%s>", GetVTypeCustom().MakeFullName().c_str());
}
}
| true |
5f3575e2dc2c6c655f1517daad8e3396051c5928 | C++ | mishranitesh/LeetCode_Solutions | /Easy_Category_Problems/141_Linked_List_Cycle_E.cpp | UTF-8 | 1,661 | 3.578125 | 4 | [] | no_license | /*
141. Linked List Cycle (EASY)
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents
the position (0-indexed) in the linked list where tail connects to.
If pos is -1, then there is no cycle in the linked list.
Input: head = [3,2,0,-4], pos = 1 head = [1,2], pos = 0 head = [1], pos = -1
Output: true true false
*/
// Includes all standard library (ONLY for GCC, not standard C++ library)
#include <bits/stdc++.h>
using namespace std;
// Definition for singly-linked list
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
/*
* Class to perform 'Linked List Cycle' implementation
*/
class LinkedListCycleSolution {
public:
/*
* Method to implement 'Linked List Cycle'
* Tortoise-Rabbit (Two Pointer Approach)
*/
bool hasCycle(ListNode *head) {
// Corner case
if (!head || !(head->next) || !(head->next->next)) return false;
// Local variable
ListNode *slowIter = head, *fastIter = head->next->next;
// Traverse until Fast Iterator reached tail of list
while (fastIter != nullptr) {
// In case of cycle - Fast will meet Slow Iterator
if (slowIter == fastIter) return true;
// Modify slow and fast iterators
slowIter = slowIter->next;
if (fastIter->next && fastIter->next->next)
fastIter = fastIter->next->next;
else
fastIter = nullptr;
}
return false;
}
};
/*
* Driver Code
*/
int main() {
// TODO
return 0;
} | true |
594f8b377ecc329628d46134fbb2421c9242b47a | C++ | LGuitron/CyPS | /UnitTest/ValueParametrized/valueParametrized.cc | UTF-8 | 1,140 | 2.796875 | 3 | [] | no_license | #include "gtest/gtest.h"
#include "valueParametrized.h"
using ::testing::Range;
using ::testing::Values;
using ::testing::ValuesIn;
using ::testing::Bool;
using ::testing::Combine;
class Fixture : public ::testing::TestWithParam<int>{};
class Chars: public::testing::TestWithParam<char>{};
class Bools: public::testing::TestWithParam<bool>{};
class IntComb: public::testing::TestWithParam<::testing::tuple<int,int>>
{
public:
int value1 = ::testing::get<0>(GetParam());
int value2 = ::testing::get<1>(GetParam());
};
TEST_P(Fixture, testA)
{
printValue(GetParam());
}
TEST_P(Chars, testB)
{
printValue(GetParam());
}
TEST_P(Bools, testC)
{
printValue(GetParam());
}
TEST_P(IntComb, testD)
{
printValues(value1,value2);
}
//Fixture Test
INSTANTIATE_TEST_CASE_P(enteros, Fixture, Values(1,2,3,4,5));
//Chars Test
char arrayC [] = {'a','b','c','d','e','f','g'};
INSTANTIATE_TEST_CASE_P(caracteres, Chars, ValuesIn(arrayC));
//Bools Test
INSTANTIATE_TEST_CASE_P(booleanos, Bools, Bool());
//Int combination Test
INSTANTIATE_TEST_CASE_P(CombinacionEnteros, IntComb, Combine(Range(10,100,1), Range(10,100,1)));
| true |
5bcc343ee2a0ae0ce7a0553faf5a676c627d27bc | C++ | chrystallagh/HavadjiaChrystalla_CSC17a_42824 | /Homework/Assignment 1 /Gaddis_Probl7.6/main.cpp | UTF-8 | 2,310 | 3.421875 | 3 | [] | no_license | /*
* File: newmain.cpp
* Author: chrystallahavadjia
* Purpose: Temperature conversions
* 7.6
*/
//System Libraries
#include <iostream>
#include<fstream>
using namespace std;
//User Libraries
//Global Constants
//Function Prototypes
//Execution Begins Here
int main()
{
const int MONTH = 3;
const int DAYS = 30;
int rainy = 0;
int cloudy = 0;
int sunny = 0;
int rainyTot = 0;
int cloudyTot=0;
int sunnyTot = 0;
int wettestMonth = -1;
int month = 0;
char metereologyData[MONTH][DAYS];
ifstream weather;
//OPEN file
weather.open("/Users/chrystallahavadjia/Desktop/rainyfile.txt");
if (!weather)
cout << "fail" <<endl;
//write file information in array
for (int m = 0; m < MONTH; m++)
{
for (int d = 0; d < DAYS; d++)
{
weather >> metereologyData[m][d];
}
}
// calculate how many days were rainy,cloudy or sunny
cout << "Days of each type for each month:";
for (int i=0; i < MONTH; i++)
{
rainy = 0;
sunny = 0;
cloudy = 0;
for(int d = 0; d < DAYS; d++)
{
if (metereologyData[i][d] == 'R' || metereologyData[i][d] == 'r')
rainy++;
else if (metereologyData[i][d] == 'C' || metereologyData[i][d] == 'c')
cloudy++;
else if (metereologyData[i][d] == 'S' || metereologyData[i][d] == 's' )
sunny++;
}
if (rainy > wettestMonth)
{
wettestMonth >> rainy;
month >> i;
}
//to find total rainy days of all months
rainyTot = rainyTot + rainy;
cloudyTot = cloudyTot+ cloudy;
sunnyTot = sunnyTot + sunny;
cout << "\n Month " << i+1 << " :\n"<< endl;
cout << " rainy " << rainy << endl << " cloudy " << cloudy << endl << " sunny " << sunny << endl;
}
cout << "Total days of rain: " << rainyTot << endl;
cout << "Total cloudy days: " << cloudyTot << endl;
cout << "Total sunny days: " << sunnyTot <<endl;
cout << "The months with the most rainy days is: Month " << month + 1 << endl;
weather.close();
return 0;
} | true |
ec9b787b195bcec1e6dc1dfd547768e653e8171c | C++ | tonytej/XMLParser | /lab2/lab2/lab2.cpp | UTF-8 | 7,520 | 3.171875 | 3 | [] | no_license | // lab2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <deque>
#include <regex>
using namespace std;
/*! A class containing a vector of string that makes up a node */
class Node {
private:
vector<string> attributes;
public:
void insertAttribute(string att);
friend bool operator<(const Node& lhs, const Node& rhs);
void clearVector();
string getAttributes(int subscript);
};
/**
* Insert element to the vector of string
*
* @param att string to be pushed
*/
void Node::insertAttribute(string att) {
attributes.push_back(att);
}
void Node::clearVector() {
attributes.clear();
}
/**
* Get attributes from the private vector
*
* @param subscript subscript to access specific attributes
* @return element inside attribute
*/
string Node::getAttributes(int subscript) {
return attributes[subscript];
}
/*! A class containing regular expressions functions needed to parse the XML file */
class regexFunctions {
private:
string pattern1;
public:
bool search(string text, string expr);
string split(string text, string split);
string replace(string text, string find, string value);
};
/**
* Search for strings that match the expression
*
* @param text text to be searched at
* @param expr expression to match
* @return status true if found else false
*/
bool regexFunctions::search(string text, string expr){
bool status;
regex pattern(expr);
if (regex_search(text.begin(), text.end(), pattern)) {
status = true;
}
else {
status = false;
}
return status;
}
/**
* Split string of matched strings using expression
*
* @param text text to be splitted
* @param split expression to match
* @return splitted string
*/
string regexFunctions::split(string text, string split){
sregex_token_iterator end;
regex pattern(split);
for (sregex_token_iterator iter(text.begin(), text.end(), pattern); iter != end; ++iter){
if ((*iter).length() > 0)
{
if ((static_cast<string>(*iter))[0] != 0x20)
return *iter;
}
}
return "Split Fail!";
}
/**
* Replace matched string with other string
*
* @param text text to be processed
* @param find expression to be matched
* @param value string to replace matched string
* @return remaining string
*/
string regexFunctions::replace(string text, string find, string value){
regex pattern(find);
string sresult = regex_replace(text, pattern, value);
return sresult;
}
/*! A class with a purpose of parsing the XML file */
class XMLParser {
private:
deque<string> elements;
stack<string> tag;
vector<Node> node;
Node temp;
public:
void process(regexFunctions rf, string filepath);
void sortVector();
vector<Node> getVector();
};
/**
* Process the XML file
*
* @param rf regexFunctions class providing necessary functions
* @param filepath string of the xml file path
*/
void XMLParser::process(regexFunctions rf, string filepath) {
ifstream fin(filepath);
if (fin.fail()) {
cout << "Input file failed to open." << endl;
exit(1);
}
string str;
int count = 0;
while (!fin.eof()) {
getline(fin, str);
if (rf.search(str, "\t</") || rf.search(str, " </")) { //termination condition
string var = str;
if (tag.top() == var) {
tag.pop();
}
if (count == 5) {//if all data is parsed (end of one node)
count = 0;//reset counter due to end of one node
for (size_t i = 0; i < elements.size(); i++) {
temp.insertAttribute(elements[i]);//insert each element from deque to node
}
node.push_back(temp);//insert node to a vector of node
temp.clearVector();//clear node for next set of data
elements.clear();//clear deque for next set of data
}
}
else if (rf.search(str, ">(.*?)<")) { //elements condition
string var = rf.split(str, ">(.*?)(?=<)");//get data without tags
var = rf.replace(var, ">", "");
elements.push_back(var);//push var to deque
count++;
}
else { //tags condition
tag.push(str);
}
}
}
void XMLParser::sortVector() {
sort(node.begin(), node.end());
}
/**
* Get the private vector of nodes from the class
* @return node
*/
vector<Node> XMLParser::getVector() {
return node;
}
/*! A class containing functions to calculate the distance between two airports */
class distanceCalculator {
private:
/// @brief The usual PI/180 constant
const double DEG_TO_RAD = 0.017453292519943295769236907684886;
/// @brief Earth's quatratic mean radius for WGS-84
const double EARTH_RADIUS_IN_METERS = 6372797.560856;
public:
int rBinarySearch(vector<Node> vec, int first, int last, string key);
double ArcInRadians(Node& from, Node& to);
double DistanceInMeters(Node& from, Node& to);
};
/**
* Binary Search Algorithm
*
* @param vec vector to be searched at
* @param first left boundary
* @param last right boundary
* @param code airport code to be searched
* @return index of the code
*/
int distanceCalculator::rBinarySearch(vector<Node> vec, int first, int last, string code) {
if (first <= last) {
int mid = (first + last) / 2; // compute mid point.
if (code == vec[mid].getAttributes(0))
return mid; // found it.
else if (code < vec[mid].getAttributes(0))
// Call ourself for the lower part of the array
return rBinarySearch(vec, first, mid - 1, code);
else
// Call ourself for the upper part of the array
return rBinarySearch(vec, mid + 1, last, code);
}
return -(first + 1); // failed to find key
}
/**
* Computes the arc, in radian, between two WGS-84 positions.
*
* @param from initial position
* @param to destination
* @return arc in radians
*/
double distanceCalculator::ArcInRadians(Node& from, Node& to) {
double fromLat = stod(from.getAttributes(3));
double fromLon = stod(from.getAttributes(4));
double toLat = stod(to.getAttributes(3));
double toLon = stod(to.getAttributes(4));
double latitudeArc = (fromLat - toLat) * DEG_TO_RAD;
double longitudeArc = (fromLon - toLon) * DEG_TO_RAD;
double latitudeH = sin(latitudeArc * 0.5);
latitudeH *= latitudeH;
double lontitudeH = sin(longitudeArc * 0.5);
lontitudeH *= lontitudeH;
double tmp = cos(fromLat*DEG_TO_RAD) * cos(toLat*DEG_TO_RAD);
return 2.0 * asin(sqrt(latitudeH + tmp*lontitudeH));
}
/**
* Computes the distance, in meters, between two WGS-84 positions.
*
* @param from initial position
* @param to destination
* @return distance in meters
*/
double distanceCalculator::DistanceInMeters(Node& from, Node& to) {
return EARTH_RADIUS_IN_METERS*ArcInRadians(from, to);
}
/**
* Enable debugging in Visual Studio
*/
void enableDebug(bool bvalue){
if (!bvalue) return;
int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
// Turn on leak-checking bit.
tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
// Turn off CRT block checking bit.
tmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
// Set flag to the new value.
_CrtSetDbgFlag(tmpFlag);
}
int main()
{
enableDebug(true);
XMLParser test;
regexFunctions rf;
distanceCalculator calc;
test.process(rf, "Airports.xml");
test.sortVector();
int airport1 = calc.rBinarySearch(test.getVector(), 0, test.getVector().size(), "GSO");
int airport2 = calc.rBinarySearch(test.getVector(), 0, test.getVector().size(), "HTS");
double result = calc.DistanceInMeters(test.getVector()[airport1], test.getVector()[airport2]);
cout << "Distance from GSO to HTS is " << result << " meters"<< endl;
}
/**
* Overloaded < operator for sorting vector of objects
*/
bool operator<(const Node& lhs, const Node& rhs) {
return lhs.attributes[0] < rhs.attributes[0];
}
| true |
64cde444e2bef2630504144b6734e9aa94824790 | C++ | mqssi/JeuDeRole | /TPJeuDeRole/EtreVivant.cpp | UTF-8 | 758 | 3.0625 | 3 | [] | no_license | #include "EtreVivant.h"
using namespace std;
EtreVivant::EtreVivant()
{
this->nom = "";
this->pointdevie = 0;
}
EtreVivant::EtreVivant(std::string nom, int pointdevie)
{
this->nom = nom;
this->pointdevie = pointdevie;
this->positionx = 0;
this->positiony = 0;
}
void EtreVivant::SePositionner(int positionx, int positiony)
{
this->positionx= positionx ;
this->positiony = positiony;
}
void EtreVivant::Attaquer(EtreVivant* Etrevivantcible)
{
cout << "Nom attaquant : " << this->nom << endl << "Nom Cible : " << Etrevivantcible->nom << endl;
Etrevivantcible->Recevoirdegats(this);
}
void EtreVivant::Recevoirdegats(EtreVivant* Etrevivantsource)
{
cout << this->nom << " est attaque par " << Etrevivantsource->nom << endl;
} | true |
5d33bf1600edcb3544dafbe025279c3d7ddba65e | C++ | Jialin/ICPC | /Template/leetcode/linked_list.h | UTF-8 | 3,090 | 2.765625 | 3 | [] | no_license | // !macro_gen
// ALL LEETCODE_LINKED_LIST_ALL
#pragma once
#include "common/macros.h"
#include "debug/debug_basic.h"
using namespace std;
#ifdef LOCAL
struct ListNode {
int val;
ListNode* next;
inline ListNode() : val(0), next(nullptr) {}
inline ListNode(int x) : val(x), next(nullptr) {}
inline ListNode(int x, ListNode* next) : val(x), next(next) {}
inline bool _containsLoop() const {
auto* slow = this;
auto* fast = this;
do {
if (fast && fast->next) {
fast = fast->next->next;
} else {
return false;
}
slow = slow->next;
} while (slow != fast);
return true;
}
inline void
_output(bool first, bool containsLoop, unordered_set<int64_t>& visited, ostream& o) const {
if (!first) {
o << ',';
}
o << val;
auto address = int64_t(this);
if (containsLoop) {
o << "(@" << hex << address << dec << ')';
}
if (visited.count(address)) {
o << "**LOOP**";
return;
}
visited.insert(address);
if (next) {
next->_output(false, containsLoop, visited, o);
}
}
inline friend ostream& operator<<(ostream& o, const ListNode* node) {
o << '[';
if (node) {
unordered_set<int64_t> visited;
node->_output(true, node->_containsLoop(), visited, o);
}
o << ']';
return o;
}
};
#endif
#ifdef LEETCODE_LINKED_LIST_CALC_LENGTH // ^
namespace lc {
inline int calcLength(const ListNode* head) {
int res = 0;
for (auto* node = head; node; node = node->next, ++res) {}
return res;
}
} // namespace lc
#endif
#ifdef LEETCODE_LINKED_LIST_CALC_KTH // ^
namespace lc {
inline ListNode* calcKth(ListNode* head, int idx) {
auto* node = head;
FOR(i, 0, idx) {
node = node->next;
}
return node;
}
} // namespace lc
#endif
#ifdef LEETCODE_LINKED_LIST_REVERSE // ^
namespace lc {
inline ListNode* reverse(ListNode* head) {
if (!head) {
return nullptr;
}
ListNode* prev = nullptr;
for (auto* cur = head; cur;) {
auto* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
} // namespace lc
#endif
#ifdef LEETCODE_LINKED_LIST_TO_VECTOR // ^
namespace lc {
inline vector<int> toVector(ListNode* head) {
vector<int> res;
for (auto* node = head; node; node = node->next) {
res.push_back(node->val);
}
return res;
}
} // namespace lc
#endif
#ifdef LEETCODE_LINKED_LIST_FROM_VECTOR // ^
namespace lc {
inline ListNode* fromVector(vector<int>& vs) {
auto* dummyHead = new ListNode(-1);
auto* tail = dummyHead;
for (int v : vs) {
auto* node = new ListNode(v);
tail->next = node;
tail = node;
}
return dummyHead->next;
}
} // namespace lc
#endif
#ifdef LEETCODE_LINKED_LIST_CONTAINS_LOOP // ^
namespace lc {
inline bool containsLoop(ListNode* head) {
if (!head) {
return false;
}
auto* slow = head;
auto* fast = head;
do {
if (fast->next) {
fast = fast->next->next;
} else {
return true;
}
slow = slow->next;
} while (slow != fast);
return false;
}
} // namespace lc
#endif
| true |
4572217a6323cc44832b5ddb227b479ab926686f | C++ | JakubKivi/PONG | /PONG/PONG.ino | UTF-8 | 513 | 2.578125 | 3 | [
"MIT"
] | permissive | #include <Servo.h> //Biblioteka odpowiedzialna za serwa
Servo serwomechanizm; //Tworzymy obiekt, dzięki któremu możemy odwołać się do serwa
int pozycja = 0; //Aktualna pozycja serwa 0-180
int zmiana = 6; //Co ile ma się zmieniać pozycja serwa?
void setup()
{
Serial.begin(9600);
serwomechanizm.attach(3); //Serwomechanizm podłączony do pinu 9
}
void loop()
{
serwomechanizm.write(map(analogRead(A0), 600, 900, 0, 180)); //Wykonaj ruch
delay(100);
}
| true |
7936b39eb6693f6fc8b35d353f37b622fb91b815 | C++ | deepcoder007/spoj | /MAXWOODS.cpp | UTF-8 | 1,521 | 3.078125 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
// a dp problem in 2D
inline int max(int i,int j)
{
if( i>j ) return i;
else return j;
}
inline int min(int i,int j)
{
if( i<j ) return i;
else return j;
}
inline int scan()
{
register int n=0;
register char c=getchar_unlocked();
while( c<'0' || c>'9')
c=getchar_unlocked();
while( c>='0' && c<='9' )
{
n=n*10+c-'0';
c=getchar_unlocked();
}
return n;
}
int m,n;
int dp[2][210][210]; // 0-> left facing , 1-> right facing
char input[210][210];
int get(int i,int j,int f) // f -> 0 for left and 1 for right
{
// cout<<"for (i,j) : "<<i<<" "<<j<<endl;
if( i<0 || i>=m || j<0 || j>=n ) return 0; // i.e. out of bound
if( input[i][j]=='#' ) return 0;
if( dp[f][i][j]!=-1 ) return dp[f][i][j];
// otherwise perform the dp
if( f==1 ) // the face is at the right
{
int a=get(i,j+1,1);
int b=get(i+1,j,0);
dp[f][i][j]=max(a,b);
}
else
{
int a=get(i,j-1,0);
int b=get(i+1,j,1);
dp[f][i][j]=max(a,b);
}
if( input[i][j]=='T')
dp[f][i][j]++;
return dp[f][i][j];
}
inline void test()
{
// cout<<"INSIDE TEST"<<endl;
m=scan(); n=scan();
register int i,j;
for(i=0;i<=200;i++)
for(j=0;j<=200;j++)
dp[0][i][j]=dp[1][i][j]=-1;
for(i=0;i<m;i++)
cin>>input[i];
// cout<<"here"<<endl;
cout<<get(0,0,1)<<endl;
}
int main()
{
int t=scan();
while( t-- )
test();
return 0;
}
| true |
85d0dea6abe46cb4039490e41209097b3995f734 | C++ | Jonariguez/ACM_Code | /UVA/1153.cpp | GB18030 | 1,561 | 2.78125 | 3 | [] | no_license | /****************
*PID:
*Auth:Jonariguez
*****************
ȰսֹʱȺab
aĽֹʱb֮ǰaļӹʱbô
aȻҪbأbļӹ
ʱ䳬˽ֹʱ䣬ô֮ǰĶɾӹʱ
ǸܵĶûб仯ܵļӹʱ
ˣΪԺܸඩ
ҪܾһЩģȶά
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn=800000+10;
struct pp{
int need,due;
pp(int n=0,int d=0):need(n),due(d){}
bool operator < (const pp &rhs) const { //<ţsortpriority_queue෴
if(due==rhs.due)
return need<rhs.need;
return due<rhs.due;
};
}s[maxn];
int main()
{
int i,j,T,res,n;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%d",&s[i].need,&s[i].due);
}
sort(s,s+n);
priority_queue<int> pq;
int now=0;
res=0;
for(i=0;i<n;i++){
pq.push(s[i].need);
now+=s[i].need;
if(now>s[i].due){
now-=pq.top();
pq.pop();
}
}
printf("%d\n",(int)pq.size());
if(T)
printf("\n");
}
return 0;
}
| true |
3981fa07c88159ae233952391ed74244aae5c013 | C++ | kotunde/SourceFileAnalyzer_featureSearch_and_classification | /GCJ_Dataset/Data/Aleksander/2974486_5644738749267968_Aleksander.cpp | UTF-8 | 1,650 | 2.625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
using namespace std;
double g[2][1005];
int a[2][1005];
int ind[2];
pair < double , int > p[2005];
int n;
int pSize;
int getAnsDeceitfulWar ()
{
for (int s = 0; s < n; s++)
{
bool ok = true;
for (int i = 0, j = s; j < n; i++, j++)
{
if (a[0][j] < a[1][i] )
{
ok = false;
break;
}
}
if (ok)
return n - s;
}
return 0;
}
int getAnsWar ()
{
int res = 0;
for (int i = n - 1, j = n - 1; i >= 0; i--)
{
if (a[0][i] > a[1][j] )
res++;
else
j--;
}
return res;
}
void solve ()
{
pSize = 0;
for (int t = 0; t < 2; t++)
{
for (int i = 0; i < n; i++)
p[pSize++] = make_pair(g[t][i], t);
}
sort(p, p + pSize);
for (int i = 0; i < 2; i++)
ind[i] = 0;
for (int i = 0; i < pSize; i++)
{
int t = p[i].second;
a[t][ind[t]++] = i;
}
int ansDeceitfulWar = getAnsDeceitfulWar();
int ansWar = getAnsWar();
printf("%d %d", ansDeceitfulWar, ansWar);
}
int main ()
{
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
int test_amount, test_num;
scanf("%d\n", &test_amount);
for (test_num = 0; test_num < test_amount; test_num++)
{
if (test_num)
printf("\n");
printf("Case #%d: ", test_num + 1);
// input
scanf("%d", &n);
for (int t = 0; t < 2; t++)
{
for (int i = 0; i < n; i++)
{
scanf("%lf", &g[t][i] );
}
}
// #input
solve();
}
return 0;
} | true |
7936e82d096437685e07d5218b1783279c3f6db6 | C++ | nicolekurtz/Calendar_app | /calendar_item.cpp | UTF-8 | 13,728 | 3.296875 | 3 | [] | no_license | // Nicole Kurtz
#include "calendar_item.h"
using namespace std;
/*
char * name; // name of calendar item
char * time; // time of calendar item
char * description; // description of calendar item
char * zoom; // zoom id if applicable
*/
// default constructor
item::item(): name(NULL), description(NULL)
{
}
// deconstructor
item::~item()
{
if(name)
delete [] name;
if(description)
delete [] description;
name = description = NULL;
}
// copy constructor
item::item(const item * to_copy)
{
if(to_copy->name)
{
name = new char[strlen(to_copy->name) + 1];
strcpy(name, to_copy->name);
}
if(to_copy->description)
{
description = new char[strlen(to_copy->description) + 1];
strcpy(description, to_copy->description);
}
}
// copy constructor
item::item(const item *& to_copy)
{
if(to_copy->name)
{
name = new char[strlen(to_copy->name) + 1];
strcpy(name, to_copy->name);
}
if(to_copy->description)
{
description = new char[strlen(to_copy->description) + 1];
strcpy(description, to_copy->description);
}
}
// add constuctor
item::item(char * name_tocopy, char * description_tocopy)
{
name = new char[strlen(name_tocopy) + 1];
strcpy(name, name_tocopy);
description = new char[strlen(description_tocopy) +1];
strcpy(description, description_tocopy);
}
// virtual display
bool item::display()
{
if(!name || !description) return false;
if(name)
cout << endl << "Name: " << name << endl;
if(description)
cout << "Description: " << description << endl;
return true;
}
// virtual function to add to list
bool item::add_list()
{
return true;
}
/*
// display list of todos
bool item::display_list()
{
return true;
}
*/
// add calendar item
bool item::add_item()
{
char name_tocopy[100];
char description_tocopy[100];
cout << "Name: ";
cin.get(name_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Description: ";
cin.get(description_tocopy, 100, '\n');
cin.ignore(100, '\n');
name = new char[strlen(name_tocopy) + 1];
strcpy(name, name_tocopy);
description = new char[strlen(description_tocopy) + 1];
strcpy(description, description_tocopy);
if(!name || !description)
return false;
return true;
}
/*
bool item::edit_calendar_item()
{
char name_toadd[100];
char description_toadd[100];
cout << "Please type the new item name: ";
cin.get(name_toadd, 100, '\n');
cin.ignore(100, '\n');
cout << "Please type the new description for " << name_toadd << ": ";
cin.get(description_toadd, 100, '\n');
cin.ignore(100, '\n');
// delete current data
delete [] name;
delete [] description;
name = new char[strlen(name_toadd) + 1];
strcpy(name, name_toadd);
description = new char[strlen(description_toadd) + 1];
strcpy(description, description_toadd);
if(!name || !description)
return false;
return true;
}
*/
// find item
bool item::find_item(char * compare, bool & check)
{
if(strcmp(name, compare) == 0)
{
char response;
display();
//display_list();
return true;
}
return false;
}
/*
// find item in list
bool item::find_item_list(char * compare)
{
return true;
}
*/
///////* NODE CLASS *//////
// default constructor
node::node(): next(NULL)
{
}
// copy constructor
node::node(const node *& tocopy)
{
const todo * ptr = dynamic_cast<const todo*>(tocopy->a_item);
if(ptr)
{
a_item = new todo(ptr);
next = NULL;
}
const lecture * ptr1 = dynamic_cast<const lecture*>(tocopy->a_item);
if(ptr1)
{
a_item = new lecture(ptr1);
next = NULL;
}
const work * ptr2 = dynamic_cast<const work*>(tocopy->a_item);
if(ptr2)
{
a_item = new work(ptr2);
next = NULL;
}
}
// copy constructor
node::node(const node * tocopy)
{
//item * temp = tocopy->a_item;
//temp->display();
const todo * ptr = dynamic_cast<const todo*>(tocopy->a_item);
if(ptr)
{
a_item = new todo(ptr);
next = NULL;
}
const lecture * ptr1 = dynamic_cast<const lecture*>(tocopy->a_item);
if(ptr1)
{
a_item = new lecture(ptr1);
next = NULL;
}
const work * ptr2 = dynamic_cast<const work*>(tocopy->a_item);
if(ptr2)
{
a_item = new work(ptr2);
next = NULL;
}
}
// deconstructor
node::~node()
{
next = NULL;
if(a_item)
delete a_item;
}
// add item to node
node::node(const item * tocopy)
{
const todo * ptr = dynamic_cast<const todo*>(tocopy);
if(ptr)
{
a_item = new todo(ptr);
next = NULL;
}
const lecture * ptr1 = dynamic_cast<const lecture*>(tocopy);
if(ptr1)
{
a_item = new lecture(ptr1);
next = NULL;
}
const work * ptr2 = dynamic_cast<const work*>(tocopy);
if(ptr2)
{
a_item = new work(ptr2);
next = NULL;
}
}
// add item to node
node::node(const item *& tocopy)
{
const todo * ptr = dynamic_cast<const todo*>(tocopy);
if(ptr)
{
a_item = new todo(ptr);
next = NULL;
}
const lecture * ptr1 = dynamic_cast<const lecture*>(tocopy);
if(ptr1)
{
a_item = new lecture(ptr1);
next = NULL;
}
const work * ptr2 = dynamic_cast<const work*>(tocopy);
if(ptr2)
{
a_item = new work(ptr2);
next = NULL;
}
}
// set next node
void node::set_next(node *& connection)
{
next = connection;
}
bool node::display_list_item()
{
if(!a_item)
return false;
if(a_item->display())
return true;
return false;
}
// display contents of node
bool node::display()
{
const todo * ptr = dynamic_cast<const todo*>(a_item);
if(ptr)
{
todo * temp = new todo(ptr);
temp->display_list();
delete temp;
return true;
}
if(a_item->display())
return true;
return false;
}
node *& node::get_next()
{
return next;
}
node *& node::get_down()
{
return down;
}
void node::set_down(node *& connection)
{
next = connection;
}
bool node::find_item(char * name, bool & check)
{
if(a_item->find_item(name, check))
return true;
return false;
}
bool node::find_item_list(char * compare)
{
const todo * ptr = dynamic_cast<const todo*>(a_item);
if(ptr)
{
todo * temp = new todo(ptr);
if(temp->find_item_list(compare))
{
delete temp;
return true;
}
delete temp;
return false;
}
/*
if(a_item->find_item_list(compare))
return true;
*/
return false;
}
/////* LIST CLASS *//////
// default constructor
list::list(): head(NULL)
{
}
// copy constructor
list::list(const list * tocopy)
{
if(tocopy->head)
{
copy_list(head, tocopy->head);
}
}
// copy list recursively
void list::copy_list(node *& head, node * tocopy)
{
if(!tocopy) return;
head = new node(tocopy);
return copy_list(head->get_next(), tocopy->get_next());
}
// destructor
list::~list()
{
if(head)
delete_list(head);
head = NULL;
}
// remove all items in the list
void list::delete_list(node *& head)
{
if(!head) return;
node * hold = head->get_next();
delete head;
head = hold;
return delete_list(head);
}
// wrapper function to find item in list
bool list::find_item(char * name)
{
bool check = false;
if(!head)
return false;
if(find_item(head, name, check))
{
if(check)
return true;
else
return false;
}
return false;
}
// recursive function to find item in list
bool list::find_item(node *& head, char * name, bool & check)
{
if(!head) return true;
if(head->find_item_list(name))
{
node * hold = head->get_next();
delete head;
head = hold;
check = true;
return find_item(head, name, check);
}
return find_item(head->get_next(), name, check);
}
// add item to list
bool list::add_todo()
{
char response;
do{
item * ptr = new todo();
ptr->add_item();
//ptr->display();
if(!head)
{
head = new node(ptr);
//head->display();
}
else
{
node * temp = new node(ptr);
temp->set_next(head);
head = temp;
}
cout << endl << "Would you like to add another to do? (y or n): ";
cin >> response;
cin.ignore(100, '\n');
delete ptr;
}while(response != 'n');
return true;
}
// wrapper function to display an item
bool list::display()
{
if(!head)
return false;
if(display(head))
return true;
return false;
}
// recursive call to display an item
bool list::display(node * head)
{
if(!head)
{
return true;
}
head->display_list_item();
//head->display();
return display(head->get_next());
}
/////* LECTURE VIDEOS */////
// constructor
lecture::lecture(): zoom(NULL), time(NULL)
{
}
// copy constructor
lecture::lecture(const lecture * to_copy): item(to_copy)
{
zoom = new char[strlen(to_copy->zoom) + 1];
strcpy(zoom, to_copy->zoom);
time = new char[strlen(to_copy->time) + 1];
strcpy(time, to_copy->time);
}
// deconstructor
lecture::~lecture()
{
if(zoom)
delete [] zoom;
if(time)
delete [] time;
zoom = time = NULL;
}
// add calendar item
bool lecture::add_item()
{
char name_tocopy[100];
char time_tocopy[100];
char description_tocopy[100];
char zoom_tocopy[100];
cout << "Name: ";
cin.get(name_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Time: ";
cin.get(time_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Description: ";
cin.get(description_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Zoom ID: ";
cin.get(zoom_tocopy, 100, '\n');
cin.ignore(100, '\n');
name = new char[strlen(name_tocopy) + 1];
strcpy(name, name_tocopy);
time = new char[strlen(time_tocopy) + 1];
strcpy(time, time_tocopy);
description = new char[strlen(description_tocopy) +1];
strcpy(description, description_tocopy);
zoom = new char[strlen(zoom_tocopy) + 1];
strcpy(zoom, zoom_tocopy);
return true;
}
// display function
bool lecture::display()
{
if(!name) return false;
cout << endl << "---Lecture Video Info---";
if(name)
cout << endl << "Name: " << name << endl;
if(time)
cout << "Time: " << time << endl;
if(description)
cout << "Description: " << description << endl;
if(zoom)
cout << "Zoom ID: " << zoom << endl;
return true;
}
// find item and display
bool lecture::find_item(char * compare)
{
if(strcmp(name, compare) == 0)
{
char response;
display();
return true;
}
return false;
}
///////* TO DO LIST ITEM *////////
// This calendar item has a list of todos
// which represent a to do list.
// this calendar item is dervied from the calendar item base class
// default constructor
todo::todo()
{
todos = new list;
}
// copy constructor
//todo::todo(const todo *& tocopy): item(tocopy)
todo::todo(const todo * tocopy): item(tocopy)
{
if(tocopy->todos)
{
todos = new list(tocopy->todos);
}
}
// deconstructor
todo::~todo()
{
if(todos)
delete todos;
}
// creates new todo item
bool todo::add_item()
{
char name_tocopy[100];
char description_tocopy[100];
cout << "Name: ";
cin.get(name_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Description: ";
cin.get(description_tocopy, 100, '\n');
cin.ignore(100, '\n');
name = new char[strlen(name_tocopy) + 1];
strcpy(name, name_tocopy);
description = new char[strlen(description_tocopy) +1];
strcpy(description, description_tocopy);
if(!name || !description)
return false;
return true;
}
// add item to list of items
bool todo::add_list()
{
if(todos->add_todo())
return true;
return false;
}
// display todo items
bool todo::display_list()
{
if(!todos)
return false;
if(todos->display())
return true;
return false;
}
// find item and display
bool todo::find_item(char * compare, bool & check)
{
if(todos->find_item(compare))
{
check = true;
return true;
}
return false;
}
// find item in list and display
bool todo::find_item_list(char * compare)
{
if(strcmp(name, compare) == 0)
{
display();
return true;
}
return false;
}
// display todo item
bool todo::display()
{
if(!name || !description) return false;
cout << endl << "----TODO ITEM----" << endl;
cout << "Name: " << name << endl;
cout << "Description: " << description << endl;
return true;
}
////////* WORK ITEM */////////
// This calendar item represents a work schedule
// it is dervied from a calendar item class
// default constructor
work::work(): start(NULL), end(NULL)
{
}
// copy constructor
work::work(const work * tocopy): item(tocopy)
{
start = new char[strlen(tocopy->start) + 1];
strcpy(start, tocopy->start);
end = new char[strlen(tocopy->end) + 1];
strcpy(end, tocopy->end);
}
// copy constructor
work::work(const work & tocopy): item(tocopy)
{
start = new char[strlen(tocopy.start) + 1];
strcpy(start, tocopy.start);
end = new char[strlen(tocopy.end) + 1];
strcpy(end, tocopy.end);
}
// deconstructor
work::~work()
{
if(start)
delete [] start;
if(end)
delete [] end;
}
// add calendar item
bool work::add_item()
{
char name_tocopy[100];
char description_tocopy[100];
char start_time[100];
char end_time[100];
cout << "Name: ";
cin.get(name_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Description: ";
cin.get(description_tocopy, 100, '\n');
cin.ignore(100, '\n');
cout << "Start Time: ";
cin.get(start_time, 100, '\n');
cin.ignore(100, '\n');
cout << "End Time: ";
cin.get(end_time, 100, '\n');
cin.ignore(100, '\n');
name = new char[strlen(name_tocopy) + 1];
strcpy(name, name_tocopy);
description = new char[strlen(description_tocopy) +1];
strcpy(description, description_tocopy);
start = new char[strlen(start_time) + 1];
strcpy(start, start_time);
end = new char[strlen(end_time) + 1];
strcpy(end, end_time);
if(!name || !description || !start || !end)
return false;
return true;
}
// display work item
bool work::display()
{
if(!name || !description || !start || !end)
return false;
cout << endl << "----Work Item----" << endl;
cout << "Name: " << name << endl;
cout << "Description: " << description << endl;
cout << "Start Time: " << start << endl;
cout << "End Time: " << end << endl;
return true;
}
// find item and display
bool work::find_item(char * compare, bool & check)
{
if(strcmp(name, compare) == 0)
{
display();
return true;
}
return false;
}
| true |
4eb643631b6f1c48dc07c5e70f21611b5e0b29f7 | C++ | bigYellowDuck/urllib | /Response.cpp | UTF-8 | 762 | 2.9375 | 3 | [] | no_license | #include "Response.h"
namespace urllib
{
using std::string;
Response::Response(const string& resp)
: resp_(resp)
{
parseRespone();
}
Response::Response(string&& resp)
: resp_(std::move(resp))
{
parseRespone();
}
const string& Response::response() const noexcept
{
return resp_;
}
const string& Response::info() const noexcept
{
return headers_;
}
const string& Response::read() const noexcept
{
return body_;
}
void Response::parseRespone()
{
auto pos1 = resp_.find("\r\n"); // ignore HTTP respone line
auto pos2 = resp_.find("\r\n\r\n");
headers_ = std::move(string(resp_.begin()+pos1+2, resp_.begin()+pos2+4));
body_ = std::move(string(resp_.begin()+pos2+4,resp_.end()));
}
} // end of namespace urllib
| true |
5bdeb097a72bd243ed5c3b6ec6080497d2433c06 | C++ | dlhe/LeetCode | /test/TestSubStringWithConcatenationOfAllWords.cpp | UTF-8 | 395 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include "../src/SubStringWithConcatenationOfAllWords.cpp"
using namespace std;
int main() {
string str = "a";
vector<string> l {"a"};
Solution s;
vector<int> a = s.findSubstring(str, l);
cout << "======" << endl;
for (int i = 0; i < a.size(); i++)
cout << a[i] << ",";
cout << endl;
return 0;
}
| true |
e73af55da59c82dd74df63117cbd9b5360c57143 | C++ | SamiMurtaza/DragonBallZ-OOP | /Final/src/Saibaman.cpp | UTF-8 | 5,125 | 2.65625 | 3 | [] | no_license | #include "Saibaman.h"
#include <SDL_mixer.h>
Saibaman::Saibaman(const char* textureSheet, int x, int y, int R, int G, int B) :Enemy(textureSheet, x, y, R, G, B)
{
Saibaman::type = 0;
dead = false;
}
void Saibaman::update(int flag, double i_angle = 0.0)
{
if (flag == 1 && xpos < 750)
{
xpos += 2; //moves left
flip = SDL_FLIP_NONE;
srcRect.x = 60;
srcRect.y = 65;
}
if (flag == 2 && xpos > 0)
{
xpos -= 2; // moves right
flip = SDL_FLIP_HORIZONTAL;
srcRect.x = 60;
srcRect.y = 65;
}
if (flag == 3 && ypos > 0)
{
/*xpos += 2;*/ ypos -= 2; //moves up
srcRect.x = 0;
srcRect.y = 65;
}
if (flag == 4 && ypos < 450)
{
/*xpos -= 2;*/ ypos += 2; //moves down
}
if (flag == 5)
{
if (ypos <= 450)
{
ypos += 1;
}
srcRect.x = 0;
srcRect.y = 0;
}
if (flag == 6)
{
srcRect.x = 55;
srcRect.y = 145;
}
srcRect.h = 55;
srcRect.w = 55;
angle = i_angle;
destRect.x = xpos;
destRect.y = ypos;
destRect.w = srcRect.w ;
destRect.h = srcRect.h ;
//frame++;
}
void Saibaman::track(GameObject& player, bool flag)
{
int x = player.getX();
int y = player.getY();
if (flag)
{
if (this->xpos - x > 100)
{
if (this->ypos > y)
{
ypos -= 2;
update(2);
}
if (this->ypos < y)
{
ypos += 2;
update(2);
}
this->update(2);
}
if (this->xpos - x < -100)
{
if (this->ypos > y)
{
ypos -= 2;
update(1);
}
if (this->ypos < y)
{
ypos += 2;
update(1);
}
this->update(1);
}
if (this->xpos - x <= 100 || this->xpos - x >= -100)
{
if (this->ypos > y)
{
ypos -= 2;
update(5);
}
if (this->ypos < y)
{
ypos += 2;
update(5);
}
}
if (this->xpos - x == 100 || this->xpos - x == -100)
{
if (this->ypos == y)
{
kiBlast(attackFrame);
}
}
}
else
{
this->death(deathFrame);
}
}
void Saibaman::kiBlast(int frame)
{
switch (frame % 18)
{
case 0:
srcRect.x = 55;
srcRect.y = 145;
srcRect.h = 55;
destRect.w = srcRect.w = 55;
//destRect.x = xpos;
if (flip == SDL_FLIP_HORIZONTAL)
{
destRect.x = xpos + 30 -30;
}
else
{
destRect.x = xpos;
}
destRect.y = ypos;
break;
case 1:
break;
case 2:
break;
case 3:
srcRect.x = 110;
srcRect.y = 145;
srcRect.h = 55;
destRect.w = srcRect.w = 55;
//destRect.x = xpos;
if (flip == SDL_FLIP_HORIZONTAL)
{
destRect.x = xpos + 30 - 30;
}
else
{
destRect.x = xpos;
}
destRect.y = ypos;
break;
case 4:
srcRect.x = 110;
srcRect.y = 145;
destRect.w = srcRect.w = 120;
if (flip == SDL_FLIP_HORIZONTAL)
{
destRect.x = xpos - 40 - 25;
}
else
{
destRect.x = xpos;
}
srcRect.h = 55;
//destRect.x = xpos;
destRect.y = ypos;
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
if (flip==SDL_FLIP_HORIZONTAL)
{
destRect.x = xpos + 30 - 30;
}
else
{
destRect.x = xpos;
}
//destRect.x = xpos;
destRect.y = ypos;
srcRect.h = 55;
destRect.w = srcRect.w = 55;
//attack = false;
break;
}
attackFrame++;
if (attackFrame % 18 == 0)
{
Mix_Chunk* gDamage = Mix_LoadWAV("audio/GokDamage.wav");
Mix_PlayChannel(-1, gDamage, 0);
Mix_PlayChannel(-1, gEAttack, 0);
cout << Enemy::attacks++ << endl;
}
}
void Saibaman::death(int frame)
{
switch (frame % 10)
{
case 0:
srcRect.x = 195;
srcRect.y = 0;
srcRect.h = destRect.h = 45;
destRect.w = srcRect.w = 50;
destRect.x = xpos;
destRect.y = ypos;
break;
case 1:
break;
case 2:
Mix_PlayChannel(-1, gEDamage, 0);
break;
case 3:
srcRect.x = 285;
srcRect.y = 0;
srcRect.h = destRect.h = 45;
destRect.w = srcRect.w = 50;
destRect.x = xpos;
destRect.y = ypos;
break;
case 4:
break;
case 5:
break;
}
deathFrame++;
if (deathFrame == 10)
{
convert = true;
}
}
| true |
85f66e8a895806c990cc00baacbe5e06bef70440 | C++ | OracleMahad/PS | /NQueen.cpp | UTF-8 | 700 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
using namespace std;
int col[100000];
int n;
bool promising(int i){
bool switching= true;
int k=1;
while(k<i&&switching){
if(col[i]==col[k]||abs(col[i]-col[k])==i-k)
switching = false;
k++;
}
return switching;
}
void queens(int i){
if(promising(i)){
if (i==n){
for(int k=1;k<=n;k++){
cout << col[k] <<endl;
}
}
else
{
for(int j=1;j<=n;j++)
{
col[i+1]=j;
queens(i+1);
}
}
}
}
int main() {
cin >> n;
queens(0);
} | true |
8ed3c8ae9331af7e14259011dbfba233d4ce0372 | C++ | BearingMe/exercicios-CeV | /exs/mundo_1/c++/028.cpp | UTF-8 | 570 | 3.484375 | 3 | [
"MIT"
] | permissive | /*
028 - Jogo da Adivinhação v1.0
Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário
tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu
*/
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main() {
int chute, numero;
cin >> chute;
srand(time(NULL));
numero = rand() % 4 + 1;
if (chute == numero) {
cout << "Você venceu!\n";
} else {
cout << "Você perdeu\n";
}
return 0;
}
| true |
46904767171c902b16714460eb41640950ab50bf | C++ | shreesh30/Data-Structures-and-Algorithms | /linearSearch.cpp | UTF-8 | 411 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool linearSearch(int arr[], int n, int key)
{
bool flag = false;
for (int i = 0; i < n; i++)
{
if (arr[i] == key)
{
flag = true;
break;
}
}
return flag;
}
int main()
{
int arr[] = {5, 2, 1, 10, 100};
int n = sizeof(arr) / sizeof(arr[0]);
cout << linearSearch(arr, n, -1);
return 0;
} | true |
ef2e13e6ccc30aa29f29e58a4848ac61528160d4 | C++ | vasiliy249/PriorityQueue | /BinomialHeap.cpp | UTF-8 | 8,272 | 3.15625 | 3 | [] | no_license | #include "BinomialHeap.h"
#include <limits>
#include <sstream>
#include <cmath>
////////////////////////////////////////////////////////////////////////////////////////////////////
BinomTreeNode::BinomTreeNode(int key)
: key_(key), left_child_(NULL), right_sibling_(NULL) {}
void BinomTreeNode::Merge(BinomTreeNodePtr root) {
root->right_sibling_ = this->left_child_;
left_child_ = root;
}
int BinomTreeNode::Degree() const {
int ret = 0;
BinomTreeNodePtr child = left_child_;
while (child) {
child = child->right_sibling_;
ret++;
}
return ret;
}
BinomialHeapPtr BinomTreeNode::RemoveRoot() {
BinomialHeapPtr ret(new BinomialHeap);
BinomTreeNodePtr child = left_child_;
while (child) {
//iterate via children and push them to new binomial heap in reverse order
ret->trees_.push_front(child);
BinomTreeNodePtr next_sibling = child->right_sibling_;
// remove pointer to sibling, because this node became root
ret->trees_.front()->right_sibling_ = NULL;
child = next_sibling;
}
return ret;
}
int BinomTreeNode::Key() const {
return key_;
}
std::string BinomTreeNode::ToString() const {
std::stringstream ss;
if (left_child_) {
ss << left_child_->key_ << " " << left_child_->ToString();
}
BinomTreeNodePtr sibling = right_sibling_;
while(sibling) {
ss << sibling->key_ << " ";
if (sibling->left_child_) {
ss << sibling->left_child_->key_ << " " << sibling->left_child_->ToString();
}
sibling = sibling->right_sibling_;
}
return ss.str();
}
BinomTreeNodePtr BinomTreeNode::Find(int key) {
BinomTreeNodePtr ret;
if (left_child_) {
if (left_child_->Key() == key) {
return left_child_;
}
ret = left_child_->Find(key);
if (ret) {
return ret;
}
}
BinomTreeNodePtr sibling = right_sibling_;
while (sibling) {
if (sibling->Key() == key) {
return sibling;
}
if (sibling->left_child_) {
if (sibling->left_child_->Key() == key) {
return sibling->left_child_;
}
ret = sibling->left_child_->Find(key);
if (ret) {
return ret;
}
}
sibling = sibling->right_sibling_;
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
BinomialHeap::BinomialHeap() {}
void BinomialHeap::Insert(int key) {
BinomTreeNodePtr tmp(new BinomTreeNode(key));
InsertTree(tmp);
}
bool BinomialHeap::ExtractMin(int& key) {
BinomTreeNodePtr min_node = GetMin();
if (!min_node) {
return false;
}
key = min_node->Key();
trees_.remove(min_node);
Union(min_node->RemoveRoot());
Heapify();
return true;
}
bool BinomialHeap::Peek(int& key) const {
BinomTreeNodePtr min_node = GetMin();
if (min_node) {
key = min_node->Key();
return true;
} else {
return false;
}
}
bool BinomialHeap::Delete(int key) {
if (!DecreaseKey(key, std::numeric_limits<int>::min())) {
return false;
}
int min;
return ExtractMin(min);
}
bool BinomialHeap::DecreaseKey(int key, int new_key) {
BinomTreeNodePtr node = Find(key);
if (!node) {
return false;
}
node->key_ = new_key;
BinomTreeNodePtr parent(node->parent_.lock());
// sifting up while node has parent and parent's key less than new key
while (parent && parent->key_ > node->key_) {
std::swap(parent->key_, node->key_);
node = parent;
parent = parent->parent_.lock();
}
return true;
}
bool BinomialHeap::Merge(IPriorityQueuePtr other) {
BinomialHeapPtr casted_other(std::dynamic_pointer_cast<BinomialHeap>(other));
if (!casted_other) {
return false;
}
Union(casted_other);
Heapify();
return true;
}
int BinomialHeap::Size() const {
Trees::const_iterator it = trees_.begin();
int ret = 0;
for (; it != trees_.end(); ++it) {
ret += static_cast<int>(pow(2, (*it)->Degree()));
}
return ret;
}
std::string BinomialHeap::ToString() const {
std::stringstream ret;
ret << "--------------------------------\n";
ret << "Heap size: " << Size() << "\n";
ret << "Tree count: " << trees_.size() << "\n";
ret << "Trees:\n\n";
Trees::const_iterator it = trees_.begin();
for (; it != trees_.end(); ++it) {
ret << "Degree: " << (*it)->Degree() << ", elements:\n";
ret << (*it)->Key() << " " << (*it)->ToString();
ret << "\n\n";
}
return ret.str();
}
// ordered union list with other trees
void BinomialHeap::Union(BinomialHeapPtr other) {
if (trees_.empty()) {
// this heap is empty, just take the other heap trees
trees_ = other->trees_;
return;
}
Trees::const_iterator my_it = trees_.begin();
Trees::const_iterator other_it = other->trees_.begin();
for (; my_it != trees_.end(); ++my_it) {
while (other_it != other->trees_.end()) {
if ((*other_it)->Degree() <= (*my_it)->Degree()) {
// if degree of other's tree is less than this, insert other's tree before this tree
// and erase it from other trees
trees_.insert(my_it, (*other_it));
other->trees_.erase(other_it++);
} else {
break;
}
}
}
if (!other->trees_.empty()) {
// if trees in other heap is not empty, just insert them to the end
trees_.insert(trees_.end(), other->trees_.begin(), other->trees_.end());
}
}
// heapify a heap to exclude trees with the same degrees
void BinomialHeap::Heapify() {
if (trees_.size() <= 1) {
// nothing to heapify
return;
}
Trees::const_iterator prev, curr, next;
prev = curr = next = trees_.begin();
curr = (++next)++;
while (curr != trees_.end()) {
if ((*prev)->Degree() < (*curr)->Degree()) {
// all is OK, just move cursors
prev++;
curr++;
if (next != trees_.end()) {
next++;
}
} else if ((*prev)->Degree() == (*curr)->Degree()) {
if (next != trees_.end() && (*prev)->Degree() == (*next)->Degree()) {
// three trees have the same degree, merge second with third, erase third and move cursors
Trees::const_iterator merge_to, merge_from;
if ((*curr)->Key() <= (*next)->Key()) {
merge_to = curr;
merge_from = next;
} else {
merge_to = next;
merge_from = curr;
}
(*merge_to)->Merge(*merge_from);
(*merge_to)->left_child_->parent_ = (*merge_to);
trees_.erase(merge_from);
prev = merge_to;
curr = ++merge_to;
if (merge_to != trees_.end()) {
next = ++merge_to;
}
} else {
// only two trees have the same degree, merge first with second, erase second and move cursors
Trees::const_iterator merge_to, merge_from;
if ((*prev)->Key() <= (*curr)->Key()) {
merge_to = prev;
merge_from = curr;
} else {
merge_to = curr;
merge_from = prev;
}
(*merge_to)->Merge(*merge_from);
(*merge_to)->left_child_->parent_ = (*merge_to);
trees_.erase(merge_from);
prev = merge_to;
if (merge_to != trees_.end()) {
curr = ++merge_to;
if (merge_to != trees_.end()) {
next = ++merge_to;
}
}
}
}
}
}
void BinomialHeap::InsertTree(BinomTreeNodePtr root) {
BinomialHeapPtr temp_heap(new BinomialHeap());
temp_heap->trees_.push_back(root);
Union(temp_heap);
Heapify();
}
BinomTreeNodePtr BinomialHeap::GetMin() const {
if (trees_.empty()) {
return BinomTreeNodePtr();
}
Trees::const_iterator it = trees_.begin();
BinomTreeNodePtr min_node = *it;
for (; it != trees_.end(); ++it) {
int it_key = (*it)->Key();
if (it_key < min_node->Key()) {
min_node = *it;
}
}
return min_node;
}
BinomTreeNodePtr BinomialHeap::Find(int key) {
BinomTreeNodePtr ret;
Trees::const_iterator it = trees_.begin();
for (; it != trees_.end(); ++it) {
if ((*it)->Key() == key) {
return (*it);
} else if((*it)->Key() < key) {
ret = (*it)->Find(key);
} else {
continue;
}
if (ret) {
return ret;
}
}
return ret;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
IPriorityQueuePtr CreatePriorityQueue() {
IPriorityQueuePtr ptr(new BinomialHeap);
return ptr;
}
| true |
3a2a74387d1e907ad1e9137518a057986ea521bf | C++ | arasu420/greatest_num | /greatest_num.cpp | UTF-8 | 366 | 3.515625 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a,b,c;
cout << "Enter the 1st num: ";
cin >> a;
cout << "Enter the 2st num: ";
cin >> b;
cout << "Enter the 3st num: ";
cin >> c;
if(a>b && a>c)
{
cout << a << " is greater";
}
else if(b>c)
{
cout << b << " is greater ";
}
else
{
cout << c << " is greater ";
}
return 0;
} | true |
b9d7e0a054019ca03a1d41b041748c1cef87fa99 | C++ | whodewho/codefun | /Shuffle_Recover.cpp | UTF-8 | 935 | 2.640625 | 3 | [] | no_license | #include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
#include "map"
#include <algorithm>
#include <stdlib.h>
#include <time.h>
#include <stack>
#include <sstream>
#include <iomanip>
#include <random>
using namespace std;
void shuffle(vector<int> &num, int &k)
{
int i=0, n=num.size();
while(i<n)
{
if(i==k||num[i]==num[num[i]]||num[i]==i)
{
i++;
continue;
}
num[k]=num[num[i]];
num[num[i]]=num[i];
int j=i;
i=min(i,k);
k=j;
}
}
void testShuffle()
{
int n=20, k=6;
vector<int> num;
for(int i=0;i<n;i++)
num.push_back(i);
random_shuffle(num.begin(), num.end());
for(int i=0;i<n;i++)
{
if(i==k)cout<<"->";
cout<<num[i]<<" ";
}
cout<<endl;
shuffle(num, k);
for(int i=0;i<n;i++)
{
if(i==k)cout<<"->";
cout<<num[i]<<" ";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
testShuffle();
return 0;
}
| true |
ea138263d266f546cac922da5d6ca34240f005ce | C++ | RickyOrmeno/Final-Project | /AnimalDatabaseFinalProject/AnimalDatabaseFinalProject/Reptiles.h | UTF-8 | 287 | 2.515625 | 3 | [] | no_license | #pragma once
#include "Animal.h"
class Reptiles : public Animal
{
private:
std::vector <std::shared_ptr<Reptiles>> _Reptiles;
public:
Reptiles(std::string name, std::string description);
void addReptile(std::shared_ptr<Reptiles> newReptile);
void showReptiles();
~Reptiles();
};
| true |
33454e8bf71cae2df7ee49f5958976051e25b804 | C++ | ErwanDL/aoc2020 | /day16/main.cpp | UTF-8 | 5,227 | 3.015625 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
template <class T> void printVector(const std::vector<T>& vec) {
std::cout << "{ ";
for (std::size_t i = 0; i < vec.size() - 1; ++i) {
std::cout << vec.at(i) << ", ";
}
std::cout << vec.back() << " }" << std::endl;
}
std::vector<std::string> split(const std::string& str, const std::string& separator) {
std::vector<std::string> res{};
std::size_t cursor = 0;
std::size_t separatorPos;
while ((separatorPos = str.find(separator, cursor)) != std::string::npos) {
res.push_back(str.substr(cursor, separatorPos - cursor));
cursor = separatorPos + separator.size();
}
res.push_back(str.substr(cursor));
return res;
}
bool allSizeOne(const std::vector<std::unordered_set<std::string>>& possibleFieldsByPos) {
for (const auto& fields : possibleFieldsByPos) {
if (fields.size() > 1) {
return false;
}
}
return true;
}
class Ranges {
int low1, high1, low2, high2;
Ranges(int low1, int high1, int low2, int high2)
: low1(low1), high1(high1), low2(low2), high2(high2) {}
public:
bool contains(int value) const {
return (low1 <= value && value <= high1) || (low2 <= value && value <= high2);
}
static Ranges fromString(const std::string& rangesStr) {
auto rangesVec = split(rangesStr, " or ");
auto range1 = split(rangesVec.at(0), "-");
auto range2 = split(rangesVec.at(1), "-");
return Ranges(std::stoi(range1.at(0)), std::stoi(range1.at(1)), std::stoi(range2.at(0)),
std::stoi(range2.at(1)));
}
};
int main(int argc, char* argv[]) {
const std::string inputFileName = argv[1];
std::ifstream inputFile{inputFileName};
std::string buffer;
std::unordered_map<std::string, Ranges> rules{};
std::vector<int> yourTicket{};
std::vector<std::vector<int>> nearbyTickets{};
while (std::getline(inputFile, buffer) && buffer != "") {
auto splitRule = split(buffer, ": ");
rules.insert({splitRule.at(0), Ranges::fromString(splitRule.at(1))});
}
std::getline(inputFile, buffer); // "your ticket:"
std::getline(inputFile, buffer);
for (const std::string& val : split(buffer, ",")) {
yourTicket.push_back(std::stoi(val));
}
std::getline(inputFile, buffer);
std::getline(inputFile, buffer); // "nearby tickets:"
while (std::getline(inputFile, buffer)) {
std::vector<int> ticket{};
for (const std::string& val : split(buffer, ",")) {
ticket.push_back(std::stoi(val));
}
nearbyTickets.push_back(ticket);
}
inputFile.close();
int errorRate = 0;
std::vector<std::vector<int>> validNearbyTickets{};
for (const auto& ticket : nearbyTickets) {
bool isValid = true;
for (int val : ticket) {
bool matchesRule = false;
for (const auto& [ruleName, ranges] : rules) {
if (ranges.contains(val)) {
matchesRule = true;
break;
}
}
if (!matchesRule) {
isValid = false;
errorRate += val;
}
}
if (isValid) {
validNearbyTickets.push_back(ticket);
}
}
std::cout << "Ticket scanning error rate: " << errorRate << std::endl;
int nFields = yourTicket.size();
std::vector<std::unordered_set<std::string>> possibleFieldsByPos{};
// Building initial values for the possible fields using the narrator's ticket
for (int i = 0; i < nFields; ++i) {
possibleFieldsByPos.push_back({});
for (const auto& [ruleName, ranges] : rules) {
if (ranges.contains(yourTicket.at(i))) {
possibleFieldsByPos.at(i).insert(ruleName);
}
}
}
for (const auto& ticket : validNearbyTickets) {
for (int i = 0; i < nFields; ++i) {
for (const auto& [ruleName, ranges] : rules) {
if (!ranges.contains(ticket.at(i))) {
possibleFieldsByPos.at(i).erase(ruleName);
}
}
}
}
while (!allSizeOne(possibleFieldsByPos)) {
for (const auto& possibleFields : possibleFieldsByPos) {
if (possibleFields.size() == 1) {
std::string onlyViableField = *possibleFields.begin();
for (auto& otherPossibleFields : possibleFieldsByPos) {
if (&otherPossibleFields != &possibleFields) {
otherPossibleFields.erase(onlyViableField);
}
}
}
}
}
long product = 1;
for (int i = 0; i < nFields; ++i) {
const std::string fieldName = *possibleFieldsByPos.at(i).begin();
std::cout << "Field name at position " << i << ": " << fieldName << std::endl;
if (fieldName.substr(0, 9) == "departure") {
product *= yourTicket.at(i);
}
}
std::cout << "Product of 'departure' fields: " << product << std::endl;
return 0;
} | true |
0312c0562f2fb41f78904558173bf5324b2d9447 | C++ | VladimirRadev/FMI | /Introduction/IntroductionHomework/Birthday/Birthday.cpp | UTF-8 | 1,389 | 3.5 | 4 | [
"MIT"
] | permissive | /**
*
* Solution to homework assignment 1
* Introduction to programming course
* Faculty of Mathematics and Informatics of Sofia University
* Winter semester 2020/2021
*
* @author Atanas Vasilev
* @idnumber 62577
* @task 1
* @compiler VC
*
*/
#include <iostream>
using namespace std;
int main()
{
const double MONEY_GIFT = 30;
const double BIRTHDAY_EXPENSES = 5;
const double ADDED_MONEY_TO_GIFT = 30;
int age;
double laptopPrice;
double presentPrice;
do
{
cin >> age;
} while (!cin || age <= 0);
do
{
cin >> laptopPrice;
} while (!cin || laptopPrice <= 0);
do
{
cin >> presentPrice;
} while (!cin || presentPrice <= 0);
int evenBirthdays = age / 2;
// Sum first elements n of some arithmetic progression formula (2 * a + (n - 1) * d) * (n / 2)
double evenBirtdaysReceivedMoney = ((2 * MONEY_GIFT + ((double)evenBirthdays - 1) * ADDED_MONEY_TO_GIFT) / 2) * evenBirthdays;
double evenBirthdaysExpenses = evenBirthdays * BIRTHDAY_EXPENSES;
int oddBirthdays = age - evenBirthdays;
double oddBirthdaysReceivedMoney = oddBirthdays * presentPrice;
double totalReceivedMoney = evenBirtdaysReceivedMoney - evenBirthdaysExpenses + oddBirthdaysReceivedMoney;
if (totalReceivedMoney >= laptopPrice)
{
cout << "yes" << endl;
cout << totalReceivedMoney - laptopPrice;
}
else
{
cout << "no" << endl;
cout << laptopPrice - totalReceivedMoney;
}
return 0;
}
| true |
0aa47426839a113fb7cde422f569dbb9fac5240e | C++ | koganie/uecda_client | /src/makeYaku.cpp | SHIFT_JIS | 31,060 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include "Yaku.h"
#include "makeYaku.h"
#include "debug.h"
using namespace std;
//悤̊Q
//joker1[݂̂ɑΉĂ邽߁Â̂g[
void pushYaku(vector<Yaku> *allYaku, int64 cd, int suits, int num, int rank, int rank2, int jps, int jpr){
//J[hrbgAX[gAÃNAẼNiKiAjokerPR̂ƂȊO͓jAgjoker̃X[gAgjoker̃NigȂƂ-1j
Yaku yaku(cd, suits, num, rank, rank2, jps, jpr);
allYaku->push_back(yaku);
}
void makeAllYaku(vector<Yaku> *allYaku, const int hands[8][15]){
//hands邱Ƃ\ȂׂĂ̖
//cout<<"a "<<allYaku->size()<<endl;
makeKaidanFrom815(allYaku, hands);//Ki
/*
int pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"b "<<allYaku->size()<<" " <<pa<<endl;
*/
makePairFrom815(allYaku, hands);//yA
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"c "<<allYaku->size()<<" " <<pa<<endl;
*/
makeTankiFrom815(allYaku, hands);//PR
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"d "<<allYaku->size()<<" " <<pa<<endl;
*/
makePass(allYaku);//pX
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"d "<<allYaku->size()<<" " <<pa<<endl;
*/
}
void makeAllYaku2(vector<Yaku> *allYaku, const int hands[8][15], int64 handsbit){
//hands邱Ƃ\ȂׂĂ̖
//cout<<"a "<<allYaku->size()<<endl;
/*
int x[8][15]={{0}};
convBitTo815(x, handsbit);
print815(x);
cout<<endl;
for(int i=0;i<5;i++){
for(int j=0;j<15;j++){
x[i][j] = hands[i][j];
}
}
cout << endl;
print815(x);
//exit(1);
*/
makeKaidanFromBit(allYaku, handsbit);//Ki
/*
int pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"b "<<allYaku->size()<<" " <<pa<<endl;
*/
makePairFrom815(allYaku, hands);//yA
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"c "<<allYaku->size()<<" " <<pa<<endl;
*/
makeTankiFrom815(allYaku, hands);//PR
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"d "<<allYaku->size()<<" " <<pa<<endl;
*/
makePass(allYaku);//pX
/*
pa=0;
for(int i=0;i<allYaku->size();i++){
if((*allYaku)[i].isPass())pa++;
}
cout<<"d "<<allYaku->size()<<" " <<pa<<endl;
*/
}
void pickKaidan(vector<Yaku> *kaidan, const vector<Yaku> &allYaku){
for(int i=0;i<allYaku.size();i++){
if( allYaku[i].isKaidan() ){
kaidan->push_back( allYaku[i] );
}
}
}
void pickPair(vector<Yaku> *pair, const vector<Yaku> &allYaku){
for(int i=0;i<allYaku.size();i++){
if( allYaku[i].isPair() ){
pair->push_back( allYaku[i] );
}
}
}
void pickTanki(vector<Yaku> *tanki, const vector<Yaku> &allYaku){
for(int i=0;i<allYaku.size();i++){
if( allYaku[i].isTanki() ){
tanki->push_back( allYaku[i] );
}
}
}
void pickLegalKaidan(vector<Yaku> *legalYaku, const vector<Yaku> &allYaku, const Table &table){
int i;
if(table.isKakumei()){//v̂Ƃ
for(i=0;i<allYaku.size();i++){
//KiŖł̋D̋傫
if( allYaku[i].isKaidan() &&
(allYaku[i].mNum==table.mBafuda.mNum && allYaku[i].mRankR<table.mBafuda.mRankL)
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits)){
legalYaku->push_back( allYaku[i] );
}
}
}
}else{//vł͂ȂƂ
for(i=0;i<allYaku.size();i++){
//KiŖł̋D̋傫
if( (allYaku[i].isKaidan()) &&
allYaku[i].mNum==table.mBafuda.mNum && allYaku[i].mRankL>table.mBafuda.mRankR)
{
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits)){
legalYaku->push_back( allYaku[i] );
}
}
}
}
}
void pickLegalPair(vector<Yaku> *legalYaku, const vector<Yaku> &allYaku, const Table &table){
int i;
if(table.isKakumei()){//v̂Ƃ
for(i=0;i<allYaku.size();i++){
//KiŖł̋D̋傫
if( allYaku[i].isPair() &&
allYaku[i].mNum==table.mBafuda.mNum && allYaku[i].mRankL<table.mBafuda.mRankL
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits)){
legalYaku->push_back( allYaku[i] );
}
}
}
}else{//vł͂ȂƂ
for(i=0;i<allYaku.size();i++){
//KiŖł̋D̋傫
if( (allYaku[i].isPair()) &&
allYaku[i].mNum==table.mBafuda.mNum && allYaku[i].mRankR>table.mBafuda.mRankL
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits)){
legalYaku->push_back( allYaku[i] );
}
}
}
}
}
void pickLegalTanki(vector<Yaku> *legalYaku, const vector<Yaku> &allYaku, const Table &table){
int i;
if(table.mBafuda.isJTanki()){//W[J[PR̓XyRlȂ
for(i=0; i < allYaku.size(); i++){
if(allYaku[i].isSpade3()==1){
legalYaku->push_back( allYaku[i] );
break;
}
}
}
else if(table.isKakumei()){//v̂Ƃ
for(i=0; i < allYaku.size(); i++){
//KiŖł̋D̋傫
if(allYaku[i].mNum==1 && allYaku[i].mRankL<table.mBafuda.mRankL){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits || allYaku[i].isJTanki() )){
legalYaku->push_back( allYaku[i] );
}
}
}
}
else{//vł͂ȂƂ
for(i=0; i < allYaku.size(); i++){
//KiŖłE̋D̋傫
if(allYaku[i].mNum==1 && allYaku[i].mRankR>table.mBafuda.mRankL){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==allYaku[i].mSuits || allYaku[i].isJTanki() )){
legalYaku->push_back( allYaku[i] );
}
}
}
}
}
void pickAllLegalYaku(vector<Yaku> *legalYaku, const vector<Yaku> &allYaku, const Table &table){
//̎D\łS@̂
//݂̏̏ɂāAitablej
//ô݂sbNAbv
if(table.isOnset()){
//pXOił̓pXׂ͂łȂƐMĂj
for(int i=0;i<allYaku.size()-1;i++){
legalYaku->push_back( allYaku[i] );
}
}else{//eX̏ɑ
if(table.isTanki()){
pickLegalTanki(legalYaku, allYaku, table);
}
else if(table.isPair()){
pickLegalPair(legalYaku, allYaku, table);
}
else if(table.isKaidan()){
pickLegalKaidan(legalYaku, allYaku, table);
}
}
}
void makeKaidanFrom815(vector<Yaku> *yaku, const int hands[8][15]){
//hands邱Ƃ̉\ȊKiyakuɓ
//LqiGɂȂ̂ŏ͈̏؍lȂ
//Ƃōv̂o
int joker = (hands[4][1]!=0);
int suit, rank;
for(suit=0; suit<4; suit++){//X[gƈ
for(rank=0; rank<13;rank++){//n_肷i蓾̂[12-13-14]}fj
int length = 0; //Lт钷i̖j
int joker_flag = joker; //joker͎g邩B
int searching = 1; //T
while(searching==1){
if(rank+length<15 && hands[suit][rank+length]==1){//J[hȂ
length++;
}else if(joker_flag==1){//ȂĂW[J[gȂ
length++;
joker_flag = 0;
}else{//Ȃꍇ͂܂
searching = 0;
}
if(searching==1 && length>=3){//Ki
int64 hd = IS_KAIDAN;
//hd |= (length<6) ? IS_NUM(length) : IS_NUM(6);//6?܂ł̓rbgg
int i, JposSuit=-1, JposRank=-1;
int bitSuit = 0; bitSuit|=(1<<suit);
for(i=rank;i<rank+length;i++){
if(hands[suit][i]==1){//1Ȃ1~13Ȃ
hd |= CARDBIT(suit, i);
}else{//Ȃjokerg
hd |= IS_JUSED;
JposSuit = suit;JposRank = i;
}
}
//if( rank<=6 && 6<=rank+length-1 )hd|=IS_8GIRI;//8舵ɂȂ
Yaku cd(hd, bitSuit, length, rank, rank+length-1, JposSuit, JposRank);
yaku->push_back(cd);
if(joker_flag==1){//jokerg킸ɗĂAjokerɒuKi邱Ƃł
for(i=rank;i<rank+length;i++){
int64 mask = ~CARDBIT(suit, i);//jokergƂ0
int64 hdj = (mask&hd)|IS_JUSED;//ĉ͎c
JposSuit=suit, JposRank=i;//joker|WV͕ʕϐ̂ߑŜςKv͂ȂîHj
Yaku cd(hdj, bitSuit, length, rank, rank+length-1, JposSuit, JposRank);
yaku->push_back(cd);
}
}
}
}//while(searching)
}//for(order
}//for(suit
}
void makeKaidanFromBit(vector<Yaku> *yaku, const int64 hands){
int64 kaidan1 = 3ull;
int64 kaidan2 = 5ull;
//cout << "j"<<endl;
//printBit(hands);
if( hands&IS_JUSED ){//jokerĂ
for(int suit=0; suit<4; suit++){
int bitSuit = (1<<suit);
//int64 hands1 = hands<<(suit*13);//̃X[g̎n_
//for(int rank=1; rank<13; rank++){//11 12
for(int rank=1; rank<13; rank++){//12 13
int64 kaidan = kaidan1 << (suit*13 + rank-1);//n_
//int64 hands2 = hands1<<(rank-1);//n_
//int64 temp = hands2&kaidan1;
int64 temp = hands&kaidan;
int bitnum = popCount64bit(temp);
//cout<<"k"<<endl;
//printBit(hands);
//printBit(kaidan);
//cout << "kasanari " << bitnum << endl;
if( bitnum==2 ){//2ƂrbgĂ
//n_11...Ŏn܂
int64 hd = temp;
int JposSuit = -1;
int JposRank = -1;
bool j_flag = true;
int length = 2;
//joker + 2AōKi
Yaku cd1(temp|IS_KAIDAN|IS_JUSED, bitSuit, 3, rank-1, rank+1, suit, rank-1);
yaku->push_back(cd1);
Yaku cd2(temp|IS_KAIDAN|IS_JUSED, bitSuit, 3, rank, rank+2, suit, rank+length);
yaku->push_back(cd2);
for(int k=rank+2; k<=13; k++){//11 12 13̉E[܂
if( hands&CARDBIT(suit,k) ){
length++;
temp|=CARDBIT(suit,k);
//cout<<suit<<" "<<rank<<" "<<1<<endl;
//printBit(temp);
{
Yaku cd(temp|IS_KAIDAN, bitSuit, length, rank, rank+length-1, JposSuit, JposRank);
yaku->push_back(cd);
}
if( j_flag ){//jokergĂȂ
{
Yaku cd(temp|IS_KAIDAN|IS_JUSED, bitSuit, length, rank, rank+length-1, suit, rank-1);
yaku->push_back(cd);
}
{
Yaku cd(temp|IS_KAIDAN|IS_JUSED, bitSuit, length, rank, rank+length-1, suit, rank+length);
yaku->push_back(cd);
}
for(int l=rank+1; l<k; l++){//Ki̎n_ƏI_ӏjokerɒuo[W
int64 jtemp = (temp&(~CARDBIT(suit,l)))|IS_JUSED;//joker0ɕԂ
//cout<<suit<<" "<<rank<<" "<<2<<endl;
//printBit(jtemp);
Yaku cd(jtemp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, suit, l);
yaku->push_back(cd);
}
}
}else if( j_flag ){//Ȃjokerg
/*
if(length>=3){//܂łŊKiĂAjokerƒuo[W
for(int l=rank+1; l<k-1; l++){
int64 jtemp = (temp&(~CARDBIT(suit,l)))|IS_JUSED;//joker0ɕԂ
cout<<suit<<" "<<rank<<" "<<2<<endl;
printBit(jtemp);
Yaku cd(jtemp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, suit, l);
yaku->push_back(cd);
}
}
*/
/*
else{
int64 jtemp = (temp&(~CARDBIT(suit,k+1)))|IS_JUSED;//joker0ɕԂ
Yaku cd(jtemp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, suit, l);
yaku->push_back(cd);
}
*/
//jokerɒuo[W
JposSuit = suit;
JposRank = k;
length++;
//cout<<suit<<" "<<rank<<" "<<3<<endl;
//printBit(temp);
//Yaku cd(temp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, JposSuit, JposRank);
//yaku->push_back(cd);
j_flag = false;
}else{
k=15;
}
}
//break;
}else if(bitnum==1 && rank<12){//11 12 13ő
//n_101...Ŏn܂
//joker1010ɎĝŁA낪0Ȃ炻̎_ŏI
kaidan = kaidan2 << (suit*13+rank-1);//n_
temp = hands&kaidan;
if( popCount64bit(temp)==2 ){
int length = 3;
//101lj
//cout<<suit<<" "<<rank<<" "<<4<<endl;
//printBit(temp);
{
Yaku cd1(temp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, suit, rank+1);
yaku->push_back(cd1);
}
//L
for(int k=rank+3; k<=13; k++){//_13܂
if( hands&CARDBIT(suit,k) ){
length++;
temp|=CARDBIT(suit,k);
//cout<<suit<<" "<<rank<<" "<<5<<endl;
//printBit(temp);
Yaku cd(temp|IS_JUSED|IS_KAIDAN, bitSuit, length, rank, rank+length-1, suit, rank+1);
yaku->push_back(cd);
}else{
break;
}
}
}else{
rank+=2;
}
}else{
rank++;
}
}
}
}else{
//cout<<"9090"<<endl;
for(int suit=0; suit<4; suit++){
int bitSuit = (1<<suit);
//int64 hands1 = hands<<(suit*13);//̃X[g̎n_
for(int rank=1; rank<12; rank++){//11 12 13 Œijoker͂Ȃ̂14͍lȂj
int64 kaidan = kaidan1 << (suit*13+rank-1);//n_
int64 temp = hands&kaidan;
//cout<<"k"<<endl;
//printBit(hands);
//printBit(kaidan);
//cout << "kasanari " << popCount64bit(temp) << endl;
if( popCount64bit(temp)==2 ){//2ƂrbgĂ
//int64 hd = temp;
int length = 2;
for(int k=rank+2; k<14; k++){
if( hands&CARDBIT(suit, k) ){
length++;
temp|=CARDBIT(suit, k);
Yaku cd(temp|IS_KAIDAN, bitSuit, length, rank, rank+length-1, -1, -1);
yaku->push_back(cd);
}else{
break;
}
}
}else{
rank++;
}
//joker͂Ȃ̂ŁȂ͍lȂ
}
}
}
}
void makePairFrom815(vector<Yaku> *yaku, const int hands[8][15]){
//LqiGɂȂ̂ŏ͈̏؍lȂ
//Ƃōv̂o
#define PATTERN_NUM 11
int PATTERN[PATTERN_NUM][4] = {
{1,1,0,0},{1,0,1,0},{1,0,0,1},{0,1,1,0},{0,1,0,1},{0,0,1,1},//62
{1,1,1,0},{1,1,0,1},{1,0,1,1},{0,1,1,1}, //43
{1,1,1,1} //14
};//yÅeX[g̉\p^[
//ɍv悤ɒTĂ
int suit, rank, pat;
int joker = (hands[4][1]!=0);
for(rank=1;rank<=13;rank++){//eNɂĂ݂Ă
for(pat=0;pat<PATTERN_NUM; pat++){//ꂼ̃p^[ɂ
int num = 0, match = 0, unmatch = 0;
for(suit=0;suit<4;suit++){//X[gׂĂ
if(PATTERN[pat][suit]==1){//Ỹp^[ɂ
num++;//
if(hands[suit][rank]==1){//Do
match++;
}else{//oȂ
unmatch++;
}
}
}//for(suit
if(num == match){//jokerg킸ɍ邱Ƃł
int64 hd = IS_PAIR;
int bitSuit = 0;
for(suit=0;suit<4;suit++){
if(PATTERN[pat][suit]==1){
//hd |= CARDBIT(suit, rank)|IS_NUM(num);
hd |= CARDBIT(suit, rank);
bitSuit |= (1<<suit);
}
}
//if(rank==6)hd|=IS_8GIRI;//8
Yaku cd(hd, bitSuit, num, rank, rank, -1, -1);
yaku->push_back(cd);
if(joker==1){//jokerɒuo[Wi8Ŏg炢_킩Ȃj
//hd |= 0ull;
for(suit=0;suit<4;suit++){//jokerɒuX[g
if(PATTERN[pat][suit]==1){
int64 mask = ~CARDBIT(suit, rank);//W[J[gƂ낾0
//int64 hdj = (mask&hd)|IS_JUSED|IS_NUM(num);
int64 hdj = (mask&hd)|IS_JUSED;
int JposSuit=suit, JposRank=rank;//joker̈ʒu
Yaku cdj(hdj, bitSuit, num, rank, rank, JposSuit, JposRank);
yaku->push_back(cdj);
}
}
}
}else if(joker==1 && unmatch==1){//jokergāAȂ̂1Ȃ
//int64 hd = IS_PAIR|IS_JUSED|IS_NUM(num);
int64 hd = IS_PAIR|IS_JUSED;
int bitSuit = 0;
int JposSuit=-1, JposRank=-1;
for(suit=0;suit<4;suit++){
if(PATTERN[pat][suit]==1){
bitSuit |= (1<<suit);
if(hands[suit][rank] == 1){
hd |= CARDBIT(suit, rank);
}else{
JposSuit=suit, JposRank=rank;
}
}
}
Yaku cd(hd, bitSuit, num, rank, rank, JposSuit, JposRank);
yaku->push_back(cd);
}
}
//Ō5J[h
if(hands[0][rank] && hands[1][rank] && hands[2][rank] && hands[3][rank] && joker){//So
//int64 hd = IS_PAIR|IS_JUSED|IS_NUM(5);
int64 hd = IS_PAIR|IS_JUSED;
int JposSuit=4, JposRank=rank;
hd|=CARDBIT(0, rank);hd|=CARDBIT(1, rank);hd|=CARDBIT(2, rank);hd|=CARDBIT(3, rank);
Yaku cd(hd, 15, 5, rank, rank, JposSuit, JposRank);
yaku->push_back(cd);
}
}//for(rank
}
void makeTankiFrom815(vector<Yaku> *yaku, const int hands[8][15]){
//815zPR
int suit, rank;
int joker = (hands[4][1]!=0);//jokerĂ
for(suit=0;suit<4;suit++){
for(rank=1;rank<=13;rank++){
if(hands[suit][rank]==1){
int bitSuit = (1<<suit);
//int64 hd = CARDBIT(suit, rank)|IS_NUM(1);
int64 hd = CARDBIT(suit, rank)|IS_TANKI;
Yaku cd(hd, bitSuit, 1, rank, rank, -1, -1);
yaku->push_back(cd);
}
}
}
//jokerPŘ
if(joker){
//int64 hd = IS_JUSED|IS_NUM(1);
int64 hd = IS_JUSED|IS_TANKI;
Yaku cd(hd, 0, 1, 0, 14, 0, 14);
yaku->push_back(cd);
}
}
void printYakuVec(const vector<Yaku> &vecCards){
for(int i=0;i<vecCards.size();i++){
cout << i << endl;
vecCards[i].printBit();
cout << endl;
}
}
void makePass(vector<Yaku> *yaku){
//WɃpX
int64 hd = IS_PASS;
Yaku cd(hd, 0, 0, 0, 0, -1, -1);
yaku->push_back(cd);
}
bool isYaku1HigherThanYaku2(const Yaku &c1, const Yaku &c2){
//v̂ƂA12Ƃ1Ԃ
return ( c1.mRankR > c2.mRankR);
}
bool isYaku1LowerThanYaku2(const Yaku &c1, const Yaku &c2){
//ʏ펞ivłȂjƂA12Ƃ1Ԃ
return ( c1.mRankL < c2.mRankL);
}
void sortYakuByRank( vector<Yaku> *vecCards, bool isKakumei ){
//アɕёւ
if( isKakumei ){//v̂Ƃ
sort( vecCards->begin(), vecCards->end(), isYaku1HigherThanYaku2 );
}else{
sort( vecCards->begin(), vecCards->end(), isYaku1LowerThanYaku2 );
}
}
void makeYakuBFrom815(vector<Yaku> *tky, int hands[8][15], const Table &table){
if(table.isOnset()){//
makeKaidanFrom815(tky, hands);
//std::cout << "kaidan" << tky->size() << std::endl;
makePairFrom815(tky, hands);
//std::cout << "pair" << tky->size() << std::endl;
makeTankiFrom815(tky, hands);
//std::cout << "tanki" << tky->size() << std::endl;
//printVCard(tky);
}else{
if(table.isKaidan()){
vector<Yaku> atky;
makeKaidanFrom815(&atky, hands);
//std::cout << "ak" << atky.size() << std::endl;
//printVCard(&atky);
sortKaidan(tky, &atky, table);
//std::cout << "bk" << tky->size() << std::endl;
//printVCard(tky);
}else if(table.isPair()){
vector<Yaku> atky;
makePairFrom815(&atky, hands);
//std::cout << "ap" << atky.size() << std::endl;
//printVCard(&atky);
sortPair(tky, &atky, table);
//std::cout << "bp" << tky->size() << std::endl;
//printVCard(tky);
}else if(table.isTanki()){
vector<Yaku> atky;
makeTankiFrom815(&atky, hands);
//printVCard(&atky);
//std::cout << "at" << atky.size() << std::endl;
sortTanki(tky, &atky, table);
//std::cout << "bt" << tky->size() << std::endl;
//printVCard(tky);
}
//printVCard(tky);
makePass(tky);
}
}
void sortAllYaku(vector<Yaku> *tky, const vector<Yaku> *atky, const Table &table){
if(table.isOnset()){
//pXO
for(int i=0;i<atky->size()-1;i++){
tky->push_back( (*atky)[i] );
}
}else{
if(table.isTanki()){
sortTanki(tky, atky, table);
}
else if(table.isPair()){
sortPair(tky, atky, table);
}
else if(table.isKaidan()){
sortKaidan(tky, atky, table);
}
}
}
void sortKaidan(vector<Yaku> *tky, const vector<Yaku> *atky, const Table &table){
if(table.isKakumei()){//v̂Ƃ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if( (*atky)[i].isKaidan() &&
((*atky)[i].mNum==table.mBafuda.mNum && (*atky)[i].mRankR<table.mBafuda.mRankL)
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits)){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}else{//vł͂ȂƂ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if( ((*atky)[i].isKaidan()) &&
(*atky)[i].mNum==table.mBafuda.mNum && (*atky)[i].mRankL>table.mBafuda.mRankR)
{
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits)){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}
}
void sortPair(vector<Yaku> *tky, const vector<Yaku> *atky, const Table &table){
if(table.isKakumei()){//v̂Ƃ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if( ((*atky)[i].isPair()) &&
(*atky)[i].mNum==table.mBafuda.mNum && (*atky)[i].mRankL<table.mBafuda.mRankL
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits)){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}else{//vł͂ȂƂ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if( ((*atky)[i].isPair()) &&
(*atky)[i].mNum==table.mBafuda.mNum && (*atky)[i].mRankR>table.mBafuda.mRankR
){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits)){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}
}
void sortTanki(vector<Yaku> *tky, const vector<Yaku> *atky, const Table &table){
if(table.isJTanki()){//W[J[PR̓XyRlȂ
for(int i=0;i<atky->size();i++){
if((*atky)[i].isSpade3()==1){//X3Ă
tky->push_back((*atky)[i]);
break;
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}
else if(table.isKakumei()){//v̂Ƃ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if((*atky)[i].mNum==1 && (*atky)[i].mRankL<table.mBafuda.mRankL){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits || (*atky)[i].isJTanki() )){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}
else{//vł͂ȂƂ
for(int i=0;i<atky->size();i++){
//KiŖł̋D̋傫
if((*atky)[i].mNum==1 && (*atky)[i].mRankR>table.mBafuda.mRankR){
if( !table.isShibari() || (table.isShibari() && table.mBafuda.mSuits==(*atky)[i].mSuits || (*atky)[i].isJTanki() )){
tky->push_back((*atky)[i]);
}
}else if((*atky)[i].mNum==0){//pX͎c
tky->push_back((*atky)[i]);
}
}
}
}
/*
void removeLap(vector<Yaku> *vecCard, int64 cdBit){
//WCardƂ菜
int i = 0;
int64 mask = BITull(53)-1;//J[ĥԂiJ[h̍܂ł͌Ȃj
while( i < (*vecCard).size() ){//J[hW̒TĂ
if( ( mask & (*vecCard)[i].getCardBit() & cdBit ) == 0 ){//bitԂȂ
i++;//_i߂
}else{//
(*vecCard).erase( (*vecCard).begin() + i);//W菜
}
}
}
*/
| true |
a10c3fe67fd35e55d21a53a2abadcc69db7b8574 | C++ | Trietptm-on-Security/heap_history_viewer | /heaphistory.cpp | UTF-8 | 9,940 | 2.796875 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <limits>
#include "json.hpp"
// using json = json;
#include "heaphistory.h"
// Constructors for helper classes.
HeapConflict::HeapConflict(uint32_t tick, uint64_t address, bool alloc)
: tick_(tick), address_(address), allocation_or_free_(alloc) {}
// The code for the heap history.
HeapHistory::HeapHistory()
: current_tick_(0),
global_area_(std::numeric_limits<uint64_t>::max(), 0, 0, 1) {}
void HeapHistory::LoadFromJSONStream(std::istream &jsondata) {
nlohmann::json incoming_data;
incoming_data << jsondata;
uint32_t counter = 0;
for (const auto &json_element : incoming_data) {
if (json_element["type"].get<std::string>() == "alloc") {
recordMalloc(json_element["address"].get<uint64_t>(),
json_element["size"].get<uint32_t>(), 0);
std::cout << json_element << std::endl;
} else if (json_element["type"].get<std::string>() == "free") {
recordFree(json_element["address"].get<uint64_t>(), 0);
} else if (json_element["type"].get<std::string>() == "event") {
printf("[!] Need to parse/display events, no support yet.\n");
}
fflush(stdout);
//if (counter++ > 500)
// break;
}
printf("heap_blocks_.size() is %d\n", heap_blocks_.size());
fflush(stdout);
}
size_t HeapHistory::getActiveBlocks(
std::vector<std::vector<HeapBlock>::iterator> *active_blocks) {
// For the moment, implement a naive linear sweep of all heap blocks.
// This can certainly be made better, but keeping it simple has priority
// for the moment.
size_t active_block_count = 0;
for (std::vector<HeapBlock>::iterator iter = heap_blocks_.begin();
iter != heap_blocks_.end(); ++iter) {
if (isBlockActive(*iter)) {
active_blocks->push_back(iter);
++active_block_count;
}
}
return active_block_count;
}
bool HeapHistory::isBlockActive(const HeapBlock &block) {
return true;
/*if (!(block.end_tick_ < current_window_.minimum_tick_) &&
!(block.start_tick_ > current_window_.maximum_tick_) &&
!((block.address_ + block.size_) > current_window_.minimum_address_) &&
!(block.address_ < current_window_.maximum_address_)) {
return true;
}
return false;*/
}
void HeapHistory::setCurrentWindow(const HeapWindow &new_window) {
current_window_.reset(new_window);
}
void HeapHistory::recordMalloc(uint64_t address, size_t size, uint8_t heap_id) {
++current_tick_;
// Check if there is already a live block at this address.
if (live_blocks_.find(std::make_pair(address, heap_id)) !=
live_blocks_.end()) {
// Record a conflict.
recordMallocConflict(address, size, heap_id);
return;
}
heap_blocks_.push_back(HeapBlock(current_tick_, size, address));
this->cached_blocks_sorted_by_address_.clear();
live_blocks_[std::make_pair(address, heap_id)] = heap_blocks_.size() - 1;
global_area_.maximum_address_ =
std::max(address + size, global_area_.maximum_address_);
global_area_.minimum_address_ =
std::min(address, global_area_.minimum_address_);
// Make room for 5% more on the right hand side.
global_area_.maximum_tick_ =
(static_cast<double>(current_tick_) * 1.05) + 1.0;
global_area_.minimum_tick_ = 0;
}
void HeapHistory::recordFree(uint64_t address, uint8_t heap_id) {
// Any event has to clear the sorted HeapBlock cache.
++current_tick_;
std::map<std::pair<uint64_t, uint8_t>, size_t>::iterator current_block =
live_blocks_.find(std::make_pair(address, heap_id));
if (current_block == live_blocks_.end()) {
recordFreeConflict(address, heap_id);
return;
}
size_t index = current_block->second;
heap_blocks_[index].end_tick_ = current_tick_;
live_blocks_.erase(current_block);
// Set the max tick 5% higher than strictly necessary.
global_area_.maximum_tick_ =
(static_cast<double>(current_tick_) * 1.05) + 1.0;
}
void HeapHistory::recordFreeConflict(uint64_t address, uint8_t heap_id) {
conflicts_.push_back(HeapConflict(current_tick_, address, false));
}
void HeapHistory::recordMallocConflict(uint64_t address, size_t size,
uint8_t heap_id) {
conflicts_.push_back(HeapConflict(current_tick_, address, true));
}
void HeapHistory::recordRealloc(uint64_t old_address, uint64_t new_address,
size_t size, uint8_t heap_id) {
// How should realloc relations be visualized?
recordFree(old_address, heap_id);
recordMalloc(new_address, size, heap_id);
}
// Write out 6 vertices (for two triangles) into the buffer.
void HeapHistory::HeapBlockToVertices(const HeapBlock &block,
std::vector<HeapVertex> *vertices) {
block.toVertices(current_tick_, vertices);
}
size_t
HeapHistory::heapBlockVerticesForActiveWindow(std::vector<HeapVertex> *vertices) {
size_t active_block_count = 0;
for (std::vector<HeapBlock>::iterator iter = heap_blocks_.begin();
iter != heap_blocks_.end(); ++iter) {
if (isBlockActive(*iter)) {
HeapBlockToVertices(*iter, vertices);
++active_block_count;
}
}
return active_block_count;
}
// Extremely slow O(n) version of testing if a given point lies within any
// block.
bool HeapHistory::getBlockAtSlow(uint64_t address, uint32_t tick,
HeapBlock *result, uint32_t *index) {
for (std::vector<HeapBlock>::iterator iter = heap_blocks_.begin();
iter != heap_blocks_.end(); ++iter) {
if (iter->contains(tick, address)) {
*result = *iter;
*index = iter - heap_blocks_.begin();
return true;
}
}
return false;
}
void HeapHistory::updateCachedSortedIterators() {
// Makes sure there is a sorted iterator array.
if (cached_blocks_sorted_by_address_.size() == 0) {
// Fill the iterator cache.
for (std::vector<HeapBlock>::iterator iter = heap_blocks_.begin();
iter != heap_blocks_.end(); ++iter) {
cached_blocks_sorted_by_address_.push_back(iter);
}
auto comparison = [](const std::vector<HeapBlock>::iterator &left,
const std::vector<HeapBlock>::iterator &right) {
// Sort blocks in descending order by address, then tick.
return (left->address_ > right->address_) ||
(left->start_tick_ > right->start_tick_);
};
std::sort(cached_blocks_sorted_by_address_.begin(),
cached_blocks_sorted_by_address_.end(), comparison);
}
}
// Attempts to find a block on the heap at a given address and tick.
// If successful, the provided pointer is filled, and an index into
// the internal heap block vector is provided (this is useful for
// calculating vertex ranges).
//
// XXX: This code is still buggy, and does not seem to find all blocks.
// TODO(thomasdullien): Debug and fix.
//
bool HeapHistory::getBlockAt(uint64_t address, uint32_t tick, HeapBlock *result,
uint32_t *index) {
updateCachedSortedIterators();
std::pair<uint64_t, uint32_t> val(address, tick);
// Find the block whose lower left corner is the first (by address, then by
// tick, descending) to come after the requested point.
const std::vector<std::vector<HeapBlock>::iterator>::iterator candidate =
std::lower_bound(cached_blocks_sorted_by_address_.begin(),
cached_blocks_sorted_by_address_.end(), val,
[this](const std::vector<HeapBlock>::iterator &iterator,
const std::pair<uint64_t, uint32_t> &pair) {
fflush(stdout);
return (pair.first < iterator->address_) ||
(pair.second < iterator->start_tick_);
});
if (candidate == cached_blocks_sorted_by_address_.end()) {
return false;
}
// Check that the point lies within the candidate block.
std::vector<HeapBlock>::iterator block = *candidate;
if ((address > (block->address_ + block->size_)) ||
(address < block->address_) || (tick > block->end_tick_) ||
(tick < block->start_tick_)) {
return false;
}
*result = *block;
*index = *candidate - heap_blocks_.begin();
return true;
}
// Provided a displacement (percentage of size of the current window in x and y
// direction), pan the window accordingly.
void HeapHistory::panCurrentWindow(double dx, double dy) {
current_window_.pan(dx, dy);
}
// Zoom toward a given point on the screen. The point is given in relative
// height / width of the current window, e.g. the center is 0.5, 0.5.
void HeapHistory::zoomToPoint(double dx, double dy, double how_much_x,
double how_much_y, long double max_height,
long double max_width) {
current_window_.zoomToPoint(dx, dy, how_much_x, how_much_y, max_height,
max_width);
}
/*const ContinuousHeapWindow &
HeapHistory::getGridWindow(uint32_t number_of_lines) {
// Find the first power-of-two p so that 16 * 2^p > height, and
// 16 * 2^p2 > width. Then update the grid_window_ variable and
// return it.
auto next_greater_pow2 = [number_of_lines](uint64_t limit) {
uint64_t p = 1;
while ((number_of_lines / 2) * p < limit) {
p = p << 1;
};
return p;
};
uint64_t p1 = next_greater_pow2(current_window_.height());
uint64_t p2 = next_greater_pow2(current_window_.width());
auto round_up = [](uint64_t input, uint64_t pow2) {
return input += (pow2 - (input % pow2));
};
grid_rectangle_.maximum_tick_ =
round_up(current_window_.maximum_tick_, p2 * (number_of_lines / 2));
grid_rectangle_.maximum_address_ =
round_up(current_window_.maximum_address_, p1 * number_of_lines / 2);
grid_rectangle_.minimum_tick_ =
grid_rectangle_.maximum_tick_ - p2 * number_of_lines;
grid_rectangle_.minimum_address_ =
grid_rectangle_.maximum_address_ - p1 * number_of_lines;
return grid_rectangle_;
}*/
| true |
cdb0f9ad0c5b00e86abd7ad4c8b33a4702f120f0 | C++ | mingliang-99/c_practise | /practise/c_lianbiao/c_lianbiao_leetcode/c_lianbiao_leetcode/main.cpp | UTF-8 | 6,748 | 3.5625 | 4 | [] | no_license | //
// main.cpp
// c_lianbiao_leetcode
//
// Created by mingliang on 2020/12/11.
//
#include <iostream>
struct ListNode{
int val;
struct ListNode *next;
ListNode(int x):val(x),next(nullptr){}
};
//生成测试链表
ListNode* createList(int len){
if(len == 0){
return NULL;
}
int val;
ListNode *cur = new ListNode(0);//创建第一个节点
ListNode *head = cur;//记录头节点
if(head == NULL){
return NULL;
}
for(int i=0;i<len;i++){
printf("create val=%d \n",i);
val = i;
ListNode *tmp = new ListNode(val);
cur->next = tmp;
cur = tmp;
}
return head->next;
}
ListNode* traversalList(ListNode *head){
ListNode *cur = head;
if(head == nullptr){
return nullptr;
}
while (cur != nullptr) {
if(cur){
printf("check val=%d \n",cur->val);
}
cur = cur->next;
}
return head;
}
//反转一个链表
/*
输入 1-> 2-> 3->4->5
pre->cur->next
输出 5->4->3->2->1
*/
//链表反转
ListNode* ReverseList2(ListNode* head)
{
if (head == nullptr){
return nullptr;
}
ListNode* reverseHead = nullptr;
// 指针1:当前节点
ListNode* cur = head;
// 指针2:当前节点的前一个节点
ListNode* pre = nullptr;
while(cur != nullptr){
// 指针3:当前节点的后一个节点
ListNode* next = cur->next;
if(next == nullptr){
reverseHead = cur;
}
// 将当前节点的后一个节点指向前一个节点
cur->next = pre; // 1-> null ;
// 将前一个节点指向当前节点
pre = cur; // pre = 1;
// 将当前节点指向后一个节点
cur = next; // cur = 2;
}
return reverseHead;
}
/*
链表是否有环/交叉 快慢指针
1.执行逻辑
2.边界条件
*/
bool hasCycle(ListNode *head) {
if(head == nullptr || head->next == nullptr){
return false;
}
ListNode *slow = head;
ListNode *fast = head->next;
while (slow != fast) {
if(fast == nullptr || fast->next == nullptr){
return false;
}
slow = slow->next;
fast = fast->next->next;
}
return true;
}
/*
链表题目三: 删除链表倒数n 个节点
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
思路 :
1.使用两个指针,第一个指针先移动 n+1 ,第二个指针从头开始移动 ,保持固定间隔
2.第一个指针移动到最后的节点,第二个指针指向最后一个节点开始倒数第n 个节点。
3.重新链接第二个指针所应用节点的 next 指针的下下个节点
时间复杂度 O(n)
空间复杂度 O(1)
*/
#if 1
ListNode *deleteNPoint(ListNode *pHead,int n){
if(pHead == nullptr || pHead == nullptr){
return nullptr;
}
ListNode *dummy = new ListNode(0);
dummy->next = pHead;
ListNode *first = dummy;
ListNode *second = dummy;
ListNode *toBeDelete = nullptr;
for(int i=0;i<n-1;i++){
if(first->next != nullptr){
first = first->next;
}else{
return nullptr;
}
}
printf("first->val = %d",first->val);
while (first != nullptr) {
first = first->next;
second = second->next;
}
printf("second->val = %d",second->val);
toBeDelete = second;
printf("toBeDelete->val = %d\n",toBeDelete->val);
if(second->next != nullptr){
second->next = second->next->next;
free(toBeDelete);
toBeDelete = NULL;
}
return dummy->next;
}
#endif
//https://www.cnblogs.com/Demrystv/p/9311288.html
//删除单链表中的倒数第K 个节点
ListNode* removeLastKthNodeInSingle(ListNode *head, int lastKth){
if (head == NULL || lastKth < 1){
return NULL;
}
ListNode *cur = head;
while (cur != NULL){
lastKth--;
cur = cur->next;
}
if (lastKth == 0){//第一个节点删除
head = head->next;
}
// 可以举例子:1 2 3 4 5 的倒数第4个节点
if (lastKth < 0){
cur = head;
while (++lastKth != 0){
cur = cur->next;
}
cur->next = cur->next->next;
}
return head;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/*
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的
链接: https://leetcode-cn.com/problems/merge-two-sorted-lists/
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == nullptr || l2 == nullptr){
return nullptr;
}
ListNode *dummy = new ListNode(0);
while(1){
if(l1 == nullptr && l1 == nullptr){
break;
}
if(l1 && l2){
if(l1->val >= l2->val){
dummy->next = l1;
dummy=l1;
l1 = l1->next;
}else{
dummy->next = l2;
dummy=l2;
l2 = l2->next;
}
}
}
return dummy->next;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
ListNode *text = createList(5);
ListNode *traver = traversalList(text);
// ListNode *vert = ReverseList2(traver);
// ListNode *traver2 = traversalList(vert);
// ListNode *todel = removeLastKthNodeInSingle(traver,3);
ListNode *todel = deleteNPoint(traver,4);
std::cout << "Hello, World!=======\n";
ListNode *trave3 = traversalList(todel);
//合并有序列表
ListNode *testL1 = new ListNode(1);
ListNode *L1Node2 = new ListNode(2);
ListNode *L1Node3 = new ListNode(4);
testL1->next
cur->next = tmp;
return 0;
}
| true |
4f093571ace6482bfddf1c85703f7c0bd2e2ed1d | C++ | ViniciusLobo/Lights-of-World | /New/SincroB-core/SincroB-core/Core/maths/vec3.cpp | UTF-8 | 3,026 | 3.484375 | 3 | [] | no_license | #include "vec3.hpp"
namespace engine { namespace maths {
vec3::vec3(const float& x, const float& y, const float& z)
{
this->x = x;
this->y = y;
this->z = z;
}
vec3& vec3::add(const vec3& vector)
{
x += vector.x;
y += vector.y;
z += vector.z;
return *this;
}
vec3& vec3::subtract(const vec3& vector)
{
x -= vector.x;
y -= vector.y;
z -= vector.z;
return *this;
}
vec3& vec3::multiply(const vec3& vector)
{
x *= vector.x;
y *= vector.y;
z *= vector.z;
return *this;
}
vec3& vec3::divide(const vec3& vector)
{
x /= vector.x;
y /= vector.y;
z /= vector.z;
return *this;
}
bool vec3::compare(const vec3& vector)
{
return x == vector.x && y == vector.y && z == vector.z;
}
vec3 operator+(vec3 vector, const vec3& other_vector)
{
return vector.add(other_vector);
}
vec3 operator-(vec3 vector, const vec3& other_vector)
{
return vector.subtract(other_vector);
}
vec3 operator*(vec3 vector, const vec3& other_vector)
{
return vector.multiply(other_vector);
}
vec3 operator/(vec3 vector, const vec3& other_vector)
{
return vector.divide(other_vector);
}
vec3 operator+(vec3 vector, const float other_vector)
{
return vector + vec3((float) other_vector,(float) other_vector,(float) other_vector);
}
vec3 operator-(vec3 vector, const float other_vector)
{
return vector - vec3((float) other_vector,(float) other_vector,(float) other_vector);
}
vec3 operator*(vec3 vector, const float other_vector)
{
return vector * vec3((float) other_vector,(float) other_vector,(float) other_vector);
}
vec3 operator/(vec3 vector, const float other_vector)
{
return vector / vec3((float) other_vector,(float) other_vector,(float) other_vector);
}
vec3& vec3::operator+=(const vec3& vector)
{
return add(vector);
}
vec3& vec3::operator-=(const vec3& vector)
{
return subtract(vector);
}
vec3& vec3::operator*=(const vec3& vector)
{
return multiply(vector);
}
vec3& vec3::operator/=(const vec3& vector)
{
return divide(vector);
}
bool vec3::operator==(const vec3& vector)
{
return compare(vector);
}
bool vec3::operator!=(const vec3& vector)
{
return !(*this == vector);
}
std::ostream& operator<<(std::ostream& stream, const vec3& vector)
{
stream << "<Vector3 (" << vector.x << ", " << vector.y << ", " << vector.z << ")>";
return stream;
}
} } | true |
f8d80de605a32e5ce737a955de4a7bd841ac781a | C++ | OS2World/APP-SCIENCE-SimRobot2 | /Vector.cpp | UTF-8 | 5,657 | 2.84375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | /***********************************************************************
**** ****
**** SimRobot ****
**** Universitaet Bremen, Fachbereich 3 - Informatik ****
**** Zentrum fuer Kognitionswissenschaften ****
**** Autor: Uwe Siems ****
**** ****
**** Datei: Vector.cc ****
**** Inhalt: Implementation der Klassen VECTOR, MATRIX, MOVEMATRIX ****
**** ****
***********************************************************************/
#include "Vector.h"
#include <math.h>
// Fuer Kommentare siehe "Vektor.h"
inline REAL sqr (REAL x) { return x*x; }
inline REAL MakeDeg (REAL x) { return x / PI * 180; }
inline REAL MakeRad (REAL x) { return x / 180 * PI; }
INTEGER sign (REAL x)
{
if (x > 0)
return 1;
else if (x < 0)
return -1;
else
return 0;
}
VECTOR::VECTOR ()
{
x = 0.0;
y = 0.0;
z = 0.0;
}
VECTOR::VECTOR (REAL xx, REAL yy, REAL zz)
{
x = xx;
y = yy;
z = zz;
}
BOOLEAN VECTOR::Norm ()
{
REAL len = abs (*this);
if (len > EPSILON) {
x = x / len;
y = y / len;
z = z / len;
return TRUE;
}
else
return FALSE;
}
BOOLEAN VECTOR::operator == (const VECTOR& v)
{
return x == v.x && y == v.y && z == v.z;
}
MATRIX::MATRIX () :
e1 (1.0, 0.0, 0.0),
e2 (0.0, 1.0, 0.0),
e3 (0.0, 0.0, 1.0)
{}
MATRIX::MATRIX (const VECTOR& v1, const VECTOR& v2, const VECTOR& v3)
{
e1 = v1;
e2 = v2;
e3 = v3;
}
MOVEMATRIX::MOVEMATRIX () {}
MOVEMATRIX::MOVEMATRIX (const MATRIX& m, const VECTOR& v)
{
Matrix = m;
Offset = v;
}
REAL abs (const VECTOR& V)
{ return sqrt (V * V); }
REAL abs (REAL r)
{ return (r >= 0 ? r : -r); }
VECTOR operator + (const VECTOR& V1, const VECTOR& V2)
{ return VECTOR (V1.x + V2.x, V1.y + V2.y, V1.z + V2.z); }
VECTOR operator - (const VECTOR& V)
{ return VECTOR (-V.x, -V.y, -V.z); }
VECTOR operator - (const VECTOR& V1, const VECTOR& V2)
{ return VECTOR (V1.x - V2.x, V1.y - V2.y, V1.z - V2.z); }
VECTOR operator * (REAL skalar, const VECTOR& V)
{ return VECTOR (skalar * V.x, skalar * V.y, skalar * V.z); }
VECTOR operator * (const VECTOR& V, REAL skalar)
{ return VECTOR (skalar * V.x, skalar * V.y, skalar * V.z); }
VECTOR operator / (const VECTOR& V, REAL skalar)
{ return V * (1/skalar); }
REAL operator * (const VECTOR& V1, const VECTOR& V2)
{ return V1.x * V2.x + V1.y * V2.y + V1.z * V2.z; }
REAL CosAngle (const VECTOR& V1, const VECTOR& V2)
{
VECTOR vn1(V1),
vn2(V2);
if (vn1.Norm () && vn2.Norm ())
return vn1 * vn2;
else
return 0;
}
VECTOR CrossProduct (const VECTOR& V1, const VECTOR& V2)
{
return VECTOR (V1.y*V2.z - V1.z*V2.y,
V1.z*V2.x - V1.x*V2.z,
V1.x*V2.y - V1.y*V2.x);
}
REAL det (const VECTOR& a, const VECTOR& b, const VECTOR& c)
{
return a.x * (b.y*c.z - b.z*c.y)
+ a.y * (b.z*c.x - b.x*c.z)
+ a.z * (b.x*c.y - b.y*c.x);
}
VECTOR operator * (const MATRIX& M, const VECTOR& V)
{ return V.x * M.e1 + V.y * M.e2 + V.z * M.e3; }
MATRIX operator * (const MATRIX& M1, const MATRIX& M2)
{ return MATRIX (M1 * M2.e1, M1 * M2.e2, M1 * M2.e3); }
VECTOR operator * (const MOVEMATRIX& MM, const VECTOR& V)
{ return MM.Matrix * V + MM.Offset; }
MOVEMATRIX operator * (const MOVEMATRIX& MM1, const MOVEMATRIX& MM2)
{ return MOVEMATRIX (MM1.Matrix * MM2.Matrix, MM1 * MM2.Offset); }
MATRIX TurnXYMatrix (REAL deg)
{
REAL sinv = sin (MakeRad (deg));
REAL cosv = cos (MakeRad (deg));
return MATRIX (VECTOR (cosv, sinv, 0.0),
VECTOR (-sinv, cosv, 0.0),
VECTOR (0.0, 0.0, 1.0));
}
MATRIX TurnXZMatrix (REAL deg)
{
REAL sinv = sin (MakeRad (deg));
REAL cosv = cos (MakeRad (deg));
return MATRIX (VECTOR (cosv, 0.0, -sinv),
VECTOR (0.0, 1.0, 0.0),
VECTOR (sinv, 0.0, cosv));
}
MATRIX TurnYZMatrix (REAL deg)
{
REAL sinv = sin (MakeRad (deg));
REAL cosv = cos (MakeRad (deg));
return MATRIX (VECTOR (1.0, 0.0, 0.0),
VECTOR (0.0, cosv, sinv),
VECTOR (0.0, -sinv, cosv));
}
BOOLEAN ExtractAngles (const MATRIX& M, REAL& alpha, REAL& beta, REAL& gamma)
// Bestimme die Winkel, um die die Standard-Matrix gedreht werden
// muss, damit sich die angegebene Matrix ergibt.
// Reihenfolge ist X-Achse, Y-Achse, Z-Achse.
{
MATRIX m(M);
if ((! m.e1.Norm ()) || // Die Vektoren der Matrix muessen normiert
(! m.e2.Norm ()) || // sein und ungleich (0,0,0)
(! m.e3.Norm ()) ||
(m.e1 * m.e2 > EPSILON) || // Die Vektoren muessen rechtwinklig
(m.e2 * m.e3 > EPSILON) || // zueinander stehen
(m.e3 * m.e1 > EPSILON)) return FALSE;
REAL alphac, betac, gammac, h;
h = sqrt (sqr (m.e1.x) + sqr (m.e1.y));
if (h < EPSILON) {
alpha = 0;
beta = -90 * sign (m.e1.z);
gamma = MakeDeg (acos (m.e2.y)) * -sign (m.e2.x);
}
else {
gammac = m.e1.x / h;
betac = h;
alphac = m.e3.z / h;
gamma = MakeDeg (acos (gammac)) * (m.e1.y < 0 ? -1 : 1);
beta = MakeDeg (-acos (betac)) * (m.e1.z < 0 ? -1 : 1);
alpha = MakeDeg (acos (alphac)) * (m.e2.z < 0 ? -1 : 1);
}
return TRUE;
}
#if !defined(_MSC_VER) && (defined(__WIN16__) || defined(__WIN32__))
extern "C" double acos(double d)
{
if(d < -1)
return M_PI;
else if(d > 1)
return 0;
else
return 0.5 * M_PI - asin(d);
}
#endif
| true |
8f27fddfb293ea5e2f7557b0f59bcee91da39e7e | C++ | renyajie/Learning | /Algorithm/基础/数据结构/kmp/kmp.cpp | GB18030 | 431 | 2.890625 | 3 | [] | no_license | // s[]dzıp[]ģʽnsijȣmpij
// ע±궼1ʼ, ne[1] = 0;
// next
for(int i = 2, j = 0; i <= m; i++) {
while(j && p[i] != p[j + 1]) j = ne[j];
if(p[i] == p[j + 1]) j++;
ne[i] = j;
}
// ƥ
for(int i = 1, j = 0; i <= n; i++) {
while(j && s[i] != p[j + 1]) j = ne[j];
if(s[i] == p[j + 1]) j++;
if(j == m) {
j = ne[j];
// ƥɹ
}
}
| true |
21e1cfd5cfeb418dd19acf0d10d2ed3bdb7917a6 | C++ | cpptt-book/2nd | /08_type_erasure/03_shared_ptr_implementation.cpp | UTF-8 | 1,733 | 3.53125 | 4 | [
"CC0-1.0"
] | permissive | // Copyright (c) 2014
// Akira Takahashi, Fumiki Fukuda.
// Released under the CC0 1.0 Universal license.
class shared_deleter_base {
public:
shared_deleter_base() {}
virtual ~shared_deleter_base() {}
virtual void destroy() = 0;
};
template <class T, class D>
class shared_deleter : public shared_deleter_base {
T* object_;
D deleter_;
public:
shared_deleter(T* object, D deleter)
: object_(object), deleter_(deleter) {}
virtual void destroy()
{
deleter_(object_);
}
};
template <class T>
class shared_ptr {
T* object_; // ポインタ
shared_deleter_base* deleter_; // カスタム削除子
public:
// カスタム削除子を使用しないコンストラクタ
explicit shared_ptr(T* object) : object_(object), deleter_(0) {}
// カスタム削除子を使用するコンストラクタ
template <class D>
shared_ptr(T* object, D deleter) : object_(object)
{
deleter_ = new shared_deleter<T, D>(object_, deleter);
}
~shared_ptr()
{
// カスタム削除子が指定されていたらそれを実行
if (deleter_) {
deleter_->destroy();
delete deleter_;
}
// カスタム削除子が指定されていなかったらdelete
else {
delete object_;
}
}
T* operator->() const { return object_; }
};
#include <iostream>
using namespace std;
struct hoge {
hoge() { cout << "コンストラクタ" << endl; }
~hoge() { cout << "デストラクタ" << endl; }
void something() const { cout << "何かする" << endl; }
};
void delete_hoge(hoge* p)
{
delete p;
cout << "削除子を使用して解放" << endl;
}
void foo()
{
shared_ptr<hoge> p(new hoge(), &delete_hoge);
p->something();
}
int main()
{
foo();
}
| true |
e22fe4d799f59b4190014d4b574b6ca491d1cf3e | C++ | dbmartinez/Starting-Out-With-C-plus-plus | /CH.4/PC4.cpp | UTF-8 | 1,161 | 4.34375 | 4 | [] | no_license | // Areas of Rectangles
// Libraries needed
#include<iostream>
using namespace std;
// Main function
int main()
{
// Variables
int length1,
width1,
length2,
width2,
area1,
area2;
// Description
cout << "\nEnter in length and width for 2 rectangles, when done ";
cout << "entering in length, press enter to input width.\n\n";
// User input for rectangle1
cout << "Enter in length and width for rectangle 1: ";
cin >> length1 >> width1;
// User input for rectangle2
cout << "Enter in length and width for rectangle 2: ";
cin >> length2 >> width2;
// Calculations
area1 = length1 * width1;
area2 = length2 * width2;
// Which rectangle has the greater area or area is the same
if(area1 > area2)
{
cout << "\nRectangle 1(" << area1 << ") is greater than rectangle 2(";
cout << area2 << ")\n";
}
else if(area2 > area1)
{
cout << "\nRectangle 2(" << area2 << ") is greater than rectangle 1(";
cout << area1 << ")\n";
}
else if(area1 == area2)
{
cout << "\nRectangle 1(" << area1 << ") is equal to rectangle 2(";
cout << area2 << ")\n";
}
return 0;
}
| true |
17ba16c8d3673f4b72b31746c94b90eef2f9bfd0 | C++ | bpgabin/gl-golf | /VoidEngine/VoidEngine/ThirdPersonCamera.cpp | UTF-8 | 1,647 | 3.078125 | 3 | [
"MIT"
] | permissive | #include "ThirdPersonCamera.hpp"
#include <iostream>
ThirdPersonCamera::ThirdPersonCamera(GolfBall* golfBall) : Camera(perspective)
{
mGolfBall = golfBall;
mOffset = mGolfBall->getPosition() ;
radius = 2.0f;
}
void ThirdPersonCamera::handleMouseMovement(float x, float y)
{
glm::vec3 worldCoordinates;
//glm::vec3 direction = mTarget - mPosition;
float theta = (float)((x / 180) * 3.14);
float phi = (float)((y / 180) * 3.14);
glm::vec3 spherical = cartesianToSpherical(mOffset);
spherical.y = spherical.y - theta;
spherical.z = spherical.z + phi;
spherical.x = radius;
mOffset = sphericalToCartesian(spherical);
}
void ThirdPersonCamera::handleKeyboard(char input, float deltaTime)
{
if (input == 'w')
{
mPosition -= glm::normalize(mUp) * mSpeed;
mTarget -= glm::normalize(mUp) * mSpeed;
}
else if (input == 's')
{
mPosition += glm::normalize(mUp) * mSpeed;
mTarget += glm::normalize(mUp) * mSpeed;
}
else if (input == 'a')
{
glm::vec3 forwardDirection = mTarget - mPosition;
glm::vec3 direction = glm::cross(forwardDirection, mUp);
mPosition += glm::normalize(direction) * mSpeed;
mTarget += glm::normalize(direction) * mSpeed;
}
else if (input == 'd')
{
glm::vec3 forwardDirection = mTarget - mPosition;
glm::vec3 direction = glm::cross(forwardDirection, mUp);
mPosition -= glm::normalize(direction) * mSpeed;
mTarget -= glm::normalize(direction) * mSpeed;
}
}
void ThirdPersonCamera::setSpeed(float speed)
{
mSpeed = speed;
}
void ThirdPersonCamera::updateCamera(float deltaTime)
{
mPosition = mGolfBall->getPosition() + mOffset;
mTarget = mGolfBall->getPosition();
} | true |
538e390f8c59dfdaa751e15d3bf7718fec3968f4 | C++ | OptimalAlgorithm/algo-study | /2020-02-13 2주차/종범/보물섬.cpp | UTF-8 | 1,255 | 2.5625 | 3 | [] | no_license | // https://www.acmicpc.net/problem/2589
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
const int MAX = 50;
int N, M, ans;
char MAP[MAX][MAX];
bool check[MAX][MAX];
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
int bfs(int sx, int sy) {
queue<pair<pair<int, int>, int>> q;
q.push(make_pair(make_pair(sx, sy), 0));
check[sx][sy] = true;
int ret = 0;
while (!q.empty()) {
int x = q.front().first.first;
int y = q.front().first.second;
int cnt = q.front().second;
q.pop();
ret = max(ret, cnt);
for (int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if (nx < 0 || nx >= N || ny < 0 || ny >= M || check[nx][ny]) continue;
if (MAP[nx][ny] == 'L') {
q.push(make_pair(make_pair(nx, ny), cnt + 1));
check[nx][ny] = true;
}
}
}
return ret;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> N >> M;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
cin >> MAP[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (MAP[i][j] == 'L') {
ans = max(ans, bfs(i, j));
memset(check, false, sizeof(check));
}
}
}
cout << ans << '\n';
return 0;
} | true |
f1c967a4ca82f2c181c12bccea6d575fd49e3c12 | C++ | grigorypalchun/Server | /main.cpp | UTF-8 | 2,604 | 2.90625 | 3 | [] | no_license | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <iostream>
#include <fcntl.h>
#include <string.h>
#include <vector>
using namespace std;
int sendall(int s, char *buf, int len, int flags)
{
int total = 0;
int n;
while(total < len)
{
n = send(s, buf+total, len-total, flags);
if(n == -1) { break; }
total += n;
}
return (n==-1 ? -1 : total);
}
int recvall(int s, char *buf, int len, int flags)
{
int total = 0;
int n;
while(total < len)
{
n = recv(s, buf+total, len-total, flags);
if(n == -1) { break; }
total += n;
}
return (n==-1 ? -1 : total);
}
int main()
{
cout << "Server \n";
int udp,tcp,sock;
struct sockaddr_in addr_u, addr_t;
int bytes_read;
udp = socket(AF_INET, SOCK_DGRAM, 0);
tcp = socket(AF_INET, SOCK_STREAM, 0);
fcntl(tcp, F_SETFL, O_NONBLOCK);
fcntl(udp, F_SETFL, O_NONBLOCK);
if(tcp < 0)
{
perror("socket");
return 0;
}
if(udp < 0)
{
perror("socket");
return 0;
}
addr_u.sin_family = AF_INET;
addr_u.sin_port = htons(3425);
addr_u.sin_addr.s_addr = htonl(INADDR_ANY);
addr_t.sin_family = AF_INET;
addr_t.sin_port = htons(3450);
addr_t.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(udp, (struct sockaddr *)&addr_u, sizeof(addr_u)) < 0)
{
perror("bind");
return 0;
}
if(bind(tcp, (struct sockaddr *)&addr_t, sizeof(addr_t)) < 0)
{
perror("bind");
return 0;
}
listen(tcp, 1);
while(1)
{
char buf[1050];
vector <int> nums;
bytes_read = 0;
bytes_read = recvall(udp, buf, 1024, 0);
if (bytes_read > 0)
{
cout << buf << '\n';
cout << bytes_read;
buf[bytes_read] = '\n';
// sendto(udp,buf,1024,0, (struct sockaddr *)&addr_u, sizeof(addr_u));
}
sock = accept(tcp, NULL, NULL);
if(sock > 0)
while (1)
{
bytes_read = recvall(sock, buf, 1024, 0);
if (bytes_read <= 0) break;
cout << buf;
}
for (int i = 0; i < bytes_read; i++)
if (buf[i] >= '0' && buf[i] <= '9')
nums.push_back(buf[i]);
if (nums.size() > 0)
{
cout << "Numbers are : \n";
cout << nums.size();
for (int i = 0; i < nums.size(); i++)
cout << nums[i] - '0' << ' ';
}
nums.clear();
}
return 0;
}
| true |
549ac283417262d80a4d7d07ce0ab8cb5c236973 | C++ | jennyaoym/chess | /piece.h | UTF-8 | 666 | 2.90625 | 3 | [] | no_license | #ifndef PIECE_H
#define PIECE_H
#include <string>
class Square;
class Checkerboard;
class Piece {
protected:
std::string colour;
int value;
Square *sq;
char name;
Checkerboard *cb;
public:
Piece(std::string colour, Square *sq, Checkerboard *cb);
virtual ~Piece();
virtual char getname() const = 0;
virtual bool can_move(Square *move) = 0;
virtual int getValue() const = 0;
virtual void move_to(Square *move);
virtual void undo() {}
std::string getcolour();
void setsquare(Square* sq);
Square* getsquare();
virtual bool hasmoved() const;
virtual void castling_move(Square *move);
virtual void restore() {return; }
};
#endif
| true |
295256c5c916c635f9e3f81fed531e0447ccaa64 | C++ | rafaelapure82/C-Parte-2 | /matricula de honor.cpp | UTF-8 | 768 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(void)
{
int nota;
cout << "Introduzca una calificacion numerica entre 0 y 10:";
cin >> nota;
cout << "La calificacion del alumno es" << endl;
if (nota == 10)
{
cout << "Matricula de Honor" << endl;
}
else if (nota >= 9)
{
cout << "Sobresaliente" << endl;
}
else if (nota >= 7)
{
cout << "Notable" << endl;
}
else if (nota >= 5)
{
cout << "Aprobado" << endl;
}
else
{
cout << "Reprobado" << endl;
}
system("pause");
}
| true |
46c306364b04ccc5948c2d28bf1003aba9a4a951 | C++ | ferreiracaf/POO | /Gerenciador de Oficina Mecânica/Código/cliente.cpp | UTF-8 | 1,888 | 3.078125 | 3 | [] | no_license | #include "cliente.h"
string Cliente::getTelefone() const
{
return telefone;
}
void Cliente::setTelefone(const string &value)
{
telefone = value;
}
string Cliente::toString() const{
stringstream ss;
ss << nome << ", tel: " << telefone << endl << "Veiculos:" << endl;
for(Automovel * aut : veiculos)
ss << aut->toString() << endl;
ss << "----------";
return ss.str();
}
bool Cliente::addAuto(Automovel *aut){
for(Automovel * a : veiculos)
if(a->getPlaca() == aut->getPlaca())
return false;
veiculos.push_back(aut);
aut->cliente = this;
return true;
}
bool Cliente::rmAuto(string placa){
for(int i = 0; i < (int) veiculos.size(); i++)
if(veiculos[i]->getPlaca() == placa){
veiculos.erase(veiculos.begin() + i);
return true;
}
return false;
}
Automovel *Cliente::getAuto(string placa){
for(Automovel * a : veiculos)
if(a->getPlaca() == placa)
return a;
return nullptr;
}
string Cliente::showAuto() const{
stringstream ss;
for (Automovel * a : veiculos)
ss << a->toString() << endl << "----------" << endl;
return ss.str();
}
void Cliente::rmAllVeiculos(){
int tam = veiculos.size();
for(int i = 0; i < tam; i++){
veiculos.erase(veiculos.begin());
}
}
Cliente::Cliente(string nome, string telefone):
telefone(telefone)
{
this->nome = nome;
}
string Cliente::getNome() const
{
return nome;
}
void Cliente::setNome(const string &value)
{
nome = value;
}
ClienteComum::ClienteComum(string nome, string telefone):
Cliente(nome, telefone)
{}
CLIENTE ClienteComum::getTipo(){
return COMUM;
}
ClienteVip::ClienteVip(string nome, string telefone):
Cliente(nome, telefone)
{}
CLIENTE ClienteVip::getTipo(){
return VIP;
}
| true |
067d54dcb37a28a6e4bd06719303c92df63a22eb | C++ | BackupTheBerlios/robotm6 | /robot2005/src/devices/simu/motorSimu.cpp | ISO-8859-1 | 1,388 | 2.765625 | 3 | [] | no_license | #include "implementation/motorSimu.h"
#include "log.h"
#include "simulatorClient.h"
// ============================================================================
// ============================== class MotorSimu ==========================
// ============================================================================
/** Reset les hctl (gauche et droite) */
bool MotorSimu::reset()
{
LOG_FUNCTION();
MotorCL::reset();
return true;
}
/** Defini la constante d'acceleration des moteurs */
void MotorSimu::setAcceleration(MotorAcceleration acceleration)
{
}
/** Specifie un consigne en vitesse pour les moteurs */
void MotorSimu::setSpeed(MotorSpeed left,
MotorSpeed right)
{
LOG_DEBUG("set speed(%d, %d)\n", (int)left, (int)right);
Simulator->setSpeed(left, right);
}
/** Retourne la position des codeurs */
void MotorSimu::getPosition(MotorPosition &left,
MotorPosition &right)
{
Simulator->getMotorPosition(left, right);
}
/** Retourne la consigne reellement envoyee au moteurs */
void MotorSimu::getPWM(MotorPWM &left,
MotorPWM &right)
{
Simulator->getPwm(left, right);
}
/** desasserrvit les moteurs */
void MotorSimu::idle()
{
}
MotorSimu::MotorSimu(bool automaticReset,
MotorAlertFunction fn) :
MotorCL(automaticReset, fn)
{
LOG_FUNCTION();
reset();
LOG_OK("Initialisation termine\n");
}
| true |
546ee4f0e9d52ce1671a6d21405cc24b6963ccfa | C++ | JacobMiske/PaintBot | /StepperMotor.ino | UTF-8 | 1,783 | 2.84375 | 3 | [] | no_license | #include <Stepper.h>
const int ledPin = 8;
Stepper upStepper1(360, 0, 1, 2, 3);
Stepper upStepper2(360, 0, 1, 2, 3);
Stepper horizontalStepper(360, 0, 1, 2, 3);
Stepper motionStepperLeft(360, 0, 1, 2, 3);
Stepper motionStepperRight(360, 0, 1, 2, 3);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
upStepper1.setSpeed(60);
upStepper2.setSpeed(60);
horizontalStepper.setSpeed(60);
motionStepperLeft.setSpeed(60);
motionStepperRight.setSpeed(60);
}
char buffer[255];
void rotate() {
stepper.step(200);
delay(5000);
stepper.step(0);
}
void blink() {
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
}
// Helper This is for the 90 degree turned gears
void driveStep90(x, y, SteppMotor, Speed){
// Diameter is 25mm
Radius
}
// Helper This is for the straight on gears
void driveStepStraight(x, y, SteppMotor, Speed){
// Diameter is 40mm
Radius = 20
}
int i = 0;
void loop() {
if(Serial.available() > 0) {
char c = Serial.read();
if(c == '\n') {
buffer[i] = '\0';
String message(buffer);
if(message == "BLINK") {
blink();
} else if(message == "MOVE_FORWARD") {
move_forward();
} else if(message == "MOVE_BACKWARD") {
move_backward();
} else if(message == "MOVE_BAC") {
move_backward();
}
i = 0;
} else {
buffer[i] = c;
i++;
}
}
int buttonState = digitalRead(buttonPin);
if(buttonState != lastButtonState) {
if(buttonState == LOW) {
Serial.println("Message1");
}
lastButtonState = buttonState;
}
}
| true |
83382a03b13c5f5e0fe0748b3ef9466d63b9608c | C++ | freshie9098/DynamicProgramming | /4.Palindromic Subsequence/2.Count Palindromic Subsequences.cpp | UTF-8 | 1,043 | 2.859375 | 3 | [] | no_license | // Count Palindromic Subsequences
// I/P: abcd O/P: 4
#include <bits/stdc++.h>
using namespace std;
// Recursive
int cntPS(string s, int i, int j) {
if (i == j)return 1;
if (i > j)return 0;
if (s[i] == s[j])return 1 + cntPS(s, i, j - 1) + cntPS(s, i + 1, j);
return cntPS(s, i, j - 1) + cntPS(s, i + 1, j) - cntPS(s, i + 1, j - 1);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
string s; cin >> s;
int n = s.length();
// Bottom up: T.C: O(N*N) A.S: O(N*N)
int dp[n + 1][n + 1];
memset(dp, 0, sizeof dp);
// filling diagonal
for (int i = 0; i < n; ++i)dp[i][i] = 1;
for (int k = 2; k <= n; ++k) {
for (int i = 0; i <= n - k; ++i) {
int j = k + i - 1;
if (s[i] == s[j]) dp[i][j] = 1 + dp[i + 1][j] + dp[i][j - 1];
else dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1];
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cout << dp[i][j] << " ";
}
cout << '\n';
}
cout << dp[0][n - 1] << '\n';
return 0;
} | true |
54b783d0a47efc58881d77bd5b8f5b39dfbdc3d4 | C++ | jcjolley/school | /objectOriented/lectures/section4/skeet/skeet.cpp | UTF-8 | 5,831 | 3.15625 | 3 | [] | no_license | /***********************************************************************
* Program:
* Skeet. Play the wonderful Skeet game using OpenGL
* Author:
* Br. Grimmett
* Summary:
***********************************************************************/
#include "point.h" // Objects have a position
#include "vector.h" // Objects have a vector
#include "gameEntities.h" // The Ball, Bird, Bullet, and Rifle Classes
#include "uiInteract.h" // interface with OpenGL
#include "uiDraw.h" // all the draw primitives exist here
#include <iostream> // Used only for debugging
using namespace std;
// set the bounds of the game
float Point::xMin = -128.0;
float Point::xMax = 128.0;
float Point::yMin = -128.0;
float Point::yMax = 128.0;
// Set the Number of bullets available
#define NUM_BULLETS 5
// Set the size of the Bird
#define BIRD_SIZE 20
/*****************************************
* Skeet - Here the class descriptor
****************************************/
class Skeet
{
public:
Skeet(); // set up the game
void draw(); // draw everything
void interact(const Interface *pUi); // Handle the key presses
void advance(); // Advance the game
private:
Bird bird; // The Bird class
Bullet bullets[NUM_BULLETS]; // The Bullet class
Rifle rifle; // The Rifle class
int hit; // Holds the score of hits
int missed; // Holds the score of misses
};
/***************************************************
* Skeet:: CONSTRUCTOR
* Set the hit and misses to 0
* Randomly set the x position of the bird
* Randomly set the y speed of the bird
***************************************************/
Skeet::Skeet()
{
hit = 0;
missed = 0;
bird.setX(bird.getXMin() + 1.0);
bird.setDx(4.0);
bird.setDy((float)random(-2, 2));
};
/********************************************
* Skeet :: ADVANCE
* Move all the objects forward
*******************************************/
void Skeet::advance()
{
// advance the bullets if they are alive
for (int i = 0; i < NUM_BULLETS; i++)
if (!bullets[i].isDead())
bullets[i].advance();
// if the bird is dead, resurrect the bird at some random time
if (bird.isDead())
{
if (0 == (random(0, 30)))
bird.regenerate();
}
else
{
// advance the bird
if (bird.advance())
{
// Add one to score, because the bird just went off the screen
missed++;
}
}
// check to see if the bullet struck the bird, as long as the bird is alive
if (!bird.isDead())
for (int i = 0; i < NUM_BULLETS; i++)
{
// Make sure the bullet is alive, then make sure the position
// of the bullet and bird are within the bird's size
if (!bullets[i].isDead())
if ((BIRD_SIZE > abs((bullets[i].getX() - bird.getX()))) &&
(BIRD_SIZE > abs((bullets[i].getY() - bird.getY()))))
{
// Kill the bird, and the bullet.
bird.kill();
bullets[i].kill();
i = NUM_BULLETS;
// Add one to the score
hit++;
}
}
}
/**************************************************
* Skeet : Interact
* Send the key presses to the right objects
*************************************************/
void Skeet::interact(const Interface *pUI)
{
// move the rifle
rifle.move(pUI->isUp() + pUI->isRight(),
pUI->isDown() + pUI->isLeft());
// shoot a bullet
if (pUI->isSpace())
{
// Space bar pressed, so start up a bullet, if one is available(dead)
for (int i = 0; i < NUM_BULLETS; i++)
if (bullets[i].isDead())
{
// Fire the bullet, sending the current angle of the rifle
bullets[i].fire(rifle.getAngle());
i = NUM_BULLETS;
}
}
}
/*************************************************
* Skeet : DRAW
* Draw all the objects that need to be drawn
************************************************/
void Skeet::draw()
{
// draw the rifle
rifle.draw();
// draw the bird
bird.draw();
// draw the bullets if they are alive
for (int i = 0; i < NUM_BULLETS; i++)
if (!bullets[i].isDead())
bullets[i].draw();
// put the score on the screen
static const Point point;
Point pointHit(point.getXMin() + 2, point.getYMax() - 2);
Point pointMiss(point.getXMax() - 30, point.getYMax() - 2);
drawNumber(pointHit, hit);
drawNumber(pointMiss, missed);
}
/*********************************************
* CALLBACK
* The main interaction loop of the engine.
* This gets called from OpenGL. It give us our
* interface pointer (where we get our events from)
* as well as a void pointer which we know is our
* game class.
*********************************************/
void callBack(const Interface *pUI, void *p)
{
// we know the void pointer is our game class so
// cast it into the game class.
Skeet *pSkeet = (Skeet *)p;
// Send the key presses to the interact function
pSkeet->interact(pUI);
// Advance all the objects that might move or change state
pSkeet->advance();
// draw all the objects that need to be drawn
pSkeet->draw();
}
/*********************************
* MAIN
* initialize the drawing window, initialize
* the game,and run it!
*********************************/
int main(int argc, char **argv)
{
// Start the drawing
Interface ui(argc, argv, "Skeet");
// play the game. Our function callback will get called periodically
Skeet skeet;
ui.run(callBack, (void *)&skeet);
return 0;
}
| true |
8de3fe6e577c867cfc712213182027d7a05fadc0 | C++ | kamyu104/LeetCode-Solutions | /C++/find-two-non-overlapping-sub-arrays-each-with-target-sum.cpp | UTF-8 | 882 | 2.859375 | 3 | [
"MIT"
] | permissive | // Time: O(n)
// Space: O(n)
class Solution {
public:
int minSumOfLengths(vector<int>& arr, int target) {
unordered_map<int, int> prefix = {{0, -1}};
vector<int> dp(arr.size());
int result = numeric_limits<int>::max(), min_len = numeric_limits<int>::max();
int accu = 0;
for (int right = 0; right < arr.size(); ++right) {
accu += arr[right];
prefix[accu] = right;
if (prefix.count(accu - target)) {
auto left = prefix[accu - target];
min_len = min(min_len, right - left);
if (left != -1 && dp[left] != numeric_limits<int>::max()) {
result = min(result, dp[left] + (right - left));
}
}
dp[right] = min_len;
}
return result != numeric_limits<int>::max() ? result : -1;
}
};
| true |
c59e1a257d6547db1d286de5b0184b2a9cb9f383 | C++ | zohairajmal/competitive-programming-problems | /leet-stickers-to-spell-word/test.cpp | UTF-8 | 2,100 | 3.015625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
class Solution {
vector<string> stickers;
string target;
int n;
vector<int> dp;
int finalState;
int minStickers(int state){
int& ret = dp[state];
if(ret == -1){
if(state == finalState){
ret = 0;
} else {
for(auto sticker : stickers){
int now = state;
for(auto letter : sticker){
for(int i = 0; i < n; i++){
if(((now >> i) & 1) == 1) continue;
if(letter == target[i]){
now |= (1 << i);
break;
}
}
}
if(now != state){
int alt = minStickers(now) + 1;
if(ret == -1 || ret > alt){
ret = alt;
}
}
}
}
}
return ret;
}
bool check(){
vector<int> vis(26, 0);
for(auto sticker : stickers){
for(auto letter : sticker){
vis[letter-'a']++;
}
}
for(auto letter : target){
if(!vis[letter-'a']){
return false;
}
}
return true;
}
public:
int minStickers(vector<string>& stickers, string target) {
this->stickers = stickers;
this->target = target;
n = target.length();
if(!check()){
return -1;
}
finalState = (1 << n)-1;
dp.resize((1 << n), -1);
return minStickers(0);
}
};
int main(){
int n;
cin >> n;
vector<string> stickers(n);
for(int i = 0; i < n; i++){
cin >> stickers[i];
}
string target;
cin >> target;
Solution sol;
cout << sol.minStickers(stickers, target);
return 0;
} | true |
1608e88a36e3f39ecdd86098cfd7c6096b34959d | C++ | quangh33/Coding-Interview-Practice | /Leetcode/adhoc/hash table/243.shortest-word-distance.cpp | UTF-8 | 398 | 2.859375 | 3 | [] | no_license | class Solution {
public:
int shortestDistance(vector<string>& words, string word1, string word2) {
unordered_map<string, int> pos;
int i = -1;
int res = words.size();
for(string w: words) {
pos[w] = ++i;
if (w == word1 && pos.count(word2) != 0) res = min(res, i - pos[word2]);
if (w == word2 && pos.count(word1) != 0) res = min(res, i - pos[word1]);
}
return res;
}
};
| true |
767ca15ac1f61c164041f431e8b64b3e662b823b | C++ | fthiebolt/neOCampus-arduino | /neosensor/libraries/M5Unit-RELAY/examples/Unit_2RELAY_M5Core/Unit_2RELAY_M5Core.ino | UTF-8 | 1,543 | 2.625 | 3 | [
"MIT"
] | permissive | /*
*******************************************************************************
* Copyright (c) 2022 by M5Stack
* Equipped with M5Core sample source code
* 配套 M5Core 示例源代码
* Visit for more information: https://docs.m5stack.com/en/unit/2relay
* 获取更多资料请访问: https://docs.m5stack.com/zh_CN/unit/2relay
*
* Product: 2Relay. 两路继电器
* Date: 2022/8/16
*******************************************************************************
Please connect to Port A(21,22),Use RELAY to switch on and off the circuit.
请连接端口A(21,22),使用继电器开关电路。
*/
#include <M5Stack.h>
void setup() {
M5.begin(); // Init M5Stack. 初始化M5Stack
M5.Power.begin(); // Init power 初始化电源模块
M5.Lcd.setTextSize(2); // Set the text size to 2. 设置文字大小为2
M5.Lcd.setCursor(85, 0);
M5.Lcd.println(("Relay Example"));
dacWrite(25, 0); // disable the speak noise. 禁用喇叭
pinMode(21, OUTPUT); // Set pin 21 to output mode. 设置21号引脚为输出模式
pinMode(22, OUTPUT); // Set pin 22 to output mode. 设置22号引脚为输出模式
}
void loop(void) {
M5.Lcd.setCursor(135, 40);
M5.Lcd.print("ON");
digitalWrite(21, HIGH);
digitalWrite(22, HIGH);
delay(1000);
M5.Lcd.fillRect(135, 40, 60, 50, BLACK);
M5.Lcd.print("OFF");
digitalWrite(21, LOW);
digitalWrite(22, LOW);
delay(1000);
M5.Lcd.fillRect(135, 40, 60, 50, BLACK);
} | true |
aca97bff8bd3669f8378b0cfd2fae303dc4f73d1 | C++ | Nickqiaoo/trigger | /invite_module.cc | UTF-8 | 1,671 | 2.765625 | 3 | [] | no_license | #include "invite_module.h"
#include <string>
InviteModule::InviteModule(){
num_to_code_map_={{0,'0'},{1,'1'},{2,'2'},{3,'3'},{4,'4'},{5,'5'},{6,'6'},{7,'7'},{8,'8'},{9,'9'},{10,'a'},
{11,'b'},{12,'c'},{13,'d'},{14,'e'},{15,'f'},{16,'g'},{17,'h'},{18,'i'},{19,'j'},{20,'k'},
{21,'l'},{22,'m'},{23,'n'},{24,'o'},{25,'p'},{26,'q'},{27,'r'},{28,'s'},{29,'t'},{30,'u'},
{31,'v'},{32,'w'},{33,'x'},{34,'y'},{35,'z'},{36,'A'},{37,'B'},{38,'C'},{39,'D'},{40,'E'},
{41,'F'},{42,'G'},{43,'H'},{44,'I'},{45,'J'},{46,'K'},{47,'L'},{48,'M'},{49,'N'},{50,'O'},
{51,'P'},{52,'Q'},{53,'R'},{54,'S'},{55,'T'},{56,'U'},{57,'V'},{58,'W'},{59,'X'},{60,'Y'},{61,'Z'},
};
for(auto it = num_to_code_map_.begin(); it != num_to_code_map_.end(); it++){
code_to_num_map_[it->second] = it->first;
}
}
InviteModule::~InviteModule(){}
std::string InviteModule::convertRoleIdToCode(int64_t roleId){
std::string roleIdStr = std::to_string(roleId);
std::reverse(roleIdStr.begin(),roleIdStr.end());
roleId = atoll(roleIdStr.c_str()) << 18;
std::string code;
do{
code.insert(code.begin(), num_to_code_map_[roleId % 62]);
roleId = roleId / 62;
}while(roleId != 0);
return code;
}
int64_t InviteModule::convertCodeToRoleId(std::string inviteCode){
int k = 0;
int64_t roleId = 0;
for(auto it = inviteCode.rbegin(); it!=inviteCode.rend(); it++){
roleId += code_to_num_map_[(*it)] * pow(62, k);
k++;
}
roleId = roleId>>18;
std::string roleIdStr = std::to_string(roleId);
std::reverse(roleIdStr.begin(),roleIdStr.end());
roleId = atoll(roleIdStr.c_str());
return roleId;
}
| true |
846e951fed1109dde84cb7672c907c11161649c7 | C++ | locolocoer/mycode | /Game-Programming-Using-Qt-5-Beginners-Guide-Second-Edition-master/Chapter08/Custom Widgets/chess/ver2/chessview.cpp | UTF-8 | 481 | 2.515625 | 3 | [
"MIT"
] | permissive | #include "chessview.h"
#include "chessboard.h"
ChessView::ChessView(QWidget *parent) : QWidget(parent)
{
}
void ChessView::setBoard(ChessBoard *board)
{
if(m_board == board) return;
if(m_board) {
// disconnect all signal-slot connections between m_board and this
m_board->disconnect(this);
}
m_board = board;
// connect signals (to be done later)
updateGeometry();
}
ChessBoard *ChessView::ChessView::board() const { return m_board; }
| true |
c37e34ce6185a4b25cbefc7fdf23a9847e2f038f | C++ | Yiluhuakai22/algorigthm-study | /LeetCode_C++/435_eraseOverlapIntervals/solution.h | UTF-8 | 691 | 3 | 3 | [
"MIT"
] | permissive | #include <vector>
#include <algorithm>
using std::vector;
class Solution
{
public:
int eraseOverlapIntervals(vector<vector<int>> &intervals)
{
if (intervals.empty())
{
return 0;
}
sort(intervals.begin(), intervals.end(), [](vector<int> a, vector<int> b)
{ return a[1] < b[1]; });
int n = intervals.size();
int total = 0, prev = intervals[0][1];
for (int i = 1; i < n; ++i)
{
if (intervals[i][0] < prev)
{
++total;
}
else
{
prev = intervals[i][1];
}
}
return total;
}
}; | true |
372fcecdb02d5a6ef32c9bc24a673244a19a208d | C++ | gajdosech2/scan-filtering | /HIROVisualizer/HIRO/include/HIRO_DRAW/ElementRenderer.h | UTF-8 | 5,994 | 2.515625 | 3 | [] | no_license | /*
Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
Unauthorized copying of this file, via any medium is strictly prohibited
Proprietary and confidential
*/
#ifndef HIRO_DRAW_ELEMENT_RENDERER_H
#define HIRO_DRAW_ELEMENT_RENDERER_H
#include <GLW/Texture.h>
#include <GLW/UniformBuffer.h>
#include <HIRO_DRAW/Renderer.h>
#include <HIRO_DRAW/ShaderApi.h>
namespace hiro::draw
{
//! Available sources of color information.
enum class ColorSource : int32_t
{
material = 0, //!< Color is taken from the material.
positions = 1, //!< Raw 3D positions are used to represent colors.
normals = 2, //!< Raw 3D normals are used to represent colors.
custom = 3, //! Vertex color attribute used to get colors.
normals_n = 4, //!< 3D normals mapped to the visible color range.
checkerboard = 5, //!< Checkerboard texture used to get colors.
albedo_texture = 6 //!< Albedo texture used to get colors.
};
//! Point rendering stylization.
struct PointsStyle
{
//! Material setting for the points.
hiro::shader::Material material;
//! When enabled, points with normal vector turned away from the camera are hidden.
bool back_face_culling = false;
//! Size of point in screen pixels.
float point_size = 10.0f;
//! Color source used to colorize the points.
hiro::draw::ColorSource color_source = hiro::draw::ColorSource::material;
};
//! Face rendering stylization.
struct FacesStyle
{
//! Available sources of normal vector.
enum class NormalSource
{
flat_normals = 0, //!< Normals are calculated from face orientations.
point_normals = 1, //!< Per vertex normals are used. Requires normal attribute for vertices.
normal_texture = 2 //!< Normals are picked from the normal texture. Requires normal texture.
};
//! When enabled, faces with flat normal vector turned away from the camera are hidden.
bool back_face_culling = false;
//! When enabled, only face edges are rendered.
bool wireframe = false;
//! Material setting for the faces.
hiro::shader::Material material;
//! Color source used to colorize the faces.
hiro::draw::ColorSource color_source = hiro::draw::ColorSource::material;
//! Albedo texture. To use, set color source to ColorSource::albedo_map.
glw::PTexture2D albedo_texture = nullptr;
//! Normal source used to calculate the lighting.
hiro::draw::FacesStyle::NormalSource normal_source = hiro::draw::FacesStyle::NormalSource::flat_normals;
//! Normal texture. To use, set normal source to NormalSource::normal_map.
glw::PTexture2D normal_texture = nullptr;
//! When enabled, color and lighting is picked from matcap sampler texture.
bool use_matcap = false;
//! Matcap sampler. Used only when matcap rendering is enabled.
glw::PTexture2D matcap_sampler = nullptr;
};
//! Normal vector rendering stylization.
struct NormalsStyle
{
//! Color of the normal vector tip.
cogs::Color3f color = cogs::color::BLACK;
//! Length of the normal vector.
float length = 0.1f;
};
/*!
\brief Base class for rendering of geometry data.
If you wish to specify your rendering override desired "OnRender" method and render inside it.
Your own method for point rendering can be implemented something like this:
\code{.cpp}
void hiro::draw::GeometryRenderer::OnRenderPoints()
{
const auto style = GetStyle<GeometryStyle>();
if (style->render_mode == GeometryStyle::RenderMode::points
|| style->render_mode == GeometryStyle::RenderMode::wired_points)
{
PointsStyle ps;
ps.back_face_culling = style->back_face_culling;
ps.color_source = style->color_source;
ps.material = style->material;
ps.point_size = style->point_size;
vao_->Bind();
RenderPoints(ps, [&]() { vao_->DrawVertices(glw::DrawMode::points); });
vao_->Unbind();
}
}
\endcode
*/
class HIRO_DRAW_API ElementRenderer : public hiro::draw::Renderer
{
public:
ElementRenderer(const hiro::draw::ElementRenderer &source) = delete;
ElementRenderer &operator=(const hiro::draw::ElementRenderer &source) = delete;
ElementRenderer(hiro::draw::ElementRenderer &&) noexcept = delete;
ElementRenderer &operator=(hiro::draw::ElementRenderer &&) noexcept = delete;
virtual ~ElementRenderer() = default;
protected:
//! Protected constructor, since this class should serve only as a base class.
ElementRenderer();
//! Loads shader programs required by this renderer.
void LoadRequiredShaderPrograms(glw::ProgramList *programs) override;
//! Specifies what happens during render.
void Render(const std::string &program) override;
//! Override if you wish to render points. Use the method RenderPoints to actually render.
virtual void OnRenderPoints();
//! Override if you wish to render faces. Use the method RenderFaces to actually render.
virtual void OnRenderFaces();
//! Override if you wish to render normals. Use the method RenderNormals to actually render.
virtual void OnRenderNormals();
//! Prepares shader according to the style and renders points using the specified render_func.
void RenderPoints(const hiro::draw::PointsStyle &style, std::function<void(void)> render_func);
//! Prepares shader according to the style and renders faces using the specified render_func.
void RenderFaces(const hiro::draw::FacesStyle &style, std::function<void(void)> render_func);
//! Prepares shader according to the style and renders normals using the specified render_func.
void RenderNormals(const hiro::draw::NormalsStyle &style, std::function<void(void)> render_func);
private:
//! Uniform buffer containing material information.
glw::UniformBuffer<hiro::shader::Material> material_ubo_;
};
}
#endif /* !HIRO_DRAW_ELEMENT_RENDERER_H */ | true |
79f18012e93aa939ea57137a8112d2f32d2a1c30 | C++ | hurou927/atcoder | /cpp/header/my_util.hpp | UTF-8 | 1,535 | 2.765625 | 3 | [] | no_license | #ifndef _MY_UTIL_HPP_
#define _MY_UTIL_HPP_
#define ALL(a) (a).begin(),(a).end()
#define EACH(i,c) for(auto i=(c).begin(); i!=(c).end(); ++i)
#define EXIST(s,e) ((s).find(e)!=(s).end())
#define SORT(c) sort((c).begin(),(c).end())
#define RSORT(c) sort((c).rbegin(),(c).rend())
#define MAXINDEX(c) distance((c).begin(),max_element((c).begin(),(c).end()))
#define MININDEX(c) distance((c).begin(),min_element((c).begin(),(c).end()))
#define DEBUG(x) std::cerr <<#x<<" = "<<(x)<<" ("<<__FILE__<<"::"<<__LINE__<<")"<<std::endl;
#define ERROR(s) std::cerr <<"Error::"<<__FILE__<<"::"<<__LINE__<<"::"<<__FUNCTION__<<"::"<<(s)<<std::endl;
#define FOR(i,a,b) for (auto i=(a);i<(b);i++)
#define RFOR(i,a,b) for (int i=(b)-1;i>=(a);i--)
inline unsigned char *read_binary(char *filename,unsigned int *size){
FILE *fp;
if((fp = fopen(filename , "rb" ))==NULL){
fprintf(stderr,"fopen FAILURE\n");
exit(1);
}
fseek( fp, 0, SEEK_END );
*size = ftell( fp );
fseek( fp, 0, SEEK_SET );
unsigned char *str=(unsigned char *)malloc(*size);
int temp=fread(str,1,*size,fp);
fclose(fp);
return str;
}
inline unsigned char *read_ascii(char *filename,unsigned int *size){
FILE *fp;
if((fp = fopen(filename , "r" ))==NULL){
fprintf(stderr,"fopen FAILURE\n");
exit(1);
}
fseek( fp, 0, SEEK_END );
*size = ftell( fp );
fseek( fp, 0, SEEK_SET );
unsigned char *str=(unsigned char *)malloc(*size);
int temp=fread(str,1,*size,fp);
fclose(fp);
return str;
}
#endif
| true |
32b7b1a799db2f1ae551ab0a79b46d4ff7d355a4 | C++ | ZzzandyzzZ/Problemas-UVA | /732 - Anagrams by Stack.cpp | UTF-8 | 957 | 3.203125 | 3 | [] | no_license | //732 - Anagrams by Stack
#include <bits/stdc++.h>
using namespace std;
string w1,w2;
int size;
stack<char> pil;
void secuencias(char op,int i,int o,string cad,stack<char> pila,string se){
//cout<<i<<" "<<o<<" "<<cad<<endl;
if(i>size||o>size||o>i)return;
//if(op=='o'&&pila.empty())return;
if(op=='i'){
pila.push(w1[i-1]);
}
else{
cad+=pila.top();
pila.pop();
if(w2.substr(0,o)!=cad){
return;
}
}
if(cad.size()==size&&cad==w2){
//cout<<cad<<endl;
cout<<se<<endl;
return;
}
secuencias('i',i+1,o,cad,pila,se+" i");
secuencias('o',i,o+1,cad,pila,se+" o");
}
int main(){
while(cin>>w1){
cin>>w2;
size=w1.size();
cout<<"["<<endl;
if(size==w2.size())
secuencias('i',1,0,"",pil,"i");
cout<<"]"<<endl;
}
} | true |
c48a46b16006d84ef59b282e998fd55793ee3850 | C++ | ahuertaalberca/C-Plus-Plus | /Homework/HW6/newproverb-1-exercise-3.cpp | UTF-8 | 1,732 | 4.21875 | 4 | [
"MIT"
] | permissive | // This program will allow the user to input from the keyboard
// whether the last word to the following proverb should be party or country:
// "Now is the time for all good men to come to the aid of their _______"
// The user will input a word to finish the sentence.
// JESUS HILARIO HERNANDEZ
#include <iostream>
#include <string>
using namespace std;
// Fill in the prototype of the function writeProverb.
string writeProverb(string);
int main ()
{
string word;
cout << "Given the phrase:" << endl;
cout << "Now is the time for all good men to come to the aid of their ___" << endl;
cout << "Input a 1 if you want the sentence to be finished with party" << endl;
cout << "Input any other number for the word country" << endl;
cout << "Please input your choice now" << endl;
cin >> word;
cout << endl;
writeProverb(word);
cout << endl << endl;
return 0;
}
// ******************************************************************************
// writeProverb
//
// task: This function prints a proverb. The function takes a string
// from the user. The word the user provides is used to
// end the proverb. "Now is the time for all good men to come
// men to come to the aid of their _(user input)_" will be
// printed to screen
// data in: code for ending word of proverb (string)
// data out: none
//
// *****************************************************************************
string writeProverb (string endword)
{
// Fill in the body of the function to accomplish what is described above
cout << "Now is the time for all good men "
<< "to come to the aid of their " << endword << endl;
return endword;
}
| true |
f5593516fcce4f8cfb068b59a43655732611d6ee | C++ | shishirkumar1996/cp | /algos_and_data_structures/algo/fft.cpp | UTF-8 | 1,386 | 3.09375 | 3 | [] | no_license | #include<bits/stdc++.h>
#define cd complex< double >
#define vcd vector< cd >
using namespace std;
vcd fft(vcd a){
int n= a.size();
if(n==1)return vcd(1,a[0]);
vcd w(n); // for storing n complex nth roots of unity
for(int i=0;i<n;i++){
double alpha = 2*M_PI*i/n;
w[i] = cd(cos(alpha),sin(alpha));
}
vcd A0(n/2),A1(n/2);
for(int i=0;i<n/2;i++){A0[i] = a[i*2];A1[i] = a[i*2+1];}
vcd y0 = fft(A0); //even indexed coefficients
vcd y1 = fft(A1); //odd indexed coefficients
vcd y(n);
for(int k=0;k<n/2;k++){
y[k] = y0[k]+w[k]*y1[k];
y[k+n/2] = y0[k]-w[k]*y1[k];
}
return y;
}
vcd inv_fft(vcd a){
int n= a.size();
if(n==1)return vcd(1,a[0]);
vcd w(n); // for storing n complex nth roots of unity
for(int i=0;i<n;i++){
double alpha = 2*M_PI*i/n;
w[i] = conj(cd(cos(alpha),sin(alpha)));
}
vcd A0(n/2),A1(n/2);
for(int i=0;i<n/2;i++){A0[i] = a[i*2];A1[i] = a[i*2+1];}
vcd y0 = inv_fft(A0); //even indexed coefficients
vcd y1 = inv_fft(A1); //odd indexed coefficients
vcd y(n);
for(int k=0;k<n/2;k++){
y[k] = (y0[k]+w[k]*y1[k])*(1.0/n);
y[k+n/2] = (y0[k]-w[k]*y1[k])*(1.0/n);
}
return y;
}
int main(){
vcd a{1,2,3,4};// 4*x^4+3*x^2+2*x+1
vcd b = fft(a);
for(int i=0;i<4;i++) cout<<b[i]<<endl;
vcd c = inv_fft(b);
for(int i=0;i<4;i++)cout<<c[i]<<endl;
return 0;
}
| true |
cfaaeec06c63fb28f82f9a77ee1b61c2cf4d39d5 | C++ | Hugo2121/Mind | /cmpt419/Proj/hanz/data_prep/index_extract/ExtractImages.cpp | UTF-8 | 3,267 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include "string_helper.h"
#include "gnt_helper.h"
#ifdef WIN32
#else
#include <sys/stat.h>
#endif
using namespace std;
map<unsigned int, vector<GNTSampleInfo>> ReadGNTInfoFile(string info_name) {
FILE* bin_file = fopen(info_name.c_str(), "rb");
int count = 0;
map<unsigned int, vector<GNTSampleInfo>> hanzImageMap;
while (!feof(bin_file)) {
int c = getc(bin_file);
if (c == EOF) {
break;
}
ungetc(c, bin_file);
GNTSampleInfo info(bin_file);
if (hanzImageMap.find(info.code) == hanzImageMap.end()) {
// Key not found
/*if (info_file.index == 1246990) {
cout << "Builded" << endl;
}*/
hanzImageMap[info.code] = {};
}
hanzImageMap[info.code].push_back(info);
count++;
//cout<<"pro:"<<count<<endl;
}
fclose(bin_file);
return hanzImageMap;
}
void MakeDir(const char* dir) {
#ifdef WIN32
CreateDirectoryA(dir, nullptr);
#else
mkdir(dir, 0700);
#endif
}
void ExtractFromCode(map<unsigned int, vector<GNTSampleInfo>> gnt_info_dict, uint32_t code, float trainPercent=1.0) {
vector<GNTSampleInfo> sampleList = gnt_info_dict[code];
int seperationPos = trainPercent*sampleList.size();
for (int i = 0; i < seperationPos; i++) {
GNT sample(sampleList[i].file_name, sampleList[i].image_offset);
string bmp_name = to_string(sampleList[i].index) + "_" + to_string(sampleList[i].image_offset) + ".bmp";
string dirName = "out/train/" + to_string(code);
MakeDir(dirName.c_str());
sample.save_BMP_file(dirName + "/" + bmp_name);
}
for (int i = seperationPos; i < sampleList.size(); i++) {
GNT sample(sampleList[i].file_name, sampleList[i].image_offset);
string bmp_name = to_string(sampleList[i].index) + "_" + to_string(sampleList[i].image_offset) + ".bmp";
string dirName = "out/validation/" + to_string(code);
MakeDir(dirName.c_str());
sample.save_BMP_file(dirName + "/" + bmp_name);
}
/*for (auto& info : gnt_info_dict[code]) {
GNT sample(info.file_name, info.image_offset);
string bmp_name = to_string(info.index) + "_" + to_string(info.image_offset) + ".bmp";
string dirName = "out/" + to_string(code);
MakeDir(dirName.c_str());
sample.save_BMP_file(dirName + "/" + bmp_name);
}*/
}
int main(int argn, char* argv[]) {
//Z:\Project\hanz\1.0train-gb1.gnt.txt
//char* path= "Z:/Project/hanz/1.0train-gb1.gnt.bin";
//char* path = "f2.gnt.bin";
map<unsigned int, vector<GNTSampleInfo>> gnt_info_dict = ReadGNTInfoFile(argv[1]);
cout << "Loaded " << gnt_info_dict.size() << " characters, enter character codes(seperate by comma)." << endl;
string codesLine;
cin >> codesLine;
MakeDir("out");
MakeDir("out/train");
MakeDir("out/validation");
vector<string> codes = split(codesLine, ',');
for (string & codeStr : codes) {
uint32_t code = stoi(codeStr);
if (codeStr.find("-") != string::npos) {
vector<string> codePair = split(codeStr,'-');
int start = stoi(codePair[0]);
int end = stoi(codePair[1]);
for (int i = start; i != end; end > start ? i++ : i--) {
ExtractFromCode(gnt_info_dict, i, 0.8);
}
}
else {
ExtractFromCode(gnt_info_dict, code, 0.8);
}
}
//map<unsigned int, vector<GNTSampleInfo>> gnt_info_dict = ReadGNTInfoFile(path);
return 0;
}
| true |
d67e378d08352c1771546f46e7e69538311d4a3b | C++ | winterthediplomat/Parallel-Road-Rage | /RoadRage/solver.cpp | UTF-8 | 1,803 | 2.734375 | 3 | [] | no_license | //#include "StdAfx.h"
#include <iostream>
#include "solver.h"
using namespace std;
Solver::Solver()
{
this->acceptConstraints=new QVector<Constraint*>;
this->rejectConstraints=new QVector<Constraint*>;
}
/*
void Solver::getSolutions(Path startSolution, QVector<Path> *solutions)
{
QMessage::critical(this, "D:", "D:");
}
*/
bool Solver::rejectSolution(Path candidate)
{
bool isRejected=false;
//#pragma omp parallel for
for(int i=0; i<this->rejectConstraints->size(); i++)
{
//this->rejectConstraints->at(i)->printName();
if(!this->rejectConstraints->at(i)->isRespected(candidate))
{
//cout<<"not respected constraint at "<<i<<"th position!"<<endl;
isRejected=true;
}
}
return isRejected;
}
bool Solver::acceptSolution(Path candidate)
{
/*
//original version: it's an EPIC FAIL
//it just does not control about *ALL* the
//constraint validation, but only ONE constraint.
//It's just wondering: there is _at least one_ constraint
//that says "this solution, in my opinion, is right" ?
bool isAccepted=false;
for(int i=0; i<this->acceptConstraints->size(); i++)
{
if(this->acceptConstraints->at(i)->isRespected(candidate))
isAccepted=true;
}
return isAccepted;
*/
unsigned int isAccepted=1;
for(int i=0; i<this->acceptConstraints->size(); i++)
{
if(!this->acceptConstraints->at(i)->isRespected(candidate))
{
isAccepted*=0;
}
}
return isAccepted==1;
}
void Solver::addAcceptConstraint(Constraint *newConstraint)
{this->acceptConstraints->push_back(newConstraint);}
void Solver::addRejectConstraint(Constraint *newConstraint)
{this->rejectConstraints->push_back(newConstraint);}
| true |
7f64a840e52c54e77b40244695159cef490335bb | C++ | prattmic/waldo | /io/linux_byteio.cc | UTF-8 | 1,556 | 2.84375 | 3 | [] | no_license | #include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <utility>
#include "external/nanopb/util/task/status.h"
#include "external/nanopb/util/task/statusor.h"
#include "io/linux_byteio.h"
using io::LinuxByteIO;
util::StatusOr<LinuxByteIO> LinuxByteIO::OpenFile(const char *filename) {
int fd = open(filename, O_RDWR|O_NONBLOCK);
if (fd < 0) {
return util::Status(util::error::Code::UNKNOWN, "open failed");
}
return LinuxByteIO(fd);
}
util::StatusOr<char> LinuxByteIO::Read() {
while (1) {
char c;
int n = read(fd_, &c, 1);
if (n < 0) {
if (errno == EINTR) {
continue;
} else if (errno == EAGAIN) {
return util::Status(util::error::Code::RESOURCE_EXHAUSTED,
"would block");
}
return util::Status(util::error::Code::UNKNOWN, "read failed");
} else if (n == 0) {
return util::Status(util::error::Code::RESOURCE_EXHAUSTED, "EOF");
}
return c;
}
}
util::Status LinuxByteIO::Write(char c) {
while (1) {
int n = write(fd_, &c, 1);
if (n < 0) {
if (errno == EINTR) {
continue;
} else if (errno == EAGAIN) {
return util::Status(util::error::Code::RESOURCE_EXHAUSTED,
"would block");
}
return util::Status(util::error::Code::UNKNOWN, "write failed");
}
return util::Status::OK;
}
}
| true |
d0f576b32a93b8b048281f757e6eb90f8c614637 | C++ | balvig/lifeboxes | /libraries/Sleep.cpp | UTF-8 | 1,484 | 2.921875 | 3 | [] | no_license | #include "Sleep.h"
namespace Lifeboxes {
const uint32_t RTC_SLEEP_COUNT_REGISTER = 65;
const uint32_t UPPER_LIMIT = 8760; // Arduino randomly decided to sleep for 2809417741 hours
Sleep::Sleep(uint32_t cyclesToSleep, uint64_t sleepingInterval) {
_defaultCyclesToSleep = cyclesToSleep;
_sleepingInterval = sleepingInterval;
}
bool Sleep::isTimeToWakeUp() {
_updateCyclesRemaining();
if(cyclesRemaining <= 0 || cyclesRemaining > UPPER_LIMIT) {
resetCyclesRemaining(_defaultCyclesToSleep);
return true;
}
else {
return false;
}
}
void Sleep::resetCyclesRemaining(uint32_t newValue) {
cyclesRemaining = newValue;
}
void Sleep::goToSleep() {
Serial.println("writing cycles");
_writeCyclesRemaining();
Serial.println("Sleeping");
ESP.deepSleep(_sleepingInterval);
}
// Private
bool Sleep::_wasResetFromSleepUp() {
const uint8_t reason = ESP.getResetInfoPtr()->reason;
return reason == 6;
}
void Sleep::_updateCyclesRemaining() {
if(_wasResetFromSleepUp()) {
resetCyclesRemaining(_defaultCyclesToSleep);
}
else {
_readCyclesRemaining();
cyclesRemaining--;
}
}
void Sleep::_readCyclesRemaining() {
system_rtc_mem_read(RTC_SLEEP_COUNT_REGISTER, &cyclesRemaining, sizeof(cyclesRemaining));
}
void Sleep::_writeCyclesRemaining() {
system_rtc_mem_write(RTC_SLEEP_COUNT_REGISTER, &cyclesRemaining, sizeof(cyclesRemaining));
}
}
| true |
3599807ce68a7ce37a7459fc4087cbf4e7177a15 | C++ | AJnad/CIS-22A-C-- | /Assignment 10/rockpaperscissors.cpp | UTF-8 | 1,914 | 3.453125 | 3 | [] | no_license | /**
* Ajay Nadhavajhala
* CIS 22A 9:30-11:20 AM M/W
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
string player1, player2, choice1, choice2;
cout << "Let's play Rock-Paper-Scissors!" << endl;
cout << "Player one, please enter your name: ";
cin >> player1;
cout << "Player two, please enter your name: ";
cin >> player2;
cout << "" << player1 << ", please enter \"Rock\", \"Paper\" or \"Scissors\": ";
cin >> choice1;
cout << "" << player2 << ", please enter \"Rock\", \"Paper\" or \"Scissors\": ";
cin >> choice2;
if(choice1 == "Rock" && choice2 == "Paper")
{
cout << "Paper beats Rock." << endl;
cout << player2 << " wins!" << endl;
}
else if (choice1 == "Rock" && choice2 == "Rock")
cout << "It's a tie!" << endl;
else if (choice1 == "Rock" && choice2 == "Scissors")
{
cout << "Rock beats Scissors." << endl;
cout << player1 << " wins!" << endl;
}
else if(choice1 == "Paper" && choice2 == "Scissors")
{
cout << "Scissors beats Paper." << endl;
cout << player2 << " wins!" << endl;
}
else if (choice1 == "Paper" && choice2 == "Paper")
cout << "It's a tie!" << endl;
else if (choice1 == "Paper" && choice2 == "Rock")
{
cout << "Paper beats Rocks." << endl;
cout << player1 << " wins!" << endl;
}
else if(choice1 == "Scissors" && choice2 == "Rock")
{
cout << "Rock beats Scissors." << endl;
cout << player2 << " wins!" << endl;
}
else if (choice1 == "Scissors" && choice2 == "Scissors")
cout << "It's a tie!" << endl;
else if (choice1 == "Scissors" && choice2 == "Paper")
{
cout << "Scissors beats Paper." << endl;
cout << player1 << " wins!" << endl;
}
}
| true |
d1e15613c32cf9eb17917141689504c1503bdaef | C++ | langmead-lab/vargas | /include/scoring.h | UTF-8 | 3,585 | 2.59375 | 3 | [
"MIT"
] | permissive | /**
* Ravi Gaddipati
* Jan 10, 2016
* rgaddip1@jhu.edu
*
* @brief
* Program CL parsing and scoring structs.
*
* @copyright
* Distributed under the MIT Software License.
* See accompanying LICENSE or https://opensource.org/licenses/MIT
*
* @file
*/
#ifndef VARGAS_SCORING_H
#define VARGAS_SCORING_H
#include "utils.h"
#include <vector>
#include <cstdint>
#include <cmath>
#include <cstdio>
#include <string>
#include <sstream>
#include <stdexcept>
namespace vargas {
/*
* @brief
* Marks a forward strand or a reverse complement strand
*/
enum class Strand {FWD, REV};
using rg::pos_t;
using target_t = std::pair<Strand, pos_t>;
/**
* @brief
* Aligner scoring parameters
*/
struct ScoreProfile {
ScoreProfile() = default;
/**
* @param match Match bonus
* @param mismatch Mismatch penalty
* @param gopen Read and ref gap open penalty
* @param gext Read and ref gap extension penalty
*/
ScoreProfile(uint8_t match, uint8_t mismatch, uint8_t gopen, uint8_t gext) :
match(match), mismatch_min(mismatch), mismatch_max(mismatch),
read_gopen(gopen), read_gext(gext), ref_gopen(gopen), ref_gext(gext), ambig(0) {}
/**
* @param match Match bonus
* @param mismatch Mismatch penalty
* @param rd_gopen Read gap open penalty
* @param rd_gext Read gap extension penalty
* @param ref_gopen Ref gap open penalty
* @param ref_gext Ref gap extension penalty
*/
ScoreProfile(unsigned match, unsigned mismatch,
unsigned rd_gopen, unsigned rd_gext,
unsigned ref_gopen, unsigned ref_gext) :
match(match), mismatch_min(mismatch), mismatch_max(mismatch),
read_gopen(rd_gopen), read_gext(rd_gext), ref_gopen(ref_gopen), ref_gext(ref_gext), ambig(0) {}
/**
* @brief
* Get a mismatch penalty from a quality value
* @param c phred value
* @return penalty
*/
unsigned penalty(char c) const {
return mismatch_min + std::floor( (mismatch_max-mismatch_min) * (std::min<float>(c, 40.0)/40.0));
}
unsigned
match = 2, /**< Match bonus */
mismatch_min = 2,
mismatch_max = 2, /**< Mismatch penalty */
read_gopen = 3, /**< Read gap open penalty */
read_gext = 1, /**< Read gap extension penalty */
ref_gopen = 3, /**< Ref gap open penalty */
ref_gext = 1, /**< Ref gap extension penalty */
ambig = 0; /**< Ambigious base penalty */
bool end_to_end = false; /**< End to end alignment */
std::string to_string() const;
};
/**
* @brief
* Aligner results
* 1 based coords.
*/
struct Results {
std::vector<pos_t> max_pos, sub_pos, max_last_pos, sub_last_pos, waiting_pos, waiting_last_pos;
std::vector<unsigned> max_count, sub_count;
std::vector<int> max_score; /**< Best scores */
std::vector<int> sub_score; /**< Second best scores */
std::vector<Strand> max_strand;
std::vector<Strand> sub_strand;
ScoreProfile profile;
size_t size() const {
return max_pos.size();
}
/**
* @brief
* Resize all result vectors.
*/
void resize(size_t size);
};
const std::vector<std::string> supported_pgid = {"bowtie2", "bwa", "hisat2"};
std::vector<std::string> tokenize_cl(std::string cl);
ScoreProfile bwt2(const std::string &cl);
ScoreProfile bwa_mem(const std::string &cl);
ScoreProfile program_profile(const std::string &cl);
}
#endif //VARGAS_SCORING_H
| true |
199a2e6dd241ce4c23046ed22fa68204381fd1ab | C++ | figoxu/CPPPraticse | /lang/ioteck/ioteck_course/chap5/private/main.cpp | UTF-8 | 450 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace::std;
class Animal{
public:
Animal() {}
void eat() const {cout << "eat" << endl;}
};
class Cat : public Animal
{
public:
Cat() {}
void maew() { cout << "maew" << endl; }
};
class Duck : private Animal
{
public:
Duck() {}
void stretchNeck() {cout << "stretch" << endl;}
};
void func(const Animal& animal)
{
animal.eat();
}
int main()
{
Cat kitty;
func(kitty);
Duck duck;
func(duck);
return 0;
}
| true |
26b5a6553028503c84d0ce980a2dc95d702c45d4 | C++ | jessiefrederick/UTN | /Laboratorio de Comp I/Trabajo Practico - 1/Ejercicio - 1.cpp | UTF-8 | 408 | 2.84375 | 3 | [] | no_license | //Nombre: Jessie Frederick
//TP Nº: 1
//EJ Nº: 1
//Comentarios:
#include<iostream>
using namespace std;
int main(void) {
int cantidadHorasTrabajadas;
int valorHora;
cout << "Ingresar cantidad de horas trabajadas: ";
cin >> cantidadHorasTrabajadas;
cout << "Ingresar valor hora de trabajo: ";
cin >> valorHora;
cout << "Sueldo: " << cantidadHorasTrabajadas * valorHora;
return 0;
}
| true |
21eb5a044e9e67644417a7cfdaa053b54a413c18 | C++ | AdityaChettri/cppProgram1 | /Assignment1.cpp | UTF-8 | 303 | 2.6875 | 3 | [] | no_license | /*Author:Aditya Chettri
DOC:17th November2020
Pattern Printing
*/
#include<iostream>
using namespace std;
int main()
{
for(int i=1;i<=7;i++)
{
for(int j=i;j<=7;j++)
{
cout<<j;
}
cout<<"\n";
}
for(int i=6;i>=1;i--)
{
for(int j=i;j<=7;j++)
{
cout<<j;
}
cout<<"\n";
}
return 0;
}
| true |
4ffbf9e898f2b8584ad21bd324591be90c024fc8 | C++ | ArttuHeinonen/oo2 | /Content.cpp | ISO-8859-1 | 588 | 2.515625 | 3 | [] | no_license | #include "Content.h"
Content* Content::content;
Content::Content(void) //ladataan sislt
{
//backgroundTex.loadFromFile("res/taivas.png");
if (!playerTex.loadFromFile("res/player.png")){
printf("Error: Player texture not found!\n");
}
if (!calibri.loadFromFile("res/calibri.ttf")){
printf("Error: font not found!\n");
}
}
Content::~Content(void)
{
}
sf::Texture Content::getPlayerTexture()
{
return this->playerTex;
}
sf::Font Content::getCalibriFont()
{
return this->calibri;
}
Content* Content::get()
{
if (!content)
content = new Content();
return content;
} | true |
b9d82b1df6aa77a969bd653e50587c28b990151f | C++ | jadkins89/CSCI2270_DataStructures | /Assignment_6/main.cpp | UTF-8 | 2,376 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include "MovieTree.hpp"
#include <fstream>
#include <sstream>
//Function Declarations
void printMenu();
void mainMenu(MovieTree &theTree);
int main(int argc, char* argv[]) {
MovieTree testTree;
char* filename = argv[1];
std::ifstream documentStream(filename, std::ios::in);
if (documentStream.fail()) {
return -1;
}
std::string currentLine;
while (getline(documentStream, currentLine)) {
std::stringstream ss(currentLine);
std::string lineArray[4];
int index = 0;
while (getline(ss, lineArray[index], ',')) {
index++;
}
int ranking = stoi(lineArray[0]);
std::string title = lineArray[1];
int releaseYear = stoi(lineArray[2]);
int quantity = stoi(lineArray[3]);
testTree.addMovieNode(ranking, title, releaseYear, quantity);
}
documentStream.close();
mainMenu(testTree);
return 0;
}
void printMenu() {
std::cout << "======Main Menu======" << std::endl;
std::cout << "1. Find a movie" << std::endl;
std::cout << "2. Rent a movie" << std::endl;
std::cout << "3. Print the inventory" << std::endl;
std::cout << "4. Delete a movie" << std::endl;
std::cout << "5. Count the movies" << std::endl;
std::cout << "6. Quit" << std::endl;
}
void mainMenu(MovieTree &theTree) {
std::string userInput;
do {
printMenu(); // Runs print menu function to display text to user
bool valid = false;
while (!valid) { // Checking validity of user input
getline(std::cin, userInput);
if (userInput.length() == 1 && userInput > "0" && userInput < "7") {
valid = true;
}
else {
std::cout << "Incorrect input. Please try again: " << std::endl;
}
}
if (userInput == "1") {
std::cout << "Enter title:" << std::endl;
std::string title;
getline(std::cin, title);
theTree.findMovie(title);
}
else if (userInput == "2") {
std::cout <<"Enter title:" << std::endl;
std::string title;
getline(std::cin, title);
theTree.rentMovie(title);
}
else if (userInput == "3") {
theTree.printMovieInventory();
}
else if (userInput == "4") {
std::cout << "Enter title:" << std::endl;
std::string title;
getline(std::cin, title);
theTree.deleteMovieNode(title);
}
else if (userInput == "5") {
std::cout << "Tree contains: " << theTree.countMovieNodes() << " movies." << std::endl;
}
}
while (userInput != "6");
std::cout << "Goodbye!" << std::endl;
} | true |
213bc331161bb1788db826f8df6f090f2e40cfc0 | C++ | XeCycle/cxxtest | /incompatible-reinterpret-warning.cc | UTF-8 | 213 | 2.59375 | 3 | [] | no_license | struct compat {
void* x;
};
struct incompat {
int a, b;
};
int main()
{
compat c;
incompat i;
(void) reinterpret_cast<void*&>(c); // good
(void) reinterpret_cast<void*&>(i); // warn
return 0;
}
| true |
423464ef511ec67bbae09fc0612d7efbada489e0 | C++ | Lenyeto/Realtime | /Lab_03_WB/build/vs2015/LogManager.h | UTF-8 | 734 | 2.703125 | 3 | [] | no_license |
#include <fstream>
#include <iostream>
#define LL_DEBUG 0x000001
#define LL_NORMAL 0x000010
#define LL_WARNING 0x000100
#define LL_ERROR 0x001000
#define LL_SCRIPT 0x010000
#define LL_ALL 0x011111
/*! The LogManager Prototype */
namespace ssuge {
class LogManager {
public:
/*! The Constructor Prototype */
LogManager(std::string name);
/*! The Deconstructor Prototype */
~LogManager();
/*! The log Prototype */
void log(std::string msg, unsigned int lvl = LL_NORMAL);
/*! The setLogMask Prototype */
void setLogMask(unsigned int lvl = LL_ALL);
private:
/*! The file that is opened for writing */
std::ofstream mFile;
/*! The log level that things are written to */
unsigned int mLogLevel;
};
} | true |
51407b10e64e05980c55cf09301989407b147551 | C++ | exvayn/CPP-Coding | /student's work/9. динамические структуры данных и модульное программирование/f3.cpp | UTF-8 | 191 | 3.015625 | 3 | [] | no_license | #include <iostream>
int f3(int *A, int i){
std::cout<<"\nSpisok: ";
if (i>=0)
for (int j=i;j>=0;j--)
std::cout<<A[j]<<" ";
else std::cout<<"empty";
std::cout<<"\n\n";
return (0);
} | true |
3d2fa00071d6c07eb6d8cc89f30f5414a8698fdb | C++ | vishwanath-ek/ProgrammingPractice | /C++/simple_programs/useOfStatic/tcpp_pg443_1.cpp | UTF-8 | 626 | 3.328125 | 3 | [] | no_license | #include <iostream>
using std::cout; using std::endl;
int
returnNextElement(int *arg = NULL){
static int *ptr = NULL;
if(arg){
ptr = arg;
if( *ptr == -1 ){
}
return *ptr;
}
ptr += 1;
if(*ptr == -1){
return (-65535);
}
return *ptr;
}
int
main(int argc, char **argv){
(void)argc;
(void)argv;
int a[]={1, 2, 0, 2, 111, -65532, -1, 0, 2, 4};
cout << returnNextElement(a) << endl;
int c = 0;
while(1){
cout << (c = returnNextElement()) << endl;
if(c == -65535){
break;
}
}
return 1;
}
| true |
218b6ad32ba8e286e73d968319dcbdb9f42e6cd1 | C++ | zhouliyfly/MyLeetCode | /39.h | GB18030 | 2,005 | 3.4375 | 3 | [] | no_license | #ifndef _39_H //ܺ
#define _39_H
#include <vector>
//֣ targetΪ鷳ࣩܶ
class Solution_39 {
public:
std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
if (candidates.empty())
return res;
std::vector<int> vec;
findcombinationSum(candidates, target, 0, vec);
return res;
}
private:
void findcombinationSum(std::vector<int>& candidates, int target, int index, std::vector<int>& vec) {
if (0 == target) {
res.push_back(vec);
return;
}
if (target < 0)
return;
for (size_t i = index; i != candidates.size(); ++i) {
vec.push_back(candidates[i]);
findcombinationSum(candidates, target - candidates[i], i, vec);
vec.pop_back();
}
}
// Լ֦
void findcombinationSum2(std::vector<int>& candidates, int target, int index, std::vector<int>& vec) {
if (0 == target) {
res.push_back(vec);
return;
}
if (target < 0)
return;
for (size_t i = index; i != candidates.size(); ++i) {
vec.push_back(candidates[i]);
findcombinationSum(candidates, target - candidates[i], i, vec);
vec.pop_back();
}
}
private:
std::vector<std::vector<int>> res;
};
// ֦
class Solution_39_2 {
public:
std::vector<std::vector<int>> combinationSum(std::vector<int>& candidates, int target) {
if (candidates.empty())
return res;
std::sort(candidates.begin(), candidates.end());
std::vector<int> vec;
findcombinationSum(candidates, target, 0, vec);
return res;
}
private:
void findcombinationSum(std::vector<int>& candidates, int target, int index, std::vector<int>& vec) {
if (0 == target) {
res.push_back(vec);
return;
}
for (size_t i = index; i != candidates.size(); ++i) {
if (target - candidates[i] < 0)
break;
vec.push_back(candidates[i]);
findcombinationSum(candidates, target - candidates[i], i, vec);
vec.pop_back();
}
}
private:
std::vector<std::vector<int>> res;
};
#endif // !_39_H
| true |
4276148d0d745151db19e02f80b013c9d1d6826e | C++ | dhoule/sketch_statusesupdate | /sketch_statusesupdate.ino | UTF-8 | 3,159 | 3.1875 | 3 | [] | no_license | /*
SendATweet
Demonstrates sending a tweet via a Twitter account using the Temboo Arduino Yun SDK.
This example code is in the public domain.
*/
#include <Bridge.h>
#include <Temboo.h>
#include "TembooAccount.h" // contains Temboo account information
#include "TwitterAccount.h"
/*** SUBSTITUTE YOUR VALUES BELOW: ***/
int numRuns = 1; // execution count, so this sketch doesn't run forever
int maxRuns = 1; // the max number of times the Twitter Update Choreo should run
unsigned long passed = 0; //Used to retweet after 30 minutes.
void setup() {
Bridge.begin();
Console.begin();
// for debugging, wait until a serial console is connected
delay(4000);
}
void loop()
{
unsigned long current = millis();
// only try to send the tweet if we haven't already sent it successfully OR 30 minutes has passed
if ( (numRuns <= maxRuns) || ((current - passed) >= 1800000) ) {
if((current - passed) >= 1800000){
passed = current;
numRuns = 1;
}
// define the text of the tweet we want to send. String(millis()) is used to create unique tweets.
String tweetText("Your message here " + String(millis()));
TembooChoreo StatusesUpdateChoreo;
// invoke the Temboo client
// NOTE that the client must be reinvoked, and repopulated with
// appropriate arguments, each time its run() method is called.
StatusesUpdateChoreo.begin();
// set Temboo account credentials
StatusesUpdateChoreo.setAccountName(TEMBOO_ACCOUNT);
StatusesUpdateChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
StatusesUpdateChoreo.setAppKey(TEMBOO_APP_KEY);
// identify the Temboo Library choreo to run (Twitter > Tweets > StatusesUpdate)
StatusesUpdateChoreo.setChoreo("/Library/Twitter/Tweets/StatusesUpdate");
// set the required choreo inputs
// see https://www.temboo.com/library/Library/Twitter/Tweets/StatusesUpdate/
// for complete details about the inputs for this Choreo
// add the Twitter account information
StatusesUpdateChoreo.addInput("AccessToken", TWITTER_ACCESS_TOKEN);
StatusesUpdateChoreo.addInput("AccessTokenSecret", TWITTER_ACCESS_TOKEN_SECRET);
StatusesUpdateChoreo.addInput("ConsumerKey", TWITTER_API_KEY);
StatusesUpdateChoreo.addInput("ConsumerSecret", TWITTER_API_SECRET);
// and the tweet we want to send
StatusesUpdateChoreo.addInput("StatusUpdate", tweetText);
// tell the Process to run and wait for the results. The
// return code (returnCode) will tell us whether the Temboo client
// was able to send our request to the Temboo servers
unsigned int returnCode = StatusesUpdateChoreo.run();
// a return code of zero (0) means everything worked
if (returnCode == 0) {
Console.println("Success! Tweet sent!");
numRuns++;
} else {
// a non-zero return code means there was an error
// read and print the error message
while (StatusesUpdateChoreo.available()) {
char c = StatusesUpdateChoreo.read();
Console.print(c);
}
}
StatusesUpdateChoreo.close();
// do nothing for the next 90 seconds
delay(50000);
}
}
| true |
92c917587de8f61dc67aabe24aa60821fc3a37b3 | C++ | bimomuhamadr/MONITOR_UDARA | /Test_MQ7.ino | UTF-8 | 862 | 3.046875 | 3 | [] | no_license | #define pinSensor 36 // mendefinisikan bahwa pin yang digunakan
// untuk membaca sensor adalah pin A0
void setup()
{
Serial.begin(9600);
}
long RL = 1000; // 1000 Ohm
long Ro = 830; // 830 ohm ( SILAHKAN DISESUAIKAN)
void loop()
{
int sensorvalue = analogRead(pinSensor); // membaca nilai ADC dari sensor
Serial.println(sensorvalue);
double VRL = sensorvalue * 3.3 / 4095; // mengubah nilai ADC ( 0 - 1023 ) menjadi nilai voltase ( 0 - 5.00 volt )
Serial.print("VRL : ");
Serial.print(VRL);
Serial.println(" volt");
double Rs = ( 3.3 * RL / VRL ) - RL;
Serial.print("Rs : ");
Serial.print(Rs);
Serial.println(" Ohm");
double ppm = 100 * pow(Rs / Ro, -1.53); // ppm = 100 * ((rs/ro)^-1.53);
Serial.print("CO : ");
Serial.print(ppm);
Serial.println(" ppm");
Serial.println();
delay(500);
}
| true |
b7c4e00edff601ef91bd9fbda9ea353f7b77d539 | C++ | sageslayers/CP | /AtCoder/ABC160/E.cpp | UTF-8 | 1,767 | 2.609375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std ;
int main () {
ios_base::sync_with_stdio;
cin.tie(0) ;
cout.tie(0) ;
int x , y , a, b , c ;
cin >> x >> y >> a >> b >> c ;
vector <int> red(a) ;
vector <int> blue(b);
vector <int> nocolor(c);
for ( int i = 0 ; i < a ; i ++ )
cin >> red[i] ;
for ( int i = 0 ; i < b ; i ++ )
cin >> blue[i] ;
for ( int i = 0 ; i < c ; i ++ )
cin >> nocolor[i] ;
red.begin() = red.begin();
blue.begin() = blue.begin();
nocolor.begin() = nocolor.begin();
sort(red.begin() , red.end() , greater<int>() );
sort(blue.begin(), blue.end(), greater<int>() );
sort(nocolor.begin() , nocolor.end() , greater<int>() ) ;
long long sum = 0 ;
while ( x > 0 || y > 0 ) {
int merah , biru, kosong ;
merah = biru = kosong = 0 ;
if ( x > 0 && red.size() > 0 )
merah = red[0] ;
if ( y > 0 && blue.size() > 0 )
biru = blue[0] ;
if ( nocolor.size() > 0 )
kosong = nocolor[0] ;
if ( x > 0 && y > 0 ) {
if(merah >= biru && merah >= kosong ) {
sum+= merah ;
x-- ;
red.erase(red.begin());
}
else if ( biru >= merah && biru >= kosong ) {
sum+= biru ;
y-- ;
blue.erase(blue.begin()) ;
}
else{
if (merah > biru ) {
biru-- ;
nocolor.erase(nocolor.begin());
}
}
}
else if ( x >0 && y == 0 ) {
if( merah > kosong ) {
sum+= merah;
red.erase(red.begin());
x-- ;
}
else {
sum+=kosong ;
nocolor.erase(nocolor.begin());
x-- ;
}
}
else if ( x == 0 && y > 0 ){
if ( biru > kosong ) {
sum+= biru ;
blue.erase(blue.begin());
y-- ;
}
else {
sum+= kosong ;
nocolor.erase(nocolor.begin());
y-- ;
}
}
}
cout << sum << endl ;
}
| true |
4097c46751482013eb734d377495c01b6f557e51 | C++ | andresfelipehenao/proyecto | /Estudiante.cpp | UTF-8 | 918 | 2.9375 | 3 | [] | no_license | #pragma once
#include "Estudiante.h"
Estudiante::Estudiante()
{
}
Estudiante::Estudiante(int identificador, string nombre, int telefono, int multa)
{
this->identificador=identificador;
this->nombre=nombre;
this->telefono=telefono;
this->multa=multa;
}
Estudiante::~Estudiante()
{
}
void Estudiante::daridentificador(int identificador)
{
this->identificador=identificador;
}
int Estudiante::obteneridentificador()
{
return identificador;
}
void Estudiante::darnombre(string nombre)
{
this->nombre=nombre;
}
string Estudiante::obtenernombre()
{
return nombre;
}
void Estudiante::dartelefono(int telefono)
{
this->telefono=telefono;
}
int Estudiante::obtenertelefono()
{
return telefono;
}
void Estudiante::darmulta(int multa)
{
this->multa=multa;
}
int Estudiante::obtenermulta()
{
return multa;
}
| true |
4922ffa4f89f82014992fb7d49dc92fc1d2a7650 | C++ | countryhu/algorithm | /now_coder/cracking_the_code_interview/9_recursion/8_countWays.cc | UTF-8 | 1,345 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <deque>
using namespace std;
/**
题目描述
有数量不限的硬币,币值为25分、10分、5分和1分,请编写代码计算n分有几种表示法。
给定一个int n,请返回n分有几种表示法。保证n小于等于100000,为了防止溢出,请将答案Mod 1000000007。
测试样例:
6
返回:
2
-------
题目分析
**/
class Coins {
public:
int countWays(int n) {
int coins[4] = {1,5,10,25};
int dp[100001] = {0};
dp[0]=1;
for(int i = 0; i < 4; i++) {
for(int j = coins[i]; j <= n; j++) {
dp[j] = (dp[j] + dp[j - coins[i]]) % 1000000007;
}
}
return dp[n];
}
};
int main() {
// 样例
{
Coins obj;
std::cout << "obj.countWays(6)=2:" << obj.countWays(6) << std::endl;
}
{
Coins obj;
std::cout << "obj.countWays(1)=1:" << obj.countWays(1) << std::endl;
}
{
Coins obj;
std::cout << "obj.countWays(100):" << obj.countWays(100) << std::endl;
}
{
Coins obj;
std::cout << "obj.countWays(1000):" << obj.countWays(1000) << std::endl;
}
{
Coins obj;
std::cout << "obj.countWays(10000):" << obj.countWays(10000) << std::endl;
}
{
Coins obj;
std::cout << "obj.countWays(100000):" << obj.countWays(100000) << std::endl;
}
return 0;
}
| true |
4bf8030857069bb3663708d9fe48433d48c72084 | C++ | guangmushikong/AirplaneView | /mypolygon.h | UTF-8 | 870 | 2.546875 | 3 | [] | no_license | #ifndef MYPOLYGON_H
#define MYPOLYGON_H
#include <QPolygonF>
#include <QPointF>
#include <QLineF>
class mypolygon
{
public:
mypolygon();
const QPolygonF getCore(){ return _core; }
void setCore(const QPolygonF& core){ _core = core; }
void optimizeCoord(QPointF _trans, double _scale);
private:
QPolygonF _core;
};
class MyLine
{
public:
MyLine();
const QLineF getCore(){ return _core; }
void setCore(const QLineF& core){ _core = core; }
void optimizeCoord(QPointF _trans, double _scale);
private:
QLineF _core;
};
class MyPointF
{
public:
MyPointF(qreal qx, qreal qy){ _core.setX(qx); _core.setY(qy); }
MyPointF(const QPointF& p){ _core = p; }
const QPointF& getCore(){ return _core; }
void setCore(const QPointF& core){ _core = core; }
void optimizeCoord(QPointF _trans, double _scale);
private:
QPointF _core;
};
#endif // MYPOLYGON_H
| true |
edbb7271cdbd24bc27043ff5ca6c1b811292223e | C++ | herumi/misc | /slow_sin.cpp | UTF-8 | 751 | 2.78125 | 3 | [] | no_license | /*
cl /EHsc /Ox /Ob2 /fp:fast /Zi slow_sin.cpp
cl /EHsc /Ox /Ob2 /fp:fast /arch:AVX /Feslow_sin_avx.exe /Zi slow_sin.cpp
Core i7-2600 3.4GHz / Windows 7 Ultimate
VS2012(x64) VS2013(x64)
slow_sin 1.33 1.34
slow_sin_avx 1.33 6.27
*/
#include <stdio.h>
#include <math.h>
#include <time.h>
struct A {
float a[8];
A()
{
const float x = log(2.0f);
for (int i = 0; i < 8; i++) {
a[i] = x;
}
}
};
const A a;
int main()
{
double (*f)(double) = sin;
double begin = clock();
double x = 1.0;
double y = 0;
x = 1;
y = 0;
for (int i = 0; i < 100000000; i++) {
y += f(x);
x += 1e-6;
}
double end = clock();
printf("x=%f, %.2fsec\n", x, (end - begin) /double(CLOCKS_PER_SEC));
}
| true |
d3c0d5dd09129ebb7ac24fcd7545416831943caa | C++ | WelsonP/sorceryGame | /concreteminion.h | UTF-8 | 688 | 2.609375 | 3 | [] | no_license | #ifndef __CONCRETEMINION__
#define __CONCRETEMINION__
#include "minion.h"
class ConcreteMinion final: public Minion {
public:
/* void attack(int dmg) override;
void attack(int, int) override;
void getAttacked() override;
void die() override;*/
// TODO const, param names
//void notify(Subject &whoFrom) override;
ConcreteMinion(std::string name, int cost, int atk, int def, int action);
//How do we construct minions, we need some way of giving them their effects
// maybe we should have a text file for list of all possible cards/minions, and effects as well, then iterate
// through to add effects? for now only simple params
// do we need big 5?
};
#endif
| true |
f56ce1a8732363c708821e779870b65f4c46dd15 | C++ | vaaleyard/coding4fun | /Algar/CodePit/soma_fat.cpp | UTF-8 | 927 | 3.21875 | 3 | [] | no_license | /*
*
* Leia dois valores inteiros M e N indefinidamente. A cada leitura, calcule e escreva a soma dos fatoriais de cada um dos valores lidos. Utilize uma variável apropriada, pois cálculo pode resultar em um * valor com mais de 15 dígitos.
*
* Entrada
* O arquivo de entrada contém vários casos de teste. Cada caso contém dois números inteiros M (0 ≤ M ≤ 20) e N (0 ≤ N ≤ 20). O fim da entrada é determinado por eof.
*
* Saída
* Para cada caso de teste de entrada, seu programa deve imprimir uma única linha, contendo um número que é a soma de ambos os fatoriais (de M e N).
*/
#include <bits/stdc++.h>
using namespace std;
long long int fat(long long int res){
if(res == 0)
return 1;
return res * fat(res - 1);
}
int main(){
int input1, input2;
long long int res = 0;
while(cin >> input1 >> input2){
res= fat(input1) + fat(input2);
cout << res << endl;
}
return 0;
}
| true |
3b1104cb3f38602818178cc6ded8d2f403a23138 | C++ | ArtSin/OOP_Task4 | /ElectricalCircuitCalculator.cpp | UTF-8 | 18,515 | 2.703125 | 3 | [] | no_license | #include <QQueue>
#include "ElectricalCircuitCalculator.h"
#include "ElectricalElementsManager.h"
// Нахождение лидера компоненты в СНМ
QPoint ElectricalCircuitCalculator::dsuLeader(QPoint u)
{
// Нахождение лидера с эвристикой сжатия путей
return (dsuParent[u] == u) ? u : (dsuParent[u] = dsuLeader(dsuParent[u]));
}
// Объединение двух компонент в СНМ
void ElectricalCircuitCalculator::dsuUnite(QPoint u, QPoint v)
{
// Нахождение лидеров компонент
u = dsuLeader(u);
v = dsuLeader(v);
// Если это одна и та же компонента, то не нужно объединять
if (u == v)
return;
// Добавление меньшей к большей
if (dsuCompSz[u] > dsuCompSz[v])
std::swap(u, v);
dsuParent[u] = v;
dsuCompSz[v] += dsuCompSz[u];
}
// Нахождение вершин схемы
bool ElectricalCircuitCalculator::findNodesAndElements(QString& error)
{
// Очищение СНМ
dsuParent.clear();
dsuCompSz.clear();
// Очищение компонент
nodesCount = 0;
compLeader.clear();
compByLeader.clear();
// Очищение элементов и источников напряжения и тока
elements.clear();
voltageSources.clear();
currentSources.clear();
// Очищение потенциалов и токов через источники напряжения
nodesPotential.clear();
voltageSourcesCurrents.clear();
// Каждой точке сетки сопоставляются элементы, подключённые к ней
QMap<QPoint, QVector<ElectricalElement*>> allPoints;
for (int orient = 0; orient < 2; orient++) // 2 ориентации
for (auto el : ElectricalElementsManager::getInstance().getElements()[orient]) // Все элементы с данной ориентацией
for (auto p : el->getEndPoints()) // Все крайние точки элемента
allPoints[p].push_back(el);
// Инициализация СНМ
for (auto it = allPoints.cbegin(); it != allPoints.cend(); it++) // Все используемые точки сетки
{
dsuParent[it.key()] = it.key();
dsuCompSz[it.key()] = 1;
}
// Объединение точек сетки, образующих компоненты связности (по проводам и замкнутым выключателям)
for (auto it = allPoints.cbegin(); it != allPoints.cend(); it++)
for (auto el : it.value()) // Все элементы в данной точке
if (el->getResistance() == 0.0 && dynamic_cast<VoltageSource*>(el) == nullptr) // Элемент - провод или замкнутый выключатель
for (auto p : el->getEndPoints()) // Все крайние точки провода
if (p != it.key()) // Объединение со второй точкой провода
dsuUnite(it.key(), p);
// Нахождение компонент по точкам-лидерам и наоборот
for (auto it = allPoints.cbegin(); it != allPoints.cend(); it++) // Все используемые точки сетки
if (dsuLeader(it.key()) == it.key()) // Если точка и есть лидер своей компоненты
{
compByLeader[it.key()] = compLeader.size();
compLeader.push_back(it.key());
}
nodesCount = compLeader.size();
// Заполнение информации о вершинах схемы
for (auto it = allPoints.cbegin(); it != allPoints.cend(); it++) // Все используемые точки сетки
for (auto el : it.value()) // Все элементы в данной точке
{
// Провода и выключатели не рассматриваются
if ((el->getResistance() == 0.0 && dynamic_cast<VoltageSource*>(el) == nullptr) ||
(std::isinf(el->getResistance()) && dynamic_cast<CurrentSource*>(el) == nullptr))
continue;
// Крайние точки элемента
auto endPoints = el->getEndPoints();
QPoint firstPoint = endPoints[0], secondPoint = endPoints[1];
// Если элемент подключён обеими точками к одной вершине схемы
if (dsuLeader(firstPoint) == dsuLeader(secondPoint))
{
error = QString(u8"Элемент замкнут проводником!");
return false;
}
// Элемент - источник напряжения (рассмотрение один раз)
auto vs = dynamic_cast<VoltageSource*>(el);
if (it.key() == firstPoint && vs != nullptr)
{
// Добавление фиктивной вершины, если не идеальный источник (источник напряжения можно
// представить как идеальный и. н. и резистор внутреннего сопротивления, подключённый последовательно)
int midNode = -1;
if (vs->getResistance() != 0.0)
{
midNode = nodesCount;
nodesCount++;
}
// Добавление источника напряжения и вершин, к которым он подключён, в список
voltageSources.append(QPair<VoltageSource*, std::tuple<int, int, int>>(vs, std::tuple<int, int, int>
(compByLeader[dsuLeader(firstPoint)], midNode, compByLeader[dsuLeader(secondPoint)])));
continue;
}
// Элемент - источник тока (рассмотрение один раз)
auto cs = dynamic_cast<CurrentSource*>(el);
if (it.key() == firstPoint && cs != nullptr)
{
// Добавление источника тока и вершин, к которым он подключён, в список
currentSources.append(QPair<CurrentSource*, QPair<int, int>>(cs, QPair<int, int>
(compByLeader[dsuLeader(firstPoint)], compByLeader[dsuLeader(secondPoint)])));
continue;
}
// Добавление элемента и вершин, к которым он подключён, в список (один раз)
if (it.key() == firstPoint)
elements.append(QPair<ElectricalElement*, QPair<int, int>>(el, QPair<int, int>
(compByLeader[dsuLeader(firstPoint)], compByLeader[dsuLeader(secondPoint)])));
}
return true;
}
// Нахождение напряжений и токов
bool ElectricalCircuitCalculator::findVoltagesAndCurrents(QString& error)
{
// Нахождение напряжений с помощью алгоритма MNA (https://lpsa.swarthmore.edu/Systems/Electrical/mna/MNA3.html)
// Количество вершин схемы кроме 0 - земли
int n = nodesCount - 1;
// Количество идеальных источников напряжения
int m = voltageSources.size();
// Проверка количеств
if (n <= 0)
{
error = QString(u8"Недостаточно вершин в схеме!");
return false;
}
if (m == 0 && currentSources.size() == 0)
{
error = QString(u8"В схеме нет источников напряжения или тока!");
return false;
}
// Матрица A (последний столбец - матрица z)
QVector<QVector<double>> a(n + m, QVector<double>(n + m + 1, 0.0));
// Подматрица G - определяется пассивными элементами (резисторами)
for (const auto& pr : elements)
{
// Вершины, к которым подключён элемент
int i = pr.second.first, j = pr.second.second;
// Проводимость элемента
double conductance = 1.0 / pr.first->getResistance();
// Добавление на диагональ
if (i != 0)
a[i - 1][i - 1] += conductance;
if (j != 0)
a[j - 1][j - 1] += conductance;
// Вычитание в (i, j) и (j, i)
if (i != 0 && j != 0)
{
a[i - 1][j - 1] -= conductance;
a[j - 1][i - 1] -= conductance;
}
}
// Номер источника напряжения
int vsInd = 0;
// Все источники напряжения
for (const auto& pr : voltageSources)
{
// Вершины, к которым подключён элемент
int i, j, k;
std::tie(i, j, k) = pr.second;
// Если есть внутреннее сопротивление
if (j != -1)
{
// Проводимость элемента
double conductance = 1.0 / pr.first->getResistance();
// Добавление на диагональ
if (i != 0)
a[i - 1][i - 1] += conductance;
if (j != 0)
a[j - 1][j - 1] += conductance;
// Вычитание в (i, j) и (j, i)
if (i != 0 && j != 0)
{
a[i - 1][j - 1] -= conductance;
a[j - 1][i - 1] -= conductance;
}
}
// Заполнение подматриц B и C
if (j == -1) // Если нет внутреннего сопротивления
{
if (i != 0)
a[i - 1][n + vsInd] = a[n + vsInd][i - 1] = 1;
}
else
{
if (j != 0)
a[j - 1][n + vsInd] = a[n + vsInd][j - 1] = 1;
}
if (k != 0)
a[k - 1][n + vsInd] = a[n + vsInd][k - 1] = -1;
// Заполнение матрицы z
a[n + vsInd][n + m] = pr.first->getVoltage();
vsInd++;
}
// Номер источника тока
int csInd = 0;
// Все источники тока
for (const auto& pr : currentSources)
{
// Вершины, к которым подключён элемент
int i = pr.second.first, j = pr.second.second;
// Если есть внутреннее сопротивление
if (!std::isinf(pr.first->getResistance()))
{
// Проводимость элемента
double conductance = 1.0 / pr.first->getResistance();
// Добавление на диагональ
if (i != 0)
a[i - 1][i - 1] += conductance;
if (j != 0)
a[j - 1][j - 1] += conductance;
// Вычитание в (i, j) и (j, i)
if (i != 0 && j != 0)
{
a[i - 1][j - 1] -= conductance;
a[j - 1][i - 1] -= conductance;
}
}
// Заполнение матрицы z
if (i != 0)
a[i - 1][n + m] += pr.first->getCurrent();
if (j != 0)
a[j - 1][n + m] -= pr.first->getCurrent();
csInd++;
}
// Матрица x - результат
QVector<double> x(n + m, 0.0);
if (solveLinearEquations(a, x) != 1)
{
error = QString(u8"Невозможно вычислить характеристики схемы (нет единственного решения)!");
return false;
}
// Заполнение потенциалов для вершин и токов через источники напряжения
nodesPotential.resize(nodesCount);
voltageSourcesCurrents.resize(m);
for (int i = 0; i < n; i++)
nodesPotential[i + 1] = x[i];
for (int i = 0; i < m; i++)
voltageSourcesCurrents[i] = abs(x[n + i]);
// Обновление состояний элементов в зависимости от тока
for (const auto& pr : elements)
{
// Вычисление тока
double current = abs(nodesPotential[pr.second.first] - nodesPotential[pr.second.second]) / pr.first->getResistance();
// Обновление состояния
pr.first->onCurrentFlow(current);
}
return true;
}
// Решение системы линейных уравнений
int ElectricalCircuitCalculator::solveLinearEquations(QVector<QVector<double>> a, QVector<double>& res)
{
// Погрешность
const double EPS = 1e-9;
// Количество уравнений
int n = a.size();
// Количество неизвестных
int m = a[0].size() - 1;
// Номер строки, в которой будет результат для i-й переменной
QVector<int> where(m, -1);
// Проход по столбцам
for (int col = 0, row = 0; col < m && row < n; col++)
{
// Номер строки с максимальным в столбе числом
int sel = row;
for (int i = row; i < n; i++)
if (std::abs(a[i][col]) > std::abs(a[sel][col]))
sel = i;
// Если все числа в столбце равны 0, то переход к следующему столбцу
if (std::abs(a[sel][col]) < EPS)
continue;
// Обмен текущей строки и строки с максимумом
for (int i = col; i <= m; i++)
std::swap(a[sel][i], a[row][i]);
// Решение для переменной - текущая строка
where[col] = row;
// Проход по всем строкам, кроме текущей
for (int i = 0; i < n; i++)
if (i != row)
{
// Вычитание текущей строки из i-й, чтобы коэффициенты обращались в нули
double c = a[i][col] / a[row][col];
for (int j = col; j <= m; ++j)
a[i][j] -= a[row][j] * c;
}
// Переход к следующей строке
row++;
}
// Если для переменной определена строка с решением, то вычисление переменной
for (int i = 0; i < m; i++)
if (where[i] != -1)
res[i] = a[where[i]][m] / a[where[i]][i];
// Проверка правильности решения
for (int i = 0; i < n; i++)
{
double sum = 0;
for (int j = 0; j < m; j++)
sum += res[j] * a[i][j];
if (abs(sum - a[i][m]) > EPS)
return 0; // Если не равно, то решения нет
}
// Если есть переменная, для которой не определено решение, то это независимая переменная
for (int i = 0; i < m; i++)
if (where[i] == -1)
return -1; // Бесконечное число решений
// Решение единственно
return 1;
}
// Вычисление характеристик схемы
bool ElectricalCircuitCalculator::calculateCircuit(QString& error)
{
// Нахождение вершин и элементов схемы
if (!findNodesAndElements(error))
return false;
// Нахождение напряжений и токов
if (!findVoltagesAndCurrents(error))
return false;
return true;
}
// Нахождение напряжения между двумя точками - разность потенциалов
bool ElectricalCircuitCalculator::getVoltage(const QPoint& loc1, const QPoint& loc2, double& res)
{
// Проверки принадлежности точек схеме
if (!dsuParent.contains(loc1) || !dsuParent.contains(loc2))
return false;
QPoint leader1 = dsuLeader(loc1), leader2 = dsuLeader(loc2);
if (!compByLeader.contains(leader1) || !compByLeader.contains(leader2))
return false;
int comp1 = compByLeader[leader1], comp2 = compByLeader[leader2];
// Вычисление результата
res = nodesPotential[comp1] - nodesPotential[comp2];
return true;
}
// Нахождение тока через элемент
bool ElectricalCircuitCalculator::getCurrent(const QPoint& loc, Qt::Orientation orientation, double& res)
{
// Проверка существования элемента
auto el = ElectricalElementsManager::getInstance().getElement(loc, orientation);
if (el == nullptr)
return false;
// Если элемент - источник напряжения
for (int i = 0; i < voltageSources.size(); i++)
if (voltageSources[i].first == el)
{
res = voltageSourcesCurrents[i];
return true;
}
// Если элемент - источник тока
for (int i = 0; i < currentSources.size(); i++)
if (currentSources[i].first == el)
{
// Если идеальный источник
if (std::isinf(el->getResistance()))
res = currentSources[i].first->getCurrent();
else
{
// Иначе вычисление по закону Ома
if (!getVoltage(el->getEndPoints()[0], el->getEndPoints()[1], res))
return false;
res = currentSources[i].first->getCurrent() - abs(res / el->getResistance());
}
return true;
}
// Проверка сопротивления элемента
if (el->getResistance() == 0.0 || std::isinf(el->getResistance()))
return false;
// Иначе вычисление по закону Ома
if (!getVoltage(el->getEndPoints()[0], el->getEndPoints()[1], res))
return false;
res = abs(res / el->getResistance());
return true;
} | true |
c14f2346eddd7b50a8e828e1235ef2581a39625f | C++ | zhanggyb/skland | /include/skland/core/rect.hpp | UTF-8 | 7,456 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SKLAND_CORE_RECT_HPP_
#define SKLAND_CORE_RECT_HPP_
#include "point.hpp"
#include "size.hpp"
#include <cstring>
#include <algorithm>
namespace skland {
namespace core {
/**
* @ingroup core
* @brief Template class for rectangle with 4 edges (left, top, right, bottom).
*/
template<typename T>
struct Rect {
/**
* @brief Create a new rectangle from the specified values of left/top/right/bottom
* @param left
* @param top
* @param right
* @param bottom
* @return
*/
inline static Rect MakeFromLTRB(T left, T top, T right, T bottom) {
return Rect(left, top, right, bottom);
}
/**
* @brief Create a new rectangle from the specified values of x/y/width/height
* @param x
* @param y
* @param width
* @param height
* @return
*/
inline static Rect MakeFromXYWH(T x, T y, T width, T height) {
return Rect(x, y, x + width, y + height);
}
/**
* @brief Default constructor
*
* Create an empty rectangle
*/
inline Rect()
: left(0), top(0), right(0), bottom(0) {}
/**
* @brief Construct a Rect with specified LTRB values
* @param left
* @param top
* @param right
* @param bottom
*/
inline Rect(T left, T top, T right, T bottom)
: left(left), top(top), right(right), bottom(bottom) {}
/**
* @brief Construct a Rect with width and height
* @param width
* @param height
*/
inline Rect(T width, T height)
: left(0), top(0), right(width), bottom(height) {}
/**
* @brief Copy constructor
* @param other
*/
inline Rect(const Rect &other)
: left(other.left), top(other.top), right(other.right), bottom(other.bottom) {}
/**
* @brief Copy constructor
* @tparam R
* @param other
*/
template<typename R>
inline Rect(const Rect<R> &other)
: left(T(other.left)), top(T(other.top)), right(T(other.right)), bottom(T(other.bottom)) {}
/**
* @brief Overload the assignment operator
* @param other
* @return
*/
inline Rect &operator=(const Rect &other) {
left = other.left;
top = other.top;
right = other.right;
bottom = other.bottom;
return *this;
}
/**
* @brief Overload the assignment operator
* @tparam R
* @param other
* @return
*/
template<typename R>
inline Rect &operator=(const Rect<R> &other) {
left = T(other.left);
top = T(other.top);
right = T(other.right);
bottom = T(other.bottom);
return *this;
}
/**
* @brief Returns a boolean that indicates whether the rectangle is empty
* @return
* - true Empty, width of height is 0 or negative
* - false Not empty
*/
inline bool IsEmpty() const {
return (width() <= T(0)) || (height() <= T(0));
}
/**
* @brief Returns a boolean that indicates whether the given point is contained in this rectangle
* @param x
* @param y
* @return
*/
inline bool Contain(T x, T y) const {
return left <= x && x < right && top <= y && y < bottom;
}
/**
* @brief Returns a boolean value that indicates whether this rect completely encloses another
* @param other
* @return
*/
inline bool Contain(const Rect &other) const {
return left <= other.left &&
top <= other.top &&
right >= other.right &&
bottom >= other.bottom;
}
/**
* @brief Move the position of this rectangle to the given position
* @param x
* @param y
*/
inline void MoveTo(T x, T y) {
right = x + width();
bottom = y + height();
left = x;
top = y;
}
/**
* @brief Relatively move
* @param dx
* @param dy
*/
inline void Move(T dx, T dy) {
left += dx;
top += dy;
right += dx;
bottom += dy;
}
/**
* @brief Resize this rectangle
* @param width
* @param height
*/
inline void Resize(T width, T height) {
right = left + width;
bottom = top + height;
}
/**
* @brief Insets a rectangle by a specified value
* @param val
* @return
*/
inline Rect Inset(T val) const {
return Inset(val, val);
}
/**
* @brief Insets a rectangle by specified values
* @param dx
* @param dy
* @return
*/
inline Rect Inset(T dx, T dy) const {
return Rect(left + dx, top + dy, right - dx, bottom - dy);
}
/**
* @brief Returns a boolean if this rect intersects another
* @param other
* @return
*/
inline bool Intersect(const Rect &other) const {
return !GetIntersection(*this, other).IsEmpty();
}
/**
* @brief Get the intersection of two rectangles
* @param rect1
* @param rect2
* @return
*/
static inline Rect GetIntersection(const Rect &rect1, const Rect &rect2) {
return Rect(std::max(rect1.left, rect2.left),
std::max(rect1.top, rect2.top),
std::min(rect1.right, rect2.right),
std::min(rect1.bottom, rect2.bottom));
}
/**
* @brief Get the left coordinate
* @return
*/
inline T x() const { return left; }
/**
* @brief Get the top coordinate
* @return
*/
inline T y() const { return top; }
/**
* @brief Get the width
* @return
*/
inline T width() const { return right - left; }
/**
* @brief Get the height
* @return
*/
inline T height() const { return bottom - top; }
/**
* @brief Get the center of x
* @return
*/
inline T center_x() const { return left + width() / T(2.0); }
/**
* @brief Get the center of y
* @return
*/
inline T center_y() const { return top + height() / T(2.0); }
/**
* @brief Left
*/
union { T l, left, x0; };
/**
* @brief Top
*/
union { T t, top, y0; };
/**
* @brief Right
*/
union { T r, right, x1; };
/**
* @brief Bottom
*/
union { T b, bottom, y1; };
};
/**
* @ingroup core
* @brief Multiple a given rect with a scalar number
* @tparam T
* @param src
* @param factor
* @return
*/
template<typename T>
inline Rect<T> operator*(const Rect<T> &src, int factor) {
return Rect<T>(src.left * factor, src.top * factor, src.right * factor, src.bottom * factor);
}
/**
* @ingroup core
* @brief Compare twe rectangle objects
* @tparam T
* @param src
* @param dst
* @return
*/
template<typename T>
inline bool operator==(const Rect<T> &src, const Rect<T> &dst) {
return memcmp(&src, &dst, sizeof(Rect<T>)) == 0;
}
template<typename T>
inline bool operator!=(const Rect<T> &src, const Rect<T> &dst) {
return memcmp(&src, &dst, sizeof(Rect<T>)) != 0;
}
/**
* @ingroup core
* @brief A typedef to Rect with integer values
*/
typedef Rect<int> RectI;
/**
* @ingroup core
* @brief A typedef to Rect with float values
*/
typedef Rect<float> RectF;
/**
* @ingroup core
* @brief A typedef to Rect with double values
*/
typedef Rect<double> RectD;
} // namespace core
} // namespace skland
#endif // SKLAND_CORE_RECT_HPP_
| true |
449d83f2fc0823217b0ee9daa54f50de2ff2171b | C++ | patricksinclair/FinalTangle | /src/TangleRunAction.cc | UTF-8 | 3,285 | 2.53125 | 3 | [] | no_license | #include "TangleRunAction.hh"
#include "G4Run.hh"
#include "G4Threading.hh"
#include "G4AutoLock.hh"
#include <cassert>
#include <fstream>
TangleRunAction *TangleRunAction::fpMasterRunAction = 0;
std::vector<std::vector<TangleRunAction::Data> *> TangleRunAction::fPointers;
std::vector<std::vector<TangleRunAction::crystalData> *> TangleRunAction::fcrystalPointers;
std::vector<std::vector<TangleRunAction::crystalEnergies> *> TangleRunAction::fcrystalEnergiesPointers;
namespace {
G4Mutex runActionMutex = G4MUTEX_INITIALIZER;
}
TangleRunAction::TangleRunAction() {
if (G4Threading::IsMasterThread()) {
fpMasterRunAction = this;
}
fData.reserve(10000000);
fcrystalData.reserve(10000000);
fcrystalEnergies.reserve(10000000);
G4AutoLock lock(&runActionMutex);
fpMasterRunAction->fPointers.push_back(&fData);
fpMasterRunAction->fcrystalPointers.push_back(&fcrystalData);
fpMasterRunAction->fcrystalEnergiesPointers.push_back(&fcrystalEnergies);
}
TangleRunAction::~TangleRunAction() {}
void TangleRunAction::BeginOfRunAction(const G4Run *) {
fData.clear();
}
namespace {
std::ofstream outFile("outFile.csv");
std::ofstream crystScattersFile("crystScatters.csv");
std::ofstream crystEnergiesFile("crystEnergies.csv");
}
void TangleRunAction::EndOfRunAction(const G4Run *run) {
G4int nofEvents = run->GetNumberOfEvent();
if (nofEvents == 0) return;
G4String runType;
if (G4Threading::IsMasterThread()) {
runType = "Global Run";
// Workers finished...
outFile << "#theta1, phi1, theta2, phi2";
for (const auto &pointer: fPointers) {
for (const auto &data: *pointer) {
outFile
<< "\n" << data.fTheta1 << ", " << data.fPhi1
<< ", " << data.fTheta2 << ", " << data.fPhi2;
}
}
outFile << std::endl;
crystScattersFile << "#phiA, phiB, dPhi\n";
for(const auto &crypointer: fcrystalPointers) {
for(const auto &cryData: *crypointer) {
G4double dPhi = cryData.fPhiB - cryData.fPhiA;
if(dPhi < 0.) dPhi += 360.;
crystScattersFile
<< cryData.fPhiA << " " << cryData.fPhiB << " " << dPhi << "\n";
}
}
crystScattersFile << std::endl;
for(const auto &cryEngpointer: fcrystalEnergiesPointers){
for(const auto &cryEngData: *cryEngpointer){
crystEnergiesFile
<< cryEngData.fEAC << " " << cryEngData.fEAN << " " << cryEngData.fEAE << " "
<< cryEngData.fEAS << " " << cryEngData.fEAW << "\n" << cryEngData.fEBC << " "
<< cryEngData.fEBN << " " << cryEngData.fEBE << " " << cryEngData.fEBS << " "
<< cryEngData.fEBW <<"\n";
}
}
crystEnergiesFile << std::endl;
} else {
runType = "Local Run-";
}
G4cout
<< "\n----------------------End of " << runType << "------------------------"
<< "\n The run consists of " << nofEvents << " events."
<< "\n------------------------------------------------------------"
<< G4endl;
}
| true |
1046242d259ccf1821dc0cfd12f0257f210bcaeb | C++ | marrusian/C | /Programare Procedurala/Solutiile ecuatiei x^2-y^2=k.cpp | UTF-8 | 1,595 | 2.90625 | 3 | [] | no_license | #include<iostream>
#include<cmath>
int main(void)
{
using namespace std;
int k = 0, sir_divizori[100] = {}, counter = 2;
sir_divizori[1] = 1;
cout << "Introduceti un numar intreg: ";
cin >> k;
if((k%2 == 0) && ((k%4) != 0))
cout << "Ecuatia nu are solutii intregi";
else if(k%2 == 1)
{
bool flag = true;
for (int i = 2; i*i <= k; i++)
{
if(k%i == 0)
{
sir_divizori[counter] = i;
counter++;
flag = false;
for (int j = i+1; j <= (k/2); j++)
{
if (j%2 != 0)
if(k%j == 0)
{
sir_divizori[counter] = j;
counter++;
}
}
break;
}
}
sir_divizori[counter] = k;
if(flag)
{
cout << "X= " << int(ceil(double(k)/2));
cout << "; Y= " << int(floor(double(k)/2)) << endl;
}
else
for (int q = 1, w = counter; q < w; q++, w--)
{
cout << "X= " << (sir_divizori[q] + sir_divizori[w])/2;
cout << "; Y= " << (sir_divizori[w] - sir_divizori[q])/2 << endl;
}
}
else
{
for (int i = 2; i <= (k/2); i++)
{
if(k%i == 0)
{
sir_divizori[counter] = i;
counter++;
}
}
sir_divizori[counter] = k;
for (int q = 1, w = counter; q < w; q++, w--)
{
if (((sir_divizori[q]%2) != 0) || (sir_divizori[w]%2 !=0))
continue;
cout << "X= " << (sir_divizori[q] + sir_divizori[w])/2;
cout << "; Y= " << (sir_divizori[w] - sir_divizori[q])/2 << endl;
}
}
int mid = ceil((counter)/2.);
if (((counter % 2) != 0) && (sir_divizori[mid]*sir_divizori[mid]) == k)
{
cout << "X = " << sir_divizori[mid];
cout << "; Y = " << "0";
}
return 0;
}
| true |