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
6c62aa3adf2e55d8166011885ac922447e80c008
C++
Khuromu/CustomPhysXEngineOpenGL
/Rigidbody with Rotation/CollisionEngine_VS2015/CollisionEngine/Polygon.cpp
UTF-8
10,471
2.640625
3
[]
no_license
#include "Polygon.h" #include <GL/glu.h> #include "InertiaTensor.h" #include "PhysicEngine.h" #include "GlobalVariables.h" #include "Renderer.h" #include "Collision.h" CPolygon::CPolygon(size_t index) : m_vertexBufferId(0), m_index(index), density(0.1f) { aabb = new AABB(); } CPolygon::~CPolygon() { DestroyBuffers(); } void CPolygon::Build() { m_lines.clear(); ComputeArea(); RecenterOnCenterOfMass(); ComputeLocalInertiaTensor(); CreateBuffers(); BuildLines(); } void CPolygon::Draw() { UpdateAABB(); glColor3f(0.7f, 0.7f, 0.7f); // Set transforms (qssuming model view mode is set) float transfMat[16] = { rotation.X.x, rotation.X.y, 0.0f, 0.0f, rotation.Y.x, rotation.Y.y, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, position.x, position.y, -1.0f, 1.0f }; glPushMatrix(); glMultMatrixf(transfMat); // Draw vertices BindBuffers(); glDrawArrays(GL_LINE_LOOP, 0, points.size()); glDisableClientState(GL_VERTEX_ARRAY); glPopMatrix(); } size_t CPolygon::GetIndex() const { return m_index; } float CPolygon::GetArea() const { return fabsf(m_signedArea); } Vec2 CPolygon::TransformPoint(const Vec2& point) const { return position + rotation * point; } Vec2 CPolygon::InverseTransformPoint(const Vec2& point) const { return rotation.GetInverseOrtho() * (point - position); } /*Vec2 CPolygon::GetCenterOfGravity() { Vec2 firstPoint = points[0]; float centerX = 0; float centerY = 0; // The area is needed twice to be properly set in the center of gravity float area = 0; float offset; for (unsigned int i = 0; i < points.size() - 1; i++) { // two points of the segment Vec2 a = points[i]; Vec2 b = points[i + 1]; // formula (x1 * yi+1 - xi+1 * yi) => gives the Area * 2 offset = (a.x - firstPoint.x) * (b.y - firstPoint.y) - (b.x - firstPoint.x) * (a.y - firstPoint.y); // offset / 2 because Area * 2 above area += offset / 2; // formula (xi + xi+1) / (yi + yi+1) centerX += (a.x + b.x - 2 * firstPoint.x) * offset; centerY += (a.y + b.y - 2 * firstPoint.y) * offset; } offset = area * 6; return TransformPoint(Vec2(centerX / offset + firstPoint.x, centerY / offset + firstPoint.y)); } void CPolygon::DrawCenterOfGravity() { Vec2 g = GetCenterOfGravity(); if (aabb->GetIsDisplayingAABB()) { gVars->pRenderer->DrawLine(Vec2(g.x - 0.1f, g.y), Vec2(g.x + 0.1f, g.y), 1, 0.8f, 0); gVars->pRenderer->DrawLine(Vec2(g.x, g.y - 0.1f), Vec2(g.x, g.y + 0.1f), 1, 0.8f, 0); } }*/ CPolygon* CPolygon::MinkowskiDiff(const CPolygon& otherPoly) const { // -1 cannot be in the index CPolygon* poly = new CPolygon(-1); for (unsigned int i = 0; i < points.size(); i++) { for (unsigned int j = 0; j < otherPoly.points.size(); j++) poly->points.push_back(otherPoly.TransformPoint(otherPoly.points[j]) - TransformPoint(points[i])); } poly->ConvexHull(); return poly; } int CPolygon::Orientation(Vec2 pivot, Vec2 externalPoint, Vec2 anyOther) { float val = (externalPoint.y - pivot.y) * (anyOther.x - externalPoint.x) - (externalPoint.x - pivot.x) * (anyOther.y - externalPoint.y); // Points are clockwise if (val > 0.f) return 1; // Points are counterclockwise else if (val < 0.f) return 2; // Points are colinear else return 0; } void CPolygon::ConvexHull() { // At least three points needed if (points.size() < 3) return; std::vector<Vec2> hull; int leftPoint = 0; // Find out the leftmost point for (unsigned int i = 1; i < points.size(); i++) { if (points[i].x < points[leftPoint].x || (points[i].x == points[leftPoint].x && points[i].y < points[leftPoint].y)) leftPoint = i; } int pivot = leftPoint; int externalPoint = 0; do { hull.push_back(points[pivot]); externalPoint = (pivot + 1) % points.size(); for (unsigned int i = 0; i < points.size(); i++) { // If counterclockwise if (Orientation(points[pivot], points[i], points[externalPoint]) == 2) externalPoint = i; } pivot = externalPoint; } while (pivot != leftPoint); points = hull; hull.clear(); } int CPolygon::SupportPoint(Vec2& direction) { int index = 0; float maxVal = points[index] | direction; float currentVal; for (int i = 1; i < points.size(); i++) { currentVal = points[i] | direction; if (maxVal < currentVal) { index = i; maxVal = currentVal; } } return index; } bool CPolygon::GJK(Vec2& impact, Vec2& normal, float distance) { const Vec2 origin = Vec2::Zero(); Simplex simplex = Simplex(); simplex.AddPoint(points[0]); int prevSupportPointIndex = -1; Vec2 point; Vec2 direction; int index; int maxLimit = points.size() * points.size(); int limitCount = 0; do { point = simplex.GetClosestPoint(origin); if (simplex.count == 3) { gVars->pRenderer->DrawLine(point, point + Vec2(0.5f, 0.5f), 0.1f, 0.7f, 0.7f); gVars->pRenderer->DrawLine(point, point + Vec2(-0.5f, -0.5f), 0.1f, 0.7f, 0.7f); gVars->pRenderer->DrawLine(point, point + Vec2(0.5f, -0.5f), 0.1f, 0.7f, 0.7f); gVars->pRenderer->DrawLine(point, point + Vec2(-0.5f, 0.5f), 0.1f, 0.7f, 0.7f); } if (simplex.ComparePoints(origin, point)) { impact = points[index]; normal = simplex.ComputeNormal(); distance = normal.GetLength(); gVars->pRenderer->DrawLine(normal, Vec2(0.f, 0.f), 0.7f, 0.6f, 0.1f); return true; } simplex.Culling(origin); direction = origin - point; gVars->pRenderer->DrawLine(point, direction, 0.8f, 0.1f, 0.1f); index = SupportPoint(direction); simplex.AddPoint(points[index]); simplex.Draw(); gVars->pRenderer->DrawLine(Vec2(0.f, 0.f), Vec2(0.5f, 0.5f), 0.6f, 0.5f, 0.1f); gVars->pRenderer->DrawLine(Vec2(0.f, 0.f), Vec2(-0.5f, -0.5f), 0.6f, 0.5f, 0.1f); gVars->pRenderer->DrawLine(Vec2(0.f, 0.f), Vec2(0.5f, -0.5f), 0.6f, 0.5f, 0.1f); gVars->pRenderer->DrawLine(Vec2(0.f, 0.f), Vec2(-0.5f, 0.5f), 0.6f, 0.5f, 0.1f); if (index == prevSupportPointIndex) return false; prevSupportPointIndex = index; limitCount++; } while (limitCount <= maxLimit); return false; } bool CPolygon::IsPointInside(const Vec2& point) const { float maxDist = -FLT_MAX; for (const Line& line : m_lines) { Line globalLine = line.Transform(rotation, position); float pointDist = globalLine.GetPointDist(point); maxDist = Max(maxDist, pointDist); } return maxDist <= 0.0f; } bool CPolygon::IsLineIntersectingPolygon(const Line& line, Vec2& colPoint, float& colDist) const { //float dist = 0.0f; float minDist = FLT_MAX; Vec2 minPoint; float lastDist = 0.0f; bool intersecting = false; for (const Vec2& point : points) { Vec2 globalPoint = TransformPoint(point); float dist = line.GetPointDist(globalPoint); if (dist < minDist) { minPoint = globalPoint; minDist = dist; } intersecting = intersecting || (dist != 0.0f && lastDist * dist < 0.0f); lastDist = dist; } if (minDist <= 0.0f) { colDist = -minDist; colPoint = minPoint; } return (minDist <= 0.0f); } bool CPolygon::CheckCollision(const CPolygon& poly, SCollision& collision) const { CPolygon* polyResult = MinkowskiDiff(poly); // Can be drawn in debug mode for (int i = 0; i < polyResult->points.size() && aabb->bIsDisplayed; i++) { if (i < polyResult->points.size() - 1) gVars->pRenderer->DrawLine(polyResult->points[i], polyResult->points[i + 1], 0.7f, 0.3f, 0.1f); else gVars->pRenderer->DrawLine(polyResult->points[i], polyResult->points[0], 0.7f, 0.3f, 0.1f); } bool bGJKResult = polyResult->GJK(collision.point, collision.normal, collision.distance);// colPoint, colNormal, colDist); delete polyResult; return bGJKResult; //return false; } AABB* CPolygon::GetOwnAABB() { return aabb; } void CPolygon::UpdateAABB() { aabb->Center(position); for (const Vec2& point : points) { aabb->Extend(TransformPoint(point)); } if (aabb->bIsDisplayed) aabb->RenderBoundingBox(); } float CPolygon::GetMass() const { return density * GetArea(); } float CPolygon::GetInertiaTensor() const { return m_localInertiaTensor * GetMass(); } Vec2 CPolygon::GetPointVelocity(const Vec2& point) const { return speed + (point - position).GetNormal() * angularVelocity; } void CPolygon::CreateBuffers() { DestroyBuffers(); float* vertices = new float[3 * points.size()]; for (size_t i = 0; i < points.size(); ++i) { vertices[3 * i] = points[i].x; vertices[3 * i + 1] = points[i].y; vertices[3 * i + 2] = 0.0f; } glGenBuffers(1, &m_vertexBufferId); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferId); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 3 * points.size(), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); delete[] vertices; } void CPolygon::BindBuffers() { if (m_vertexBufferId != 0) { glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferId); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, (void*)0); } } void CPolygon::DestroyBuffers() { if (m_vertexBufferId != 0) { glDeleteBuffers(1, &m_vertexBufferId); m_vertexBufferId = 0; } } void CPolygon::BuildLines() { for (size_t index = 0; index < points.size(); ++index) { const Vec2& pointA = points[index]; const Vec2& pointB = points[(index + 1) % points.size()]; Vec2 lineDir = (pointA - pointB).Normalized(); m_lines.push_back(Line(pointB, lineDir, (pointA - pointB).GetLength())); } } void CPolygon::ComputeArea() { m_signedArea = 0.0f; for (size_t index = 0; index < points.size(); ++index) { const Vec2& pointA = points[index]; const Vec2& pointB = points[(index + 1) % points.size()]; m_signedArea += pointA.x * pointB.y - pointB.x * pointA.y; } m_signedArea *= 0.5f; } void CPolygon::RecenterOnCenterOfMass() { Vec2 centroid; for (size_t index = 0; index < points.size(); ++index) { const Vec2& pointA = points[index]; const Vec2& pointB = points[(index + 1) % points.size()]; float factor = pointA.x * pointB.y - pointB.x * pointA.y; centroid.x += (pointA.x + pointB.x) * factor; centroid.y += (pointA.y + pointB.y) * factor; } centroid /= 6.0f * m_signedArea; for (Vec2& point : points) { point -= centroid; } position += centroid; } void CPolygon::ComputeLocalInertiaTensor() { m_localInertiaTensor = 0.0f; for (size_t i = 0; i + 1 < points.size(); ++i) { const Vec2& pointA = points[i]; const Vec2& pointB = points[i + 1]; m_localInertiaTensor += ComputeInertiaTensor_Triangle(Vec2(), pointA, pointB); } } bool operator < (const CPolygonPtr& poly, const CPolygonPtr& otherPoly) { return (poly->aabb->min.x < otherPoly->aabb->min.x); }
true
47c5deeb60749cdfdb9d8c0b54251db00efdba93
C++
david20571015/Introduction-to-Computers-and-Programming
/lab4/2.cpp
UTF-8
293
2.75
3
[]
no_license
#include<stdio.h> int main(void){ int n=0; double x,arcsin; printf("x = "); scanf("%lf",&x); double term=x; while((term>=1e-12)||(term<=-1e-12)){ arcsin+=term; n++; term=term*(2*n-1)*(2*n)*(2*n-1)/4/n/n/(2*n+1)*x*x; } printf("arcsin %.2lf = %.10lf",x,arcsin); return 0; }
true
d5f0f29299ef6b026192cbc4c9fdb442666bbe69
C++
luisfmplus/proyecto3_ED
/Codigo/7BPersonas.cpp
UTF-8
21,290
3.234375
3
[]
no_license
/* Manejo de errores. 1 = todo bien -1 = lista vacia -2 = fuera de rango -3 = repetido -4 = error en general */ //falta implementar la funcion de borrarNodo() //modificaciones en: abcdefg #include <iostream> using namespace std; class PaginaNodoPersona; class NodoPersona { public: NodoPersona(int Pas, char* nom){ Identificador = Pas; for (int i = 0; nom[i] != '\000' && i < sizeof(Nombre) ; i++){ Nombre[i] = nom[i]; } Izquierda = NULL; Derecha =NULL; } private: int Identificador; char Nombre[30] = "\000"; PaginaNodoPersona *Izquierda; PaginaNodoPersona *Derecha; friend class ArbolB_Persona; friend class PaginaNodoPersona; }; typedef NodoPersona *pnodopersona; class PaginaNodoPersona { public: pnodopersona pnodo = NULL; PaginaNodoPersona *siguiente = NULL; PaginaNodoPersona *anterior = NULL; PaginaNodoPersona* crearPaginaVacia(int tamano){ //crea una pagina del tamanno indicado y devuelve su puntero PaginaNodoPersona * aux = NULL; PaginaNodoPersona * ante = NULL; PaginaNodoPersona * sigue = NULL; if ((tamano <= 0) || (tamano%2 ==1)){ return NULL; } aux = new PaginaNodoPersona(NULL,NULL); ante = aux; for (int i = 1; i < tamano; i++){ sigue = new PaginaNodoPersona(NULL,ante); ante = sigue; } return aux; } PaginaNodoPersona* clonarPagina(PaginaNodoPersona* aux){ // crear un pagina identica a la recibida y devuelve su ubicacion PaginaNodoPersona* temp = aux; PaginaNodoPersona* aux2 = aux; PaginaNodoPersona*temp2 = NULL; int i; if (temp == NULL){ return NULL; } for ( i = 1; temp->siguiente != NULL; i++){ temp = temp->siguiente; } temp = crearPaginaVacia(i); temp2 = temp; while (aux2 != NULL){ temp2->pnodo = aux2->pnodo; temp2 = temp2->siguiente; aux2 = aux2->siguiente; } return temp; } void dividirPagina(PaginaNodoPersona* Izquierda, PaginaNodoPersona* Derecha){ //Dividimos los contenidos de la pagina Izquierda. //La mitad menor a la izquierda y la mitad mayor a la derecha //La pagina Derecha tiene que venir vacia PaginaNodoPersona* aux = Izquierda; PaginaNodoPersona* temp = Derecha; if ((aux == NULL) || (temp == NULL)){ return; } int tamanoIzquierda = tamanoMax(aux); int i; int j = 0; //aux queda en el primer elemento de la mitad mayor for (i = 0; i < (tamanoIzquierda/2); i++){ aux = aux->siguiente; } //hacemos la asignacion y borrado for (i; i > 0; i--){ temp->pnodo = aux->pnodo; aux->pnodo = NULL; temp = temp->siguiente; aux = aux->siguiente; } } int tamanoMax(PaginaNodoPersona* entrada){ PaginaNodoPersona* aux = entrada; int i; for ( i = 0; aux != NULL; i++){ aux = aux->siguiente; } return i; } int tamanoUsado(PaginaNodoPersona* entrada){ PaginaNodoPersona* aux = entrada; int i; int j = 0; for ( i = 0; aux != NULL; i++){ if (aux->pnodo != NULL){ j++; } aux = aux->siguiente; } return j; } private: PaginaNodoPersona(pnodopersona Elemento, PaginaNodoPersona* ante ){ pnodo = Elemento; anterior = ante; if (ante != NULL){ ante->siguiente = this; } } PaginaNodoPersona( PaginaNodoPersona* ante ){ pnodo = NULL; anterior = ante; if (ante != NULL){ ante->siguiente = this; } } }; class ArbolB_Persona { public: ArbolB_Persona(int tamano) { primero = NULL; tamanoPaginas = tamano;} ~ArbolB_Persona(); int getIdentificador(int &valor, pnodopersona aux); int getNombre(char *nombre, pnodopersona aux); int setIdentificador(int valor, pnodopersona aux); int setNombre(char *nombre, pnodopersona aux); pnodopersona getultimoNodoInsertado(); bool isArbolVacio() { return arbolVacio(); } int isIdentificadorRepetido(int valor); int insertarNodo(int pasport, char* nom); void MostrarNodo(pnodopersona aux); void Mostrar(); pnodopersona getNodo(int valor); bool getNodo(pnodopersona &recibir, int valor); int borrarNodo(pnodopersona nodo); private: bool arbolVacio() { return primero == NULL; } pnodopersona getNodo(int valor, pnodopersona aux); pnodopersona getNodo(int valor, PaginaNodoPersona* aux); void MostrarInorde(PaginaNodoPersona* aux); void MostrarInorde(pnodopersona aux); void Mostrar(pnodopersona aux); int isIdentificadorRepetido(int valor, pnodopersona aux); int isIdentificadorRepetido(int valor, PaginaNodoPersona* aux); int insertarNodo(int pasport, char* nom, PaginaNodoPersona* aux); int insertarNodo(int pasport, char* nom, pnodopersona aux); void borrarArbol(PaginaNodoPersona* pagina); void borrarArbol(pnodopersona nodo); int insertarNodo(PaginaNodoPersona*& raiz, pnodopersona nodo); int empujar(pnodopersona nodo, PaginaNodoPersona*aux, bool& empujararriba, pnodopersona& X, PaginaNodoPersona*& Xr); PaginaNodoPersona* buscarNodo(pnodopersona nodo, PaginaNodoPersona*aux, int& k); int meterHoja(pnodopersona nodo, PaginaNodoPersona* Xr, PaginaNodoPersona* aux, int k); int dividirNodo(pnodopersona nodo,pnodopersona& X,PaginaNodoPersona*& Xr, PaginaNodoPersona* aux, int k); PaginaNodoPersona* primero; pnodopersona ultimonodo; int tamanoPaginas = 4; }; ArbolB_Persona :: ~ArbolB_Persona(){ borrarArbol(primero); primero == NULL; } void ArbolB_Persona :: borrarArbol(PaginaNodoPersona* pagina) { if (pagina == NULL){ return; } PaginaNodoPersona* aux = pagina->siguiente; PaginaNodoPersona* temp; // si aux == NULL, significa que la pagina tiene solamente un nodo // adicionalmente no entra en el while while (aux != NULL){ //este while omite al ultimo puntero, por lo tanto se repite una vez mas afuera del mismo borrarArbol(pagina->pnodo); temp = pagina; // aux = aux->siguiente; pagina = pagina->siguiente; delete temp; } //al ser esta pocision en la pagina, no ocupamos a los punteros adionales borrarArbol(pagina->pnodo); delete pagina; } void ArbolB_Persona :: borrarArbol(pnodopersona nodo) { if (nodo == NULL){ return; } borrarArbol(nodo->Izquierda); borrarArbol(nodo->Derecha); delete nodo; } int ArbolB_Persona :: insertarNodo(int pasport, char* nom){ PaginaNodoPersona* aux = primero; if (aux == NULL){ //Arbol vacio y pagina en nulo aux = aux->crearPaginaVacia(tamanoPaginas); aux->pnodo = new NodoPersona(pasport,nom); ultimonodo = aux->pnodo; primero = aux; return 1; } if (isIdentificadorRepetido(pasport) == -3 ){ //el elemento a insertar ya esta en el arbol return-3; } //inicio de la llamadas recursivas pnodopersona temp = new NodoPersona(pasport, nom); int i = insertarNodo(aux, temp); // actualizamos el puntero de primero if (aux != primero ){ primero = aux; } return i; } int ArbolB_Persona :: insertarNodo(PaginaNodoPersona*& raiz, pnodopersona nodo){ //al usar aux el cambio es local //al usar raiz el cambio es mas global //esta diferencia nos permite alterar al puntero "aux" con el valor de primero, // y nunca arriesgar la modificacion de primero PaginaNodoPersona* aux = raiz; bool empujararriba = false; pnodopersona X = NULL; PaginaNodoPersona* Xr = NULL; int i = empujar(nodo, aux, empujararriba, X, Xr); // creamos la nueva cabeza if (empujararriba){ aux = aux->crearPaginaVacia(tamanoPaginas); aux->pnodo = X; aux->pnodo->Izquierda = raiz; aux->pnodo->Derecha = Xr; raiz = aux; return 1; } return i; } int ArbolB_Persona :: empujar(pnodopersona nodo, PaginaNodoPersona*aux, bool& empujararriba, pnodopersona& X, PaginaNodoPersona*& Xr){ int k = 0; //pagina existe? if (aux == NULL){ empujararriba = true; X = nodo; Xr = NULL; } else { PaginaNodoPersona*posicion = buscarNodo(nodo,aux,k); //busca la pagina donde se deberia insertar si esta existe //pocision es el puntero de la siguiente pagina a revisar //este puntero puede ser nulo o no int i = empujar(nodo, posicion, empujararriba, X, Xr); if (empujararriba){ if (aux->tamanoMax(aux) > aux->tamanoUsado(aux)){ empujararriba = false; //resulta que pocision esta nulo si entra aqui i = meterHoja(X, Xr, aux ,k); } else { //entra a aqui si la pagina en la que queremos insertar esta llena empujararriba = true; i = dividirNodo(nodo, X, Xr,aux,k); } } return i; } return -2; } PaginaNodoPersona* ArbolB_Persona :: buscarNodo(pnodopersona nodo, PaginaNodoPersona*aux, int& k){ //esta funcion me devuelve la pocision del puntero en el ultimo nodo mayor que el valor a buscar // y la ubicacion de la pagina por la cual bajar // k = 0; bajamos a aux.pnodo.izquierda // k = 1; bajamos a aux.pnodo.derecha // k > 1; aux se mueve a la ubicacion correcta y aux.pnodo.derecha es por donde bajamos // k es un recordatorio de cual puntero devolvi if (nodo->Identificador < aux->pnodo->Identificador){ k = 0; } else { k = aux->tamanoUsado(aux); //dejamos a aux en el ultimo puntero a pnodo no null for (int i = k; i > 1 ; i--){ aux = aux->siguiente; } while ((nodo->Identificador < aux->pnodo->Identificador) && (k>1)){ aux = aux->anterior; k--; } return aux->pnodo->Derecha; } return aux->pnodo->Izquierda; } int ArbolB_Persona :: meterHoja(pnodopersona X, PaginaNodoPersona* Xr, PaginaNodoPersona* aux, int k){ //cuando entramos en esta funcion resulta que la pagina en la que insertaremos la informacion // no esta llena. eso significa que la pagina actual es recien creada o tiene menos del maximo //usando k sabemos cuantas pocisiones tenemos que correr int usado = aux->tamanoUsado(aux); //movemos el puntero al primer nodo vacio porque este tendra el valor del nuevo dato // el del dato anterior while (aux->pnodo != NULL){ aux = aux->siguiente; } if (k == usado){ //le asignamos el dato nuevo a ese nodo vacio aux->pnodo = X; aux->pnodo->Derecha = Xr; return 1; } while (k < usado){ // asignamos el valor anterior al nodo actual aux->pnodo = aux->anterior->pnodo; //movemos el nodo actual al anterior aux = aux->anterior; usado--; } //le asignamos a el nodo actual el valor nuevo aux->pnodo = X; aux->pnodo->Derecha = Xr; aux->pnodo->Izquierda= aux->siguiente->pnodo->Izquierda;//abcdefg aux->siguiente->pnodo->Izquierda = NULL;//abcdefg return 1; } int ArbolB_Persona :: dividirNodo(pnodopersona nodo,pnodopersona& X,PaginaNodoPersona*& Xr, PaginaNodoPersona* aux, int k){ //aclaracion de la funcion // Esta funcion esta basada en la que la profesora nos entrego y enseño, // sin embargo, debido a la circunstancia de que la pagina puede hacerse de cualquier tamanno // deseado es que la funcion se ve muy diferente int maximo = aux->tamanoMax(aux); if (X == nodo){ // la division esta ocurriendo en una hoja o // lo que se quiere insertar inicialmente esta en el centro // en ambos casos, implica que el nodo a insertar no tiene ningun hijo PaginaNodoPersona* temp = temp->crearPaginaVacia(tamanoPaginas); aux->dividirPagina(aux, temp); if (k <= ((maximo/2)-1) ){ // cuando entra aqui se debe subir el ultimo valor no nulo de la lista aux // y se debe insertar el valor de "nodo" en su pocision correspondiente en esa lista PaginaNodoPersona* sosten = aux;//abcdefg while (aux->pnodo != NULL){//abcdefg aux = aux->siguiente; } pnodopersona valorSubir = aux->anterior->pnodo; aux->anterior->pnodo = NULL; aux = sosten;//abcdefg meterHoja(nodo,NULL,aux,k); X = valorSubir; Xr = temp; } else if (k >= ((maximo/2)+1) ){ // cuando entra aqui se debe subir el primer valor no nulo de la lista temp // y se debe insertar el valor de "nodo" en su pocision correspondiente en esa lista pnodopersona valorSubir = temp->pnodo; temp->pnodo = NULL; //arreglamos el orden de los datos pues ahora estan: // [0,x,x1,x2] PaginaNodoPersona* Sosten = temp; while (temp->siguiente != NULL){ temp = temp->siguiente; temp->anterior->pnodo = temp->pnodo; } temp->pnodo = NULL; temp = Sosten; //finaliza el arreglo meterHoja(nodo,NULL,temp,(k-((maximo/2)+1))); X = valorSubir; Xr = temp; } else { //el nodo a insertar esta en la mitad X = nodo; Xr = temp; } } else { // el valor de X no es nulo, por lo tanto nuestro numero en nodo, ya fue insertado en alguna hoja // o resulta que la hoja se dividio y nodo estaba en el centro y por lo tanto subio, // en cualquier caso, ignoramos a nodo //el hecho de entrar aqui, significa que el valor en X no pudo ser insertado en la pagina pues esta esta llena PaginaNodoPersona* temp = temp->crearPaginaVacia(tamanoPaginas); aux->dividirPagina(aux, temp); if (k <= ((maximo/2)-1) ){ // cuando entra aqui se debe subir el ultimo valor no nulo de la lista aux // y se debe insertar el valor de X en su pocision correspondiente en esa lista PaginaNodoPersona* sosten = aux;//abcdefg while (aux->pnodo != NULL){//abcdefg aux = aux->siguiente; } pnodopersona valorSubir = aux->anterior->pnodo; aux->anterior->pnodo = NULL; aux = sosten;//abcdefg meterHoja(X,Xr,aux,k); temp->pnodo->Izquierda = valorSubir->Derecha; X = valorSubir; Xr = temp; } else if (k >= ((maximo/2)+1) ){ // cuando entra aqui se debe subir el primer valor no nulo de la lista temp // y se debe insertar el valor de X en su pocision correspondiente en esa lista pnodopersona valorSubir = temp->pnodo; temp->pnodo = NULL; //arreglamos el orden de los datos pues ahora estan: // [0,x,x1,x2] PaginaNodoPersona* Sosten = temp; while (temp->siguiente != NULL){ temp = temp->siguiente; temp->anterior->pnodo = temp->pnodo; } temp->pnodo = NULL; temp = Sosten; //finaliza el arreglo meterHoja(X,Xr,temp,(k-((maximo/2)+1))); temp->pnodo->Izquierda = valorSubir->Derecha; X = valorSubir; Xr = temp; } else { //el nodo a insertar esta en la mitad //antes de actualizar volver a actualizar los valores de X y Xr //debemos asignarle el puntero Xr a temp->pnodo->Izquierda = Xr; X = nodo; Xr = temp; } } return -2; } int ArbolB_Persona :: isIdentificadorRepetido(int valor){ // me informa que el nodo ya existe o que no existe //Funcion inicializadora de una busqueda recursiva por el valor indicado en la estructura //buscamos de forma recursiva si el valor se encuentra en la estructura // si no la encuentra, retornara -2 // si encuentra el valor retornara -3 // si la estructura esta vacia retorna -1 PaginaNodoPersona* aux = primero; if (arbolVacio() ){ return -1; } int i; while (aux != NULL){ i = isIdentificadorRepetido(valor, aux->pnodo); if (i == -3){ return -3; } aux = aux->siguiente; } return-2; } int ArbolB_Persona :: isIdentificadorRepetido(int valor, pnodopersona aux){ // me informa que el nodo ya existe o que no existe //buscamos de forma recursiva si el valor se encuentra en la estructura // si no la encuentra, retornara -2 // si encuentra el valor retornara -3 //se cumple si llegamos a una hoja if (aux == NULL){ return -2; } if (aux->Identificador == valor){ return -3; } else if (valor < aux->Identificador){ return isIdentificadorRepetido(valor, aux->Izquierda); } else if (valor > aux->Identificador){ return isIdentificadorRepetido(valor, aux->Derecha); } return-4; } int ArbolB_Persona :: isIdentificadorRepetido(int valor, PaginaNodoPersona* aux){ // me informa que el nodo ya existe o que no existe // se cumple si llegamos a una pagina hoja vacia if (aux == NULL){ return -2; } int temp; while (aux != NULL){ //aux == NULL si se acabaron los elementos de la pagina temp = isIdentificadorRepetido(valor, aux->pnodo); if (temp == -3){ return -3; } aux = aux->siguiente; } return -2; } void ArbolB_Persona :: MostrarInorde(pnodopersona aux){ //funcion recursiva auxiliar //muestras todos los nodos contenidos en la estructura //en inorden if (aux == NULL){ return; } MostrarInorde(aux->Izquierda); Mostrar(aux); MostrarInorde(aux->Derecha); } void ArbolB_Persona :: MostrarInorde(PaginaNodoPersona* aux){ //permite el paso intermediario de la pagina if (aux == NULL){ return; } while (aux != NULL){ // mostramos todos los valores de la pagina MostrarInorde(aux->pnodo); aux = aux->siguiente; } } void ArbolB_Persona :: Mostrar(){ //Muestra toda la informacion contenida en la estructura // de manera inorden PaginaNodoPersona* aux = primero; if (aux == NULL){ cout<< "\nArbol vacio"<<endl; return; } if (aux->pnodo == NULL){ cout<< "\nArbol vacio"<<endl; return; } cout << "\nMostrando todas la Informacion\n"<< endl; //abcdefg MostrarInorde(aux); } void ArbolB_Persona :: Mostrar(pnodopersona aux){ //imprime en pantalla los valores de la informacion //del nodo indicado char espacio[] = "; "; cout << aux->Identificador << espacio << aux->Nombre << " >>" << endl; } void ArbolB_Persona :: MostrarNodo(pnodopersona aux){ //Permite imprimir la informacion del nodo recibido if (aux == NULL){ cout<<"Error: Puntero nulo\n"; return; } char espacio[] = "; "; cout << aux->Identificador << espacio << aux->Nombre << " >>" << endl; } bool ArbolB_Persona :: getNodo(pnodopersona &recibir, int valor){ //retorna la ubicacion del nodo con el valor de identificacion == valor // e informa si la obtencion del mismo fue exitosa o fallida PaginaNodoPersona* aux = primero; recibir = getNodo(valor, aux); if (recibir == NULL){ return false; } return true; } pnodopersona ArbolB_Persona :: getNodo(int valor){ //funcion inicializadora de la funcion recursiva para obtener el puntero con su identificacion == valor PaginaNodoPersona* aux = primero; return getNodo(valor, aux); } pnodopersona ArbolB_Persona :: getNodo(int valor, PaginaNodoPersona* aux){ // funcion intermediaria que nos permite transcurrir por los valrores de la pagina if (aux == NULL){ return NULL; } pnodopersona temp; while (aux != NULL){ //aux == NULL solamente cuando hayamos acabado con todos los valores temp = getNodo(valor, aux->pnodo); if (temp != NULL){ return temp; } aux = aux->siguiente; } return NULL; } pnodopersona ArbolB_Persona :: getNodo(int valor, pnodopersona aux){ //funcion recursiva que busca por el puntero con su identificacion == valor pnodopersona temp = NULL; if (aux == NULL){ return NULL; } if (valor == aux->Identificador){ return aux; } temp = getNodo(valor, aux->Izquierda); if (temp != NULL){ return temp; } temp = getNodo(valor, aux->Derecha); if (temp != NULL){ return temp; } return NULL; } pnodopersona ArbolB_Persona :: getultimoNodoInsertado(){ return ultimonodo; } int ArbolB_Persona :: borrarNodo(pnodopersona nodo){ if (nodo == NULL){ return -1; } //implementacion del borrado return 1; } int ArbolB_Persona :: getIdentificador(int &valor, pnodopersona aux){ if (aux == NULL){ return -4; } valor = aux->Identificador; return 1; } int ArbolB_Persona :: getNombre(char *nombre, pnodopersona aux){ int i; if (aux == NULL){ return -4; } for (i = 0; i < sizeof(aux->Nombre); i++) { nombre[i] = aux->Nombre[i]; } return 1; } int ArbolB_Persona :: setIdentificador(int valor, pnodopersona aux){ if (aux == NULL){ return -4; } aux->Identificador = valor; return 1; } int ArbolB_Persona :: setNombre(char *nombre, pnodopersona aux){ int i; if (aux == NULL){ return -4; } for (i = 0; (i < sizeof(aux->Nombre)); i++) { // limpieamos la variable aux->Nombre[i] = '\000'; } for (i = 0; ((nombre[i]!= '\000') && (i < sizeof(aux->Nombre))); i++) { // asignamos valor aux->Nombre[i] = nombre[i]; } return 1; }
true
718406d9bf9303798875e7b33d6a56809e0eaa39
C++
DayOut/SIP_1_bidirectional_ring_list
/SIP_1_bidirectional_ring_list/SIP_1_bidirectional_ring_list.cpp
WINDOWS-1251
13,459
3.421875
3
[]
no_license
// SIP_1_bidirectional_ring_list.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <ctime> using namespace std; template <typename T> class List { private: template<typename T> struct TElem { T inf; TElem< T > *next; TElem< T > *prev; }; TElem<T> *head, *current; public: List() { head = current = NULL; } ~List() { deleteAllElements(); head = current = NULL; } void show() { if (head) { TElem<T> *cursor = head; do { cout << cursor->inf << "\t"; cursor = cursor->next; } while (cursor != head); cout << endl; } } void showReverse() { if (head) { TElem<T> *cursor = head->prev; // do { cout << cursor->inf << "\t"; cursor = cursor->prev; } while (cursor != head->prev); cout << endl; } } void addToEnd(T value) { TElem< T > *tmp = new TElem < T >; tmp->inf = value; if (head) { tmp->next = head; tmp->prev = head->prev; head->prev->next = tmp; head->prev = tmp; } else { head = tmp->next = tmp->prev = tmp; } } void addToBegin(T value) { TElem< T > *tmp = new TElem< T >; tmp->inf = value; if (head) { tmp->next = head; tmp->prev = head->prev; head->prev->next = tmp; head->prev = tmp; } else { head = tmp->next = tmp->prev = tmp; } head = tmp; } void addSorted(T value) { if (head) { TElem< T > *tmp = new TElem< T >; tmp->inf = value; TElem< T > *cursor = head; do { if (cursor->inf >= value) { break; } cursor = cursor->next; } while (cursor != head); tmp->next = cursor; tmp->prev = cursor->prev; cursor->prev->next = tmp; cursor->prev = tmp; } else { addToBegin(value); } } void deleteElement(T value) { if (head) { TElem< T > *cursor = head; do { if (cursor->inf == value) { cursor->prev->next = cursor->next; cursor->next = cursor->prev; delete cursor; break; } cursor = cursor->next; } while (cursor != head); } } void deleteCurrentElement() { TElem< T > *tmp; if (!head) { return; } else if (current == head) { tmp = head; if (head->next == head) { head = NULL; } else { head = head->next; head->prev = tmp->prev; tmp->prev->next = head; } } else { tmp = current; current = current->next; current->prev = tmp->prev; tmp->prev->next = current; } delete tmp; } bool findElement(T value) { if (!head) { return false; } TElem<T> *cursor = head; do { if (cursor->inf == value) { return true; } cursor = cursor->next; } while (cursor != head); return false; } void deleteAllElements() { if (head) { head->prev->next = NULL; do { current = head; head = head->next; delete current; } while (head); } } void sort() { /* it may helps: https://ide.geeksforgeeks.org/GWuAsj https://ideone.com/EdBruH https://github.com/ashishnith09/DSAlgosinC/blob/master/LinkedList/MergeSort%20On%20DLL%20by%20passing%20variable%20by%20refrences https://www.geeksforgeeks.org/merge-sort-for-doubly-linked-list/ https://stackoverflow.com/questions/26684481/linked-list-merge-sort MergeSort on Doubly Linked List http://www.cplusplus.com/forum/beginner/199976/ https://stackoverflow.com/questions/47170967/merge-sort-on-a-doubly-linked-list-c https://www.google.com.ua/search?ei=XRzJWt2kArOTmwXU9KbIDw&q=mergesort+double+list+c%2B%2B&oq=mergesort+double+list+c%2B%2B&gs_l=psy-ab.3...4216612.4217431.0.4227108.6.6.0.0.0.0.158.397.0j3.3.0....0...1c.1.64.psy-ab..3.0.0....0.Jws_DfvwYAA */ // head->prev->next = NULL; head->prev = NULL; // mergeSort(&head); current = head->next; TElem< T > *tmp = head; // do { if (current->next == NULL) { current->next = head; head->prev = current; } current->prev = tmp; tmp = tmp->next; current = current->next; } while (current->next != head); } void mergeSort(TElem< T > **root) { TElem< T > *list1, *list2; TElem< T > *headPtr1 = *root; if ((headPtr1 == NULL) || (headPtr1->next == NULL)) { return; } findMid(headPtr1, &list1, &list2); mergeSort(&list1); mergeSort(&list2); *root = mergeList(list1, list2); } typename TElem< T >* mergeList(TElem< T > *list1, TElem< T > *list2) { TElem< T > tempheadPtr = { 0, NULL }, *tail = &tempheadPtr; while ((list1 != NULL) && (list2 != NULL)) { TElem< T > **min = (list1->inf < list2->inf) ? &list1 : &list2; TElem< T > *next = (*min)->next; tail = tail->next = *min; *min = next; } tail->next = list1 ? list1 : list2; return tempheadPtr.next; } void findMid(TElem< T > *root, TElem< T > **list1, TElem< T > **list2) { /** * TElem< T > * */ struct TElem< T > *slow, *fast; if ((root == NULL) || (root->next == NULL)) { *list1 = root; *list2 = NULL; return; } else { /* , fast 2 slow, slow 2 fast ( fast == NULL, slow ) */ slow = root; fast = root->next; while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } *list1 = root; *list2 = slow->next; slow->next = NULL; } } bool operator!() { // -> , true return (head) ? false : true; //() ? _ : _; /* if(head != NULL) { return false; } return true; */ } void operator++() { if (!head) return; if (current) // current { current = current->next; } else { current = head; // current - } // current = (current) ? current->next : head; } void operator --() { if (!head) return; if (current != NULL) // current { current = current->prev; } else { current = head; // current - } //current = (current) ? current->prev : head; } List< T >& operator=(List< T >& right) { if (this == &right) // { return *this; } TElem< T > *rightHead = right.getHead(); TElem< T > *rightCurrent = rightHead; TElem< T > *tmp = head; // while (tmp || rightCurrent) { if (rightCurrent && tmp) { tmp->inf = rightCurrent->inf; } else if (tmp && !rightCurrent) { current = tmp; tmp = tmp->prev; deleteCurrentElement(); } else if (!tmp && rightCurrent) { addToEnd(rightCurrent->inf); } if(tmp) tmp = (tmp->next == head) ? NULL : tmp->next; if(rightCurrent) rightCurrent = (rightCurrent->next == rightHead) ? NULL : rightCurrent->next; } } void sortCurrentElement() { // if (!head) { return; } // "" if (!current) { current = head; } else if (current == head && current->inf <= head->next->inf) { return; } else if (current == head && current->inf > head->next->inf) { head = head->next; head->prev = current->prev; head->prev->next = current->next; } TElem< T > *tmp = head; while (current->inf > tmp->inf) { tmp = tmp->next; if (tmp == head) { break; } } current->next = tmp->prev->next; current->prev = tmp->prev; tmp->prev->next = current; tmp->prev = current; } void setCurrentToHead() { if (head) current = head; } T getCopyInf() { if (!current) { current = head; } return current->inf; } T& getPointerInf() { if (!current) { current = head; } return current->inf; } private: TElem< T >* getHead() { return head; } }; int main() { setlocale(LC_ALL, "rus"); srand(time(NULL)); List<int> list; if (!list) { cout << "O_o \n"; } for (int i = 0; i < 20000; i++) { list.addToEnd(rand() % 1000000); } list.addToBegin(2); //list.show(); list.deleteElement(0); //list.addToEnd() //list.show(); list.findElement(4); list.findElement(11); //list.show(); unsigned int start = clock(); list.sort(); unsigned int end = clock(); cout << " : " << end - start << " ms\n"; /*list.addSorted(9); list.addSorted(8); list.show(); cout << endl; list.showReverse(); List<int> list2; cout << "list2: \n"; list2 = list; list.deleteCurrentElement(); list2.show(); cout << endl; list2.showReverse(); cout << "------------------ \n list: \n"; list.show(); cout << "list2:" << endl; list2 = list; list2.show(); cout << "------------------ \n list: \n"; list.addToEnd(59); list.show(); cout << "list2:" << endl; list2 = list; list2.show(); cout << "------------------ \n list: \n"; list.addToBegin(10); list.show(); list.setCurrentToHead(); list.sortCurrentElement(); --list; list.show(); cout << endl; int a = list.getCopyInf(); cout << "\n" << a << endl;*/ system("pause"); return 0; }
true
6af4fb0e0ec985a9c2e552ecd56c422333b0b96c
C++
ZhuoerFeng/2019-OOP
/PA5/problem_32/pizza.h
UTF-8
1,898
3.53125
4
[]
no_license
#pragma once #include <cstring> #include <iostream> #include "plate.h" class Pizza { protected: std::string name; int ketchup, cheese; bool cooked; bool cutted; Plate *plate; public: Pizza(const std::string &name, int ketchup, int cheese) : name(name), ketchup(ketchup), cheese(cheese), cooked(false), cutted(false), plate(nullptr) {} virtual void cook() { this->cooked = true; } virtual void cut() { this->cutted = true; } virtual void put_on(Plate *plate) { this->plate = plate; plate->hold_pizza(this); } virtual void eat() { std::cout << "Eating " << this->name << " ("; float total = (this->ketchup + this->cheese) / 100.0f; if (total == 0.0f) total = 1.0f; std::cout << static_cast<int>(round(this->ketchup / total)) << "% ketchup"; std::cout << " and "; std::cout << static_cast<int>(round(this->cheese / total)) << "% cheese"; if (this->cooked || this->cutted) { std::cout << " that is"; if (this->cooked) std::cout << " cooked"; if (this->cooked && this->cutted) std::cout << " and"; if (this->cutted) std::cout << " cutted"; } std::cout << ") from " << this->plate->id() << " plate."; std::cout << std::endl; } virtual ~Pizza() { this->plate->hold_pizza(nullptr); std::cout << "Washed " << this->plate->id() << " plate." << std::endl; } }; class Seafood_Pizza : public Pizza { Seafood_Pizza() : Pizza("Seafood Pizza", 30, 90) {} }; class Beef_Pizza : public Pizza { Beef_Pizza() : Pizza("Beef Pizza", 20, 40) {} }; class Fruit_Pizza : public Pizza { Fruit_Pizza() : Pizza("Fruit Pizza", 0, 0) {} }; class Sausage_Pizza : public Pizza { Sausage_Pizza() : Pizza("Sausage Pizza", 40, 20) {} }; class Tomato_Pizza : public Pizza { Tomato_Pizza() : Pizza("Tomato Pizza", 20, 0) {} }; class Cheese_Pizza : public Pizza { Cheese_Pizza() : Pizza("Cheese Pizza", 0, 20) {} };
true
96f7fceaaadcb36848fe2859b91512aa229e89fd
C++
Sara3/-prefix-notation-to-infix-notation.-
/Stackfunctions.h
UTF-8
964
2.875
3
[]
no_license
//---------------------------------------------------------------------------- // File -------- stackfunctions.h // Programmer -- Sabera Daqiq // // This file contains declarations for the class stingstack and for toinfix function // functions. See the accompanying implementation file for details. //---------------------------------------------------------------------------- #include <iostream> #include <string> using namespace std; #ifndef STACKFUNCTIONS_H #define STACKFUNCTIONS_H const int CAPACITY=100; class stringstack{ private: string list[CAPACITY]; int size; public: void push(string newitem); void show()const; string pop(); bool isEmpty()const; bool isFull() const; string peek () const; stringstack (); int getsize() const; bool isOperator(char item) const; }; string toinfix(string prefix); #endif
true
36eb63dfe052526e41acf283616bd86e4ec764db
C++
Hotanmes/PAT
/PAT_advanced/1138.cpp
UTF-8
955
3.140625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<vector> using namespace std; vector<int> pre,in; bool flag = false; void postorder(int prel, int inl, int inr)//参数意义分别为先序遍历序列中根结点下标、中序遍历序列中最左端结点下标和最右端结点下标 { if (inl > inr || flag == true) return; int i = inl; while (in[i] != pre[prel])//找出根结点在中序遍历序列中的下标 ++i; postorder(prel + 1, inl, i - 1);//遍历左子树 postorder(prel + i - inl + 1, i + 1, inr);//遍历右子树,i-inl+1代表左子树结点个数 if (flag == false) { printf("%d\n", in[i]);//最后的i代表后序遍历序列首结点在中序遍历序列中的下标 flag = true; } } int main() { int n; cin >> n; pre.resize(n); in.resize(n); for (int i = 0; i < n; ++i) { scanf("%d", &pre[i]); } for (int i = 0; i < n; ++i) { scanf("%d", &in[i]); } postorder(0, 0, n - 1); return 0; }
true
f8280e4aa0feca3ba90605c5505a0e41bd58ebde
C++
farabiahmed/MachineLearningFramework
/include/Representations/RepresentationUDP.hpp
UTF-8
1,512
2.546875
3
[]
no_license
/* * RepresentationUDP.hpp * * Created on: May 28, 2017 * Author: farabiahmed */ #ifndef REPRESENTATIONS_REPRESENTATIONUDP_HPP_ #define REPRESENTATIONS_REPRESENTATIONUDP_HPP_ #include <cmath> #include <iomanip> #include <cassert> #include <fstream> #include <iostream> #include <string> #include <vector> #include "Environments/Environment.hpp" #include "Representations/Representation.hpp" #include "Miscellaneous/ConfigParser.hpp" #include "Communication/UDP.hpp" #include "Miscellaneous/Convert.hpp" /* * */ class RepresentationUDP : public Representation { public: RepresentationUDP(const Environment& env, const ConfigParser& cfg); virtual ~RepresentationUDP(); pair<int,double> Get_Greedy_Pair(const SmartVector& state) const; SmartVector Get_Policy(const SmartVector& state) const; double Get_Value(const SmartVector& state, const SmartVector& action) const; void Set_Value(const SmartVector& state, const SmartVector& action, double value); void Add_Experience(const SmartVector& state, const SmartVector& action, const SmartVector& nextState, const double& reward, const int status); void Print_Value(); string Name; ///< It stores the name of representation to increase readability and awareness. ///< Such as StateActionValue, GaussianRBF etc. protected: string Vector_ToString(const SmartVector& vec) const; UDP udpsocket; private: string host_ip; int port_tx; int port_rx; double gamma; }; #endif /* REPRESENTATIONS_REPRESENTATIONUDP_HPP_ */
true
9f8b61352f39e59650f315d823b756bf1c361bc0
C++
MQuy/mlang
/mc/src/llvm/const_eval.h
UTF-8
3,140
2.703125
3
[]
no_license
#ifndef LLVM_CONST_EVAL_H #define LLVM_CONST_EVAL_H 1 #include <memory> #include "ast/parser.h" #include "semantic/translation_unit.h" class IR; class ConstExprEval : NodeVisitor { public: ConstExprEval(IR *ir, std::shared_ptr<ExprAST> expr) : ir(ir) , expr(expr) { } int eval(); void *visit_literal_expr(LiteralExprAST<int> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<long> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<long long> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<unsigned int> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<unsigned long> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<unsigned long long> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<float> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<double> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<long double> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<unsigned char> *expr, void *data = nullptr); void *visit_literal_expr(LiteralExprAST<std::string> *expr, void *data = nullptr); void *visit_identifier_expr(IdentifierExprAST *expr, void *data = nullptr); void *visit_binary_expr(BinaryExprAST *expr, void *data = nullptr); void *visit_unary_expr(UnaryExprAST *expr, void *data = nullptr); void *visit_tenary_expr(TenaryExprAST *expr, void *data = nullptr); void *visit_member_access_expr(MemberAccessExprAST *expr, void *data = nullptr); void *visit_function_call_expr(FunctionCallExprAST *expr, void *data = nullptr); void *visit_typecast_expr(TypeCastExprAST *expr, void *data = nullptr); void *visit_sizeof_expr(SizeOfExprAST *expr, void *data = nullptr); void *visit_alignof_expr(AlignOfExprAST *expr, void *data = nullptr); void *visit_initializer_expr(InitializerExprAST *expr, void *data = nullptr); void *visit_label_stmt(LabelStmtAST *stmt, void *data = nullptr); void *visit_case_stmt(CaseStmtAST *stmt, void *data = nullptr); void *visit_default_stmt(DefaultStmtAST *stmt, void *data = nullptr); void *visit_expr_stmt(ExprStmtAST *stmt, void *data = nullptr); void *visit_compound_stmt(CompoundStmtAST *stmt, void *data = nullptr); void *visit_if_stmt(IfStmtAST *stmt, void *data = nullptr); void *visit_switch_stmt(SwitchStmtAST *stmt, void *data = nullptr); void *visit_for_stmt(ForStmtAST *stmt, void *data = nullptr); void *visit_while_stmt(WhileStmtAST *stmt, void *data = nullptr); void *visit_dowhile_stmt(DoWhileStmtAST *stmt, void *data = nullptr); void *visit_jump_stmt(JumpStmtAST *stmt, void *data = nullptr); void *visit_continue_stmt(ContinueStmtAST *stmt, void *data = nullptr); void *visit_break_stmt(BreakStmtAST *stmt, void *data = nullptr); void *visit_return_stmt(ReturnStmtAST *stmt, void *data = nullptr); void *visit_function_definition(FunctionDefinitionAST *stmt, void *data = nullptr); void *visit_declaration(DeclarationAST *stmt, void *data = nullptr); private: TranslationUnit translation_unit; IR *ir; std::shared_ptr<ExprAST> expr; }; #endif
true
c676ac1d41ac63b83eb7edee9864fffa82774705
C++
red-rick/CFundamentals
/Chapter_9/Exercise_1/golf.cpp
UTF-8
510
3.078125
3
[]
no_license
#include<iostream> #include"golf.h" void setgolf(golf & g, const char * name, int hc) { strncpy(g.fullname, name, Len); g.handicap = hc; } int setgolf(golf & g) { std::cout << "Enter Full Name: "; std::cin.getline(g.fullname, Len); if (strlen(g.fullname) == 0) return 0; std::cout << "Enter handicap: "; (std::cin >> g.handicap).get(); return 1; } void handicap(golf & g, int hc) { g.handicap = hc; } void showgolf(const golf & g) { std::cout << g.fullname << ", " << g.handicap << std::endl; }
true
1efefdc0d60e5feb481b753674c8d8bfcae8c0bf
C++
gviau/sketch-stl
/src/sketch_string.cpp
UTF-8
18,978
3.15625
3
[ "MIT" ]
permissive
#include "sketch_string.h" #include <math.h> namespace SketchStl { string::string() : data_(nullptr), length_(0), capacity_(1) { data_ = (char*)malloc(1); data_[length_] = '\0'; } string::string(const string& str) { length_ = str.length_; capacity_ = str.capacity_; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = str.data_[i]; } data_[length_] = '\0'; } string::string(const string& str, size_t pos, size_t len) : data_(nullptr), length_(len), capacity_(len) { if (len == npos) { length_ = str.length_ - pos; capacity_ = length_; } capacity_ += 1; data_ = (char*)malloc(capacity_); size_t idx = pos; for (size_t i = 0; i < length_; i++) { data_[i] = str[pos++]; } data_[length_] = '\0'; } string::string(const char* s) : data_(nullptr), length_(0), capacity_(0) { if (s == nullptr) { return; } const char* begin = s; while (*begin++) { length_ += 1; capacity_ += 1; } capacity_ += 1; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = *s++; } data_[length_] = '\0'; } string::string(const char* s, size_t n) : data_(nullptr), length_(n), capacity_(n) { capacity_ += 1; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = *s++; } data_[length_] = '\0'; } string::string(size_t n, char c) : data_(nullptr), length_(n), capacity_(n) { capacity_ += 1; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = c; } data_[length_] = '\0'; } string::~string() { free(data_); } string& string::operator=(const string& str) { if (&str != this) { free(data_); length_ = str.length_; capacity_ = str.capacity_; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = str.data_[i]; } data_[length_] = '\0'; } return *this; } string& string::operator=(const char* s) { if (s != nullptr) { free(data_); length_ = 0; capacity_ = 0; const char* begin = s; while (*begin++) { length_ += 1; capacity_ += 1; } capacity_ += 1; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < length_; i++) { data_[i] = *s++; } data_[length_] = '\0'; } return *this; } string& string::operator=(char c) { free(data_); if (c == '\0') { length_ = 0; capacity_ = 1; } else { length_ = 1; capacity_ = 2; } data_ = (char*)malloc(capacity_); if (length_ > 0) { data_[0] = c; } data_[length_] = '\0'; return *this; } size_t string::size() const { return length_; } size_t string::length() const { return length_; } size_t string::max_size() const { return -1; } void string::resize(size_t n) { if (n != length_) { char* newData = (char*)malloc(n + 1); size_t newLength = 0; if (n < length_) { newLength = n; } else { newLength = length_; } for (size_t i = 0; i < newLength; i++) { newData[i] = data_[i]; } newData[newLength] = '\0'; free(data_); data_ = newData; length_ = n; capacity_ = length_ + 1; } } void string::resize(size_t n, char c) { size_t oldLength = length_; resize(n); if (oldLength < length_) { for (size_t i = oldLength; i < length_; i++) { data_[i] = c; } data_[length_] = '\0'; } } size_t string::capacity() const { return capacity_; } void string::reserve(size_t n) { if (n > (capacity_ - 1)) { char* newData = (char*)malloc(n + 1); for (size_t i = 0; i < length_; i++) { newData[i] = data_[i]; } newData[length_] = '\0'; free(data_); data_ = newData; capacity_ = n + 1; } } void string::clear() { free(data_); data_ = (char*)malloc(1); data_[0] = '\0'; length_ = 0; capacity_ = 1; } bool string::empty() const { return length_ == 0; } char& string::operator[](size_t pos) { assert(pos < length_); return data_[pos]; } const char& string::operator[](size_t pos) const { assert(pos < length_); return data_[pos]; } char& string::at(size_t pos) { assert(pos < length_); return data_[pos]; } const char& string::at(size_t pos) const { assert(pos < length_); return data_[pos]; } string& string::operator+=(const string& str) { size_t newSize = length_ + str.length_; if (newSize > (capacity_ - 1)) { char* newData = (char*)malloc(newSize + 1); for (size_t i = 0; i < length_; i++) { newData[i] = data_[i]; } free(data_); data_ = newData; } size_t idx = 0; for (size_t i = length_; i < newSize; i++) { data_[i] = str.data_[idx++]; } data_[newSize] = '\0'; length_ = newSize; capacity_ = length_ + 1; return *this; } string& string::operator+=(const char* s) { return (*this) += string(s); } string& string::operator+=(char c) { if (length_ + 1 > (capacity_ - 1)) { char* newData = (char*)malloc(capacity_ + 1); for (size_t i = 0; i < length_; i++) { newData[i] = data_[i]; } free(data_); data_ = newData; } data_[length_] = c; data_[length_ + 1] = '\0'; length_ += 1; capacity_ += 1; return *this; } string& string::append(const string& str) { return (*this += str); } string& string::append(const string& str, size_t subpos, size_t sublen) { return (*this += str.substr(subpos, sublen)); } string& string::append(const char* s) { return (*this += s); } string& string::append(const char* s, size_t n) { string str(s, n); return (*this += str); } string& string::append(size_t n, char c) { string str(n, c); return (*this += str); } void string::push_back(char c) { *this += c; } string& string::assign(const string& str) { return (*this = str); } string& string::assign(const string& str, size_t subpos, size_t sublen) { return (*this = str.substr(subpos, sublen)); } string& string::assign(const char* s) { return (*this = s); } string& string::assign(const char* s, size_t n) { string str(s, n); return (*this = str); } string& string::assign(size_t n, char c) { string str(n, c); return (*this = str); } string& string::insert(size_t pos, const string& str) { size_t newLength = length_ + str.length_; if (newLength > (capacity_ - 1)) { // Allocate enough space and insert the string char* newData = (char*)malloc(newLength + 1); size_t endIdx = 0; for (; endIdx < pos; endIdx++) { newData[endIdx] = data_[endIdx]; } size_t endPos = pos + str.length_; size_t idx = 0; for (size_t i = pos; i < endPos; i++) { newData[i] = str.data_[idx++]; } for (size_t i = endPos; i < newLength; i++) { newData[i] = data_[endIdx++]; } free(data_); data_ = newData; capacity_ = newLength + 1; data_[newLength] = '\0'; } else { char* buffer = (char*)malloc(length_ - pos); // Start by copying the portion after the insertion position size_t idx = 0; for (size_t i = pos; i < length_; i++) { buffer[idx++] = data_[i]; } // Overwrite the part that we just copied with the string to insert and append back the buffer idx = 0; size_t endPos = pos + str.length_; for (size_t i = pos; i < endPos; i++) { data_[i] = str.data_[idx++]; } idx = 0; for (size_t i = endPos; i < newLength; i++) { data_[i] = buffer[idx++]; } free(buffer); } length_ = newLength; return *this; } string& string::insert(size_t pos, const string& str, size_t subpos, size_t sublen) { if (str == "") { return *this; } return insert(pos, str.substr(subpos, sublen)); } string& string::insert(size_t pos, const char* s) { string str(s); return insert(pos, str); } string& string::insert(size_t pos, const char* s, size_t n) { string str(s, n); return insert(pos, str); } string& string::insert(size_t pos, size_t n, char c) { string str(n, c); return insert(pos, str); } string& string::erase(size_t pos, size_t len) { if (pos == 0 && len == npos) { clear(); } else { assert(pos < length_); // Copy the left part of the buffer char* leftBuffer = (char*)malloc(pos); for (size_t i = 0; i < pos; i++) { leftBuffer[i] = data_[i]; } // Copy the right part of the buffer size_t rightSize = length_ - pos - len; char* rightBuffer = (char*)malloc(rightSize); size_t idx = pos + len; for (size_t i = 0; i < rightSize; i++) { rightBuffer[i] = data_[idx++]; } // Resize and concatenate the two buffers free(data_); length_ = pos + rightSize; capacity_ = length_ + 1; data_ = (char*)malloc(capacity_); for (size_t i = 0; i < pos; i++) { data_[i] = leftBuffer[i]; } idx = pos; for (size_t i = 0; i < rightSize; i++) { data_[idx++] = rightBuffer[i]; } data_[length_] = '\0'; free(leftBuffer); free(rightBuffer); } return *this; } string& string::replace(size_t pos, size_t len, const string& str) { assert(pos < length_); // We need a larger buffer if (len > (length_ - pos)) { len = length_ - pos; } size_t newSize = length_ - len + str.length_; if (newSize > (capacity_ - 1)) { char* newData = (char*)malloc(newSize + 1); for (size_t i = 0; i < pos; i++) { newData[i] = data_[i]; } size_t idx = 0; size_t endPos = pos + str.length_; for (size_t i = pos; i < endPos; i++) { newData[i] = str.data_[idx++]; } size_t rightPos = pos + len; for (size_t i = endPos; i < newSize; i++) { newData[i] = data_[rightPos++]; } length_ = newSize; capacity_ = newSize + 1; free(data_); data_ = newData; } else { size_t rightSize = length_ - pos - len; char* rightBuffer = (char*)malloc(rightSize); size_t idx = 0; size_t startPos = pos + len; for (size_t i = startPos; i < length_; i++) { rightBuffer[idx++] = data_[i]; } idx = 0; startPos = pos + str.length_; for (size_t i = pos; i < startPos; i++) { data_[i] = str.data_[idx++]; } idx = 0; for (size_t i = startPos; i < newSize; i++) { data_[i] = rightBuffer[idx++]; } length_ = newSize; free(rightBuffer); } data_[length_] = '\0'; return *this; } string& string::replace(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) { return replace(pos, len, str.substr(subpos, sublen)); } string& string::replace(size_t pos, size_t len, const char* s) { return replace(pos, len, string(s)); } string& string::replace(size_t pos, size_t len, const char* s, size_t n) { return replace(pos, len, string(s, n)); } string& string::replace(size_t pos, size_t len, size_t n, char c) { return replace(pos, len, string(n, c)); } void string::swap(string& str) { char* tmpBuffer = data_; size_t tmpLength = length_; size_t tmpCapacity = capacity_; data_ = str.data_; length_ = str.length_; capacity_ = str.capacity_; str.data_ = tmpBuffer; str.length_ = tmpLength; str.capacity_ = tmpCapacity; } const char* string::c_str() const { return data_; } const char* string::data() const { return data_; } size_t string::copy(char* s, size_t len, size_t pos) { assert(pos < length_); size_t endPos = pos + len; if (endPos > length_) { endPos = length_; } size_t idx = 0; for (size_t i = pos; i < endPos; i++) { s[idx++] = data_[i]; } return idx; } string string::substr(size_t pos, size_t len) const { if (length_ == 0) { return ""; } assert(pos < length_); if (len == npos) { len = length_ - pos; } size_t endPos = pos + len; if (endPos > length_) { endPos = length_; } size_t size = endPos - pos; string substring; substring.resize(size); size_t idx = 0; for (size_t i = pos; i < endPos; i++) { substring.data_[idx++] = data_[i]; } substring.data_[substring.length_] = '\0'; return substring; } size_t string::find(const string& str, size_t pos) const { if (str.length_ == 0) { return pos; } if (str.length_ + pos > length_) { return npos; } if (pos == 0 && str.length_ == length_) { return (compare(str) == 0) ? 0 : npos; } // KMP algorithm as described at http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm int* table = (int*)malloc(str.length_ * sizeof(int)); table[0] = -1; table[1] = 0; // Table creation size_t position = 2; int cnd = 0; while (position < str.length_) { if (str[position - 1] == str[cnd]) { cnd += 1; table[position] = cnd; position += 1; } else if (cnd > 0) { cnd = table[cnd]; } else { table[position] = 0; position += 1; } } // String matching size_t m = pos, i = 0; while (m + i < length_) { if (str[i] == data_[m + i]) { if (i == str.length_ - 1) { free(table); return m; } i += 1; } else { if (table[i] > -1) { m = m + i - table[i]; i = table[i]; } else { i = 0; m += 1; } } } free(table); return npos; } size_t string::find(const char* s, size_t pos) const { return find(string(s), pos); } size_t string::find(const char* s, size_t pos, size_t n) const { return find(string(s, n), pos); } size_t string::find(char c, size_t pos) const { if (pos >= length_) { return npos; } if (length_ == 0) { return npos; } for (size_t i = pos; i < length_; i++) { if (c == data_[i]) { return i; } } return npos; } int string::compare(const string& str) const { if (length_ < str.length_) { return -1; } else if (length_ > str.length_) { return 1; } int comp = 0; for (size_t i = 0; i < length_; i++) { comp = data_[i] - str.data_[i]; if (comp < 0) { return -1; } else if (comp > 0) { return 1; } } return 0; } int string::compare(size_t pos, size_t len, const string& str) const { return substr(pos, len).compare(str); } int string::compare(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const { return compare(pos, len, str.substr(subpos, sublen)); } int string::compare(const char* s) const { return compare(string(s)); } int string::compare(size_t pos, size_t len, const char* s) const { return substr(pos, len).compare(s); } int string::compare(size_t pos, size_t len, const char* s, size_t n) const { return substr(pos, len).compare(string(s, n)); } string operator+(const string& lhs, const string& rhs) { size_t newSize = lhs.length_ + rhs.length_; string result; result.reserve(newSize); for (size_t i = 0; i < lhs.length_; i++) { result.data_[i] = lhs.data_[i]; } size_t idx = 0; for (size_t i = lhs.length_; i < newSize; i++) { result.data_[i] = rhs.data_[idx++]; } result.data_[newSize] = '\0'; result.length_ = newSize; return result; } string operator+(const string& lhs, const char* rhs) { return lhs + string(rhs); } string operator+(const char* lhs, const string& rhs) { return string(lhs) + rhs; } string operator+(const string& lhs, char rhs) { size_t newSize = lhs.length_ + 1; string result; result.reserve(newSize); for (size_t i = 0; i < lhs.length_; i++) { result.data_[i] = lhs.data_[i]; } result.data_[lhs.length_] = rhs; result.data_[newSize] = '\0'; result.length_ = newSize; return result; } string operator+(char lhs, const string& rhs) { size_t newSize = rhs.length_ + 1; string result; result.reserve(newSize); result.data_[0] = lhs; for (size_t i = 0; i < rhs.length_; i++) { result.data_[i + 1] = rhs.data_[i]; } result.data_[newSize] = '\0'; result.length_ = newSize; return result; } bool operator==(const string& lhs, const string& rhs) { return lhs.compare(rhs) == 0; } bool operator==(const string& lhs, const char* rhs) { return lhs.compare(rhs) == 0; } bool operator==(const char* lhs, const string& rhs) { return rhs.compare(lhs) == 0; } bool operator!=(const string& lhs, const string& rhs) { return lhs.compare(rhs) != 0; } bool operator!=(const string& lhs, const char* rhs) { return lhs.compare(rhs) != 0; } bool operator!=(const char* lhs, const string& rhs) { return rhs.compare(lhs) != 0; } bool operator<(const string& lhs, const string& rhs) { return lhs.compare(rhs) < 0; } bool operator<(const string& lhs, const char* rhs) { return lhs.compare(rhs) < 0; } bool operator<(const char* lhs, const string& rhs) { return rhs.compare(lhs) > 0; } bool operator<=(const string& lhs, const string& rhs) { return lhs.compare(rhs) <= 0; } bool operator<=(const string& lhs, const char* rhs) { return lhs.compare(rhs) <= 0; } bool operator<=(const char* lhs, const string& rhs) { return rhs.compare(lhs)>= 0; } bool operator>(const string& lhs, const string& rhs) { return lhs.compare(rhs) > 0; } bool operator>(const string& lhs, const char* rhs) { return lhs.compare(rhs) > 0; } bool operator>(const char* lhs, const string& rhs) { return rhs.compare(lhs) < 0; } bool operator>=(const string& lhs, const string& rhs) { return lhs.compare(rhs) >= 0; } bool operator>=(const string& lhs, const char* rhs) { return lhs.compare(rhs) >= 0; } bool operator>=(const char* lhs, const string& rhs) { return rhs.compare(lhs) <= 0; } }
true
1cb0b0fc3be00d85f73629a1045d53878d19d454
C++
longruiliu/Personal-Work
/leetcode/level_order_one_bt.cpp
UTF-8
2,759
3.5
4
[]
no_license
#include<iostream> #include<stdlib.h> #include<vector> using namespace std; typedef struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }*Tree; class Solution { public: vector<vector<int> > levelOrder(TreeNode *root) { vector<vector<int> > result,l_child,r_child,all_child; vector<int> root_value; if (NULL == root) return result; if (NULL == root->left && NULL == root->right) { root_value.push_back(root->val); result.push_back(root_value); return result; } root_value.push_back(root->val); result.push_back(root_value); l_child = levelOrder(root->left); r_child = levelOrder(root->right); all_child = merge_all(l_child,r_child); for (int i = 0;i < all_child.size();i++) result.push_back(all_child[i]); return result; } vector<vector<int> > merge_all(vector<vector<int> > left,vector<vector<int> > right) { if (left.empty()) return right; if (right.empty()) return left; int left_length = left.size(); int right_length = right.size(); if (left_length >= right_length) { for (int i = 0;i < right_length;i++) for (int j = 0; j < right[i].size();j++) left[i].push_back(right[i][j]); } else { for (int i = 0;i < left_length;i++) for (int j = 0; j < right[i].size();j++) left[i].push_back(right[i][j]); for (int i = left_length;i < right_length;i++) left.push_back(right[i]); } return left; } }; void build_tree(Tree &T) { int data; cin>>data; if (-1 != data) { Tree tmp = new TreeNode(data); T = tmp; build_tree(T->left); build_tree(T->right); } } void print_tree(Tree &root) { if (NULL != root) { cout<<root->val<<" "; print_tree(root->left); print_tree(root->right); } } int main() { Tree T = NULL; build_tree(T); print_tree(T); cout<<endl; Solution result; vector<vector<int> > data = result.levelOrder(T); if (!data.empty()) { for (int i = 0;i < data.size();i++) { for (int j = 0;j < data[i].size();j++) cout<<data[i][j]<<" "; cout<<endl; } } return 0; }
true
3b816cdc94e33268141a224e51261b7518754681
C++
Turtlesoup/SuperRobotHunt
/LDGame/BezierCurve.cpp
UTF-8
928
2.984375
3
[]
no_license
#include "BezierCurve.h" #include "MathHelper.h" BezierCurve::BezierCurve() : _p1(Vector2<float>()), _p2(Vector2<float>()), _p3(Vector2<float>()) { } BezierCurve::BezierCurve(Vector2<float> p1, Vector2<float> p2, Vector2<float> p3) : _p1(p1), _p2(p2), _p3(p3) { } BezierCurve::~BezierCurve() { } Vector2<float> BezierCurve::getPoint(float interpolationValue) { if(interpolationValue < 0) { interpolationValue = 0; } else if(interpolationValue > 1) { interpolationValue = 1; } Vector2<float> a = MathHelper::lerpVector2f(interpolationValue, _p1, _p2); Vector2<float> b = MathHelper::lerpVector2f(interpolationValue, _p2, _p3); return MathHelper::lerpVector2f(interpolationValue, a, b); } Vector2<float> &BezierCurve::getP1() { return _p1; } Vector2<float> &BezierCurve::getP2() { return _p2; } Vector2<float> &BezierCurve::getP3() { return _p3; }
true
b7cb36ea92e7049de444df4dd3eef01a6944149f
C++
SeoRiel/SortList
/SortList/SquentialSort.cpp
WINDOWS-1252
294
3.34375
3
[]
no_license
#include "SortHeader.h" // (Squential Sort) // TC : O(n^2) // SC : O(n) void SquentialSort(int input[], int count) { for (int i = 0; i < count - 1; ++i) { for (int j = i + 1; j < count; ++j) { if (input[i] < input[j]) { Swap(input[i], input[j]); } } } }
true
d4a378aabae89b23b6432685c15524ba3e900488
C++
thomasvangoidsenhoven/Raytracer-3D-Cplus
/raytracer/raytracer/imaging/bitmap.cpp
UTF-8
1,946
3.3125
3
[]
no_license
#include "imaging/bitmap.h" #include <algorithm> #include <assert.h> using namespace imaging; imaging::Bitmap::Bitmap(unsigned width, unsigned height) : m_pixels(width, height, colors::black()) { // NOP } unsigned imaging::Bitmap::width() const { return m_pixels.width(); } unsigned imaging::Bitmap::height() const { return m_pixels.height(); } bool imaging::Bitmap::is_inside(const Position2D& p) const { return p.x < width() && p.y < height(); } Color& imaging::Bitmap::operator[](const Position2D& p) { assert(is_inside(p)); return m_pixels[p]; } const Color& imaging::Bitmap::operator[](const Position2D& p) const { assert(is_inside(p)); return m_pixels[p]; } void imaging::Bitmap::clear(const Color& Color) { for_each_position([this, &Color](const Position2D& p) { m_pixels[p] = Color; }); } void imaging::Bitmap::for_each_position(std::function<void(const Position2D&)> callback) const { m_pixels.for_each_position(callback); } Bitmap& imaging::Bitmap::operator +=(const Bitmap& bitmap) { assert(width() == bitmap.width()); assert(height() == bitmap.height()); for_each_position([this, &bitmap](const Position2D& p) { (*this)[p] += bitmap[p]; }); return *this; } Bitmap& imaging::Bitmap::operator -=(const Bitmap& bitmap) { assert(width() == bitmap.width()); assert(height() == bitmap.height()); for_each_position([this, &bitmap](const Position2D& p) { (*this)[p] -= bitmap[p]; }); return *this; } Bitmap& imaging::Bitmap::operator *=(double constant) { for_each_position([this, constant](const Position2D& p) { (*this)[p] *= constant; }); return *this; } Bitmap& imaging::Bitmap::operator /=(double constant) { return *this *= 1 / constant; } void imaging::Bitmap::invert() { for_each_position([this](const Position2D& position) { (*this)[position].invert(); }); }
true
3aff56b309a765ce71a25feb0a121d12099cecb9
C++
cazBlue/AIEYearOneProjects
/Assessment One & Two/source/enemy.cpp
UTF-8
2,612
3.078125
3
[]
no_license
#include "enemy.h" #include "character.h" #include <math.h> //Character::Character(Level *level, DrawEngine *de, int s_index, float x, float y, int lives, char u, char d, char l, char r) : Sprite(level, de, s_index, x, y, lives) Enemy::Enemy(Level *lvl, DrawEngine *de, int s_index, float x, float y, int i_lives) : Sprite(lvl, de, s_index, x, y, i_lives) { goal = 0; classID = ENEMY_CLASSID; //set in Sprite.h } bool Enemy::move(float x, float y) { int xpos = (int)(pos.x + x); int ypos = (int)(pos.y + y); if(isValidLevelMove(xpos, ypos)) { list <Sprite *>::iterator Iter; //make sure we don't run into any other enemies for (Iter = level->npc.begin(); Iter != level->npc.end(); Iter++) { if((*Iter) !=this && (int)(*Iter)->getX() == xpos && (int)(*Iter)->getY() == ypos) //don't check for this asset in the list { return false; } } //erase sprite at current location erase(pos.x, pos.y); //move the sprite to the new cords pos.x += x; pos.y += y; //set the facing direction facingDirection.x = x; facingDirection.y = y; //draw sprite at new location draw(pos.x, pos.y); if(goal != 0) //make sure there is a goal to check for (evil monkey mode has the player as a goal { if ((int)goal->getX() == xpos && (int)goal->getY() == ypos) //check if the enemy has hit the player, take a life if so goal->addLives(-1); } return true; } return false; } void Enemy::idleUpdate(void) { if(goal) simulateAI(); } void Enemy::addGoal(Character *g) { goal = g; } void Enemy::simulateAI(void) { vector goal_pos = goal->getPosition(); //the goal is the current position of the player vector direction; //empty direction direction.x = goal_pos.x - pos.x; //get the x vector of direction to the goal (player) direction.y = goal_pos.y - pos.y; //get the y vector of direction to the goal (player) float mag = sqrt(direction.x * direction.x + direction.y * direction.y); //get the length of the current pos to the goal pos as a magnitude (speed) direction.x = direction.x / (mag * 5); //temper the magnitude (speed) of the move by increasing the number. Effectively slows the enemies down. direction.y = direction.y / (mag * 5); // " " //first try and move in the desired direction //if this direction is invalid try and move in any other direction at random if(!move(direction.x, direction.y)) { while(!move(float(rand() % 3 - 1), float(rand() % 3 - 1))) //tries to move in any direction until succesfull, fairly verbose method { //no function needed, it all happens in the while loop itself } } }
true
d4bee37bd8d8d1b24f1f2bcb46d2efa02f257142
C++
amkashyap1220/CSCI-241-Intermediate-Programming
/Assign5/account.cpp
UTF-8
1,983
3.9375
4
[]
no_license
/** * @file account.cpp * @author Alexander Kashyap (z1926618@students.niu.edu) * @date 2021-02-18 * * Assignment 5 * Course: CSCI 241 * Section: 1 */ #include <iostream> #include <iomanip> #include "account.h" using namespace std; /** * @brief Return the account number for an account * * @return const char* the account number */ const char *account::get_account_number() const { return this->account_number; } /** * @brief Return the account balance for an account * * @return double the account balance */ double account::get_account_balance() const { return this->account_balance; } /** * @brief take a double deposit amount and add it to the balance for the bank account * * @param deposit_amount the amount to be deposited */ void account::process_deposit(double deposit_amount) { // add deposit_amount this->account_balance += deposit_amount; } /** * @brief take a double withdrawal amount. If the bank account's balance is less than the withdrawal amount, * the member function should just return false. Otherwise, subtract the withdrawal amount from the balance * of the bank account and return true. * * @param withdrawal_amount the amount to be withdrawal from the account * @return true, bank account's balance is not less than the withdrawal amount * @return false, bank account's balance is less than the withdrawal amount */ bool account::process_withdrawal(double withdrawal_amount) { // subtract withdrawal_amount if account has a high enough balance if (this->account_balance < withdrawal_amount) { return false; } this->account_balance -= withdrawal_amount; return true; } /** * @brief print the values of the data members * */ void account::print() const { // print the account number, name, and balance cout << "Account Number: " << account_number << endl; cout << "Name: " << customer_name << endl; cout << "Balance: $" << fixed << setprecision(2) << account_balance << endl; }
true
09cf3cd15842850302dd5501d907ea476cdde444
C++
darbyjohnston/DJV
/examples/Desktop/ComboBoxDesktopExample.cpp
UTF-8
2,694
2.578125
3
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 2004-2020 Darby Johnston // All rights reserved. #include <djvDesktopApp/Application.h> #include <djvUI/ComboBox.h> #include <djvUI/GridLayout.h> #include <djvUI/Window.h> #include <djvCore/Error.h> #include <djvCore/String.h> using namespace djv; int main(int argc, char ** argv) { int r = 1; try { // Create an application. auto args = Desktop::Application::args(argc, argv); auto app = Desktop::Application::create(args); // Create some combo box widgets. auto comboBox0 = UI::ComboBox::create(app); comboBox0->setItems(Core::String::getRandomNames(5)); comboBox0->setCurrentItem(0); comboBox0->setHAlign(UI::HAlign::Left); comboBox0->setVAlign(UI::VAlign::Top); auto comboBox1 = UI::ComboBox::create(app); comboBox1->setItems(Core::String::getRandomNames(25)); comboBox0->setCurrentItem(0); comboBox1->setHAlign(UI::HAlign::Right); comboBox1->setVAlign(UI::VAlign::Top); auto comboBox2 = UI::ComboBox::create(app); comboBox2->setItems(Core::String::getRandomNames(5)); comboBox0->setCurrentItem(0); comboBox2->setHAlign(UI::HAlign::Left); comboBox2->setVAlign(UI::VAlign::Bottom); auto comboBox3 = UI::ComboBox::create(app); comboBox3->setItems(Core::String::getRandomNames(25)); comboBox0->setCurrentItem(0); comboBox3->setHAlign(UI::HAlign::Right); comboBox3->setVAlign(UI::VAlign::Bottom); // Create a layout for the widgets. auto layout = UI::GridLayout::create(app); layout->setMargin(UI::MetricsRole::MarginLarge); layout->addChild(comboBox0); layout->setGridPos(comboBox0, glm::ivec2(0, 0)); layout->setStretch(comboBox0, UI::GridStretch::Both); layout->addChild(comboBox1); layout->setGridPos(comboBox1, glm::ivec2(1, 0)); layout->setStretch(comboBox1, UI::GridStretch::Both); layout->addChild(comboBox2); layout->setGridPos(comboBox2, glm::ivec2(0, 1)); layout->setStretch(comboBox2, UI::GridStretch::Both); layout->addChild(comboBox3); layout->setGridPos(comboBox3, glm::ivec2(1, 1)); layout->setStretch(comboBox3, UI::GridStretch::Both); // Create a window and show it. auto window = UI::Window::create(app); window->addChild(layout); window->show(); // Run the application. app->run(); r = app->getExitCode(); } catch (const std::exception & e) { std::cout << Core::Error::format(e) << std::endl; } return r; }
true
4add425eae3c81bdc5ebed3f1c36bc8a38ad9b14
C++
VT-ATEx/Core-2014
/Current_Code/Libraries/cppfiles/tests/INTEGRATED_TEST/cutdown.cpp
UTF-8
808
2.703125
3
[]
no_license
#include "cutdown.h" #define LED0_PATH "/sys/class/leds/beaglebone:green:usr0" using namespace std; void on_led() { std::fstream fs; fs.open(LED0_PATH "/trigger", std::fstream::out); fs << "none"; fs.close(); fs.open(LED0_PATH "/brightness", std::fstream::out); fs << "1"; fs.close(); } int activate_cutdown(unsigned int pinNum) { GPIO gpio(pinNum); if (gpio.gpio_export() != 0) { perror("Export Failed!"); return -1; } if (gpio.gpio_set_dir(1) != 0) { perror("Direction Failed!"); return -1; } if (gpio.gpio_set_value(1) != 0) { perror("Value Set Failed"); return -1; } on_led(); usleep(1000000); if (gpio.gpio_set_value(0) != 0) { perror("Value not reset!"); return -1; } if (gpio.gpio_unexport() != 0) { perror("Unexport Failed!"); return -1; } return 0; }
true
6380c09285efdc177c0d5c87d2621712ee25d0f7
C++
byllyfish/oftr
/include/ofp/oxmregister.h
UTF-8
1,723
2.875
3
[ "MIT" ]
permissive
// Copyright (c) 2016-2018 William W. Fisher (at gmail dot com) // This file is distributed under the MIT License. #ifndef OFP_OXMREGISTER_H_ #define OFP_OXMREGISTER_H_ #include "ofp/oxmtype.h" namespace ofp { /// Concrete class representing the bits of an OXM register. /// /// A register's string representation is: /// /// FIELD[begin:end] /// /// `begin` is the starting bit offset (first bit is zero). `end` is the ending /// bit offset (not inclusive). /// /// For example, to specify the the OUI in a MacAddress: /// /// ETH_DST[0:24] class OXMRegister { public: OXMRegister() = default; explicit OXMRegister(OXMType type) : type_{type}, offset_{0}, nbits_{maxBits()} {} explicit OXMRegister(OXMType type, UInt16 offset, UInt16 nbits) : type_{type}, offset_{offset}, nbits_{nbits} {} explicit OXMRegister(llvm::StringRef s) { (void)parse(s); } OXMType type() const { return type_; } UInt16 nbits() const { return nbits_; } UInt16 offset() const { return offset_; } UInt32 end() const { return offset_ + nbits_; } bool valid() const; bool parse(llvm::StringRef s); std::string toString() const { return detail::ToString(*this); } private: OXMType type_; UInt16 offset_ = 0; UInt16 nbits_ = 0; UInt16 maxBits() const { return type_.oxmSize() * 8; } friend llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const OXMRegister &value) { return os << value.type() << '[' << value.offset() << ':' << value.end() << ']'; } }; static_assert(sizeof(OXMRegister) == 8, "Unexpected size."); static_assert(alignof(OXMRegister) == 4, "Unexpected alignment."); } // namespace ofp #endif // OFP_OXMREGISTER_H_
true
3d3448d4a3016b060b3ec7c3a34ea66255e69107
C++
jin1408/StudyingDataStructure
/Meeting3.cpp
UTF-8
1,689
3.4375
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> // Deque를 이용한 meeting program using namespace std; int main(){ cout << "This is meeting program" << endl; deque<string> man; deque<string> woman; int count =0; string name; string gender; string answer; while(true){ if(count >100) return 0; cout<<"Name :"; cin>>name; cout<<"Gender : "; cin>>gender; cout<<"Do you want to match immediately?"; cin>>answer; if(gender == "m"){ if(answer == "y") man.push_front(name); else man.push_back(name); if(woman.empty() == false){ cout<<"Matching Success! "<<man.front()<<" and " <<woman.front()<<endl; cout<<endl; man.pop_front(); woman.pop_front(); } else{ cout<<"Can not match! Please Wait" << endl; cout<<endl; } } else{ if(answer == "y") woman.push_front(name); else woman.push_back(name); if(man.empty() == false){ cout<<"Matching Success! "<<man.front()<<" and " <<woman.front()<<endl; cout<<endl; man.pop_front(); woman.pop_front(); } else{ cout<<"Can not match! Please Wait" << endl; cout<<endl; } } count +=1; } }
true
9556b36a0c26279b07203de5005b2dc6e14a3d18
C++
rafsan99/Problem-Solving
/Business trip.cpp
UTF-8
569
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ int n,a[12],i,sum=0; cin>>n; for(i=0;i<12;i++){ cin>>a[i]; } sort(a,a+12,greater<int>()); if(n==0){ cout<<0; return 0; } for(i=0;i<12;i++){ if(a[i]==n){ cout<<1; break; } sum=sum+a[i]; if(sum>=n){ cout<<i+1; break; } if(i==11){ cout<<-1; } } }
true
dbf764f08f22f30f14cbed3b593f0ece9c2e9f43
C++
mborko/code-examples
/cpp/checkInt.cpp
UTF-8
497
3.25
3
[]
no_license
#include <iostream> #include <cstdlib> #include <sstream> using namespace std; int main(int argc, char** argv) { int temp; if ( argc >= 2 ) { if ( ! ( stringstream(argv[1]) >> temp ) ){ cout << "That was not an integer...\nTry again!" << endl; return EXIT_FAILURE; } else { cout << temp << " is an integer... Yippieee!" << endl; } } else { cout << "Please give one integer value as argument!" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
true
c2cc4e02f351ed23a756905e4eae4f616845d73e
C++
ccup/cctest
/spec/core/test_desc_spec.cc
UTF-8
1,699
2.828125
3
[ "Apache-2.0" ]
permissive
#include "cctest/cctest.h" #include "cctest/core/test_desc.h" using namespace cctest; namespace { FIXTURE(TestDescSpec) { TEST("without annotation") { TestDesc desc("test name"); ASSERT_EQ("test name", desc.name()); } TEST("extract test name") { TestDesc desc("@{id=xxx} test name"); ASSERT_EQ("test name", desc.name()); } TEST("extract id") { TestDesc desc("@{id=xxx} test name"); ASSERT_EQ("xxx", desc.id()); } TEST("extract dep") { TestDesc desc("@{dep=xxx} test name"); ASSERT_EQ("xxx", desc.dep()); } TEST("extract disable") { TestDesc desc("@{disable} test name"); ASSERT_TRUE(desc.disable()); } TEST("extract times") { TestDesc desc("@{times=10} test name"); ASSERT_EQ(10, desc.times()); } TEST("constains unknown keywords") { TestDesc desc("@{unknown_key=unknown_value} test name"); ASSERT_EQ("test name", desc.name()); } TEST("extract id, dep, and test name") { TestDesc desc("@{id=xxx, dep=yyy} test name"); ASSERT_EQ("test name", desc.name()); ASSERT_EQ("xxx", desc.id()); ASSERT_EQ("yyy", desc.dep()); } TEST("prefix starts with blacks") { TestDesc desc(" @{id=xxx, dep=yyy} test name"); ASSERT_EQ("test name", desc.name()); ASSERT_EQ("xxx", desc.id()); ASSERT_EQ("yyy", desc.dep()); } TEST("test name ends with blacks") { TestDesc desc("@{id=xxx, dep=yyy} test name "); ASSERT_EQ("test name", desc.name()); } TEST("prefix contains blacks") { TestDesc desc("@{ id = xxx, dep = yyy } test name"); ASSERT_EQ("test name", desc.name()); ASSERT_EQ("xxx", desc.id()); ASSERT_EQ("yyy", desc.dep()); } }; } // namespace
true
9ef29b6dd3730ec18413f4d3c8156c46a54f64d1
C++
BuiDucAnh68/CTDL-GT
/ASS1/bai 5/bai 5/bai 5cpp.cpp
UTF-8
2,414
3.5625
4
[]
no_license
// Hãy tách danh sách vừa nhập thành 2 danh sách l1 và l2 sao cho: //l1 bao gồm các số chẵn không trùng nhau. //l2 bao gồm các số lẻ không trùng nhau. //Đều được xếp theo thứ tự đầu vào #include<iostream> using namespace std; struct node { int info; node *pNext; }; struct List { node *pHead; node *pTail; }; void CreateList(List &l) { l.pHead = NULL; l.pTail = NULL; } node *CreateNode(int x) { node * p = new node; if (p == NULL) exit(1); p->info = x; p->pNext = NULL; return p; } void AddTail(List &l, node *p) { if (l.pHead == NULL) { l.pHead = p; l.pTail = l.pHead; } else { l.pTail->pNext = p; l.pTail = p; } } void Nhap(List &l) { int x; while (1) { cin >> x; if (x == 0) break; node * p = CreateNode(x); AddTail(l, p); } if (l.pHead == NULL) cout << "Danh sach rong !!!"; } void Xuat(List &l) { for (node * p = l.pHead; p != NULL; p = p->pNext) cout << p->info << " "; } int DemSoPhanTu(List l) { int dem = 0; for (node * p = l.pHead; p != NULL; p = p->pNext) dem++; return dem; } void Split(List l, List &l1, List &l2) { node* p; for (p = l.pHead; p != NULL; p = p->pNext) { if (p->info % 2 == 0) { node* p2 = new node; if (p2 == NULL) exit(-1); p2->info = p->info; p2->pNext = NULL; if (l1.pHead == NULL) { l1.pHead = p2; l1.pTail = l1.pHead; } else { node* e = l1.pHead; while (e != NULL) { if (e->info == p2->info) { goto xy; } e = e->pNext; } l1.pTail->pNext = p2; l1.pTail = p2; } } else { node* p3 = new node; if (p3 == NULL) exit(-1); p3->info = p->info; p3->pNext = NULL; if (l2.pHead == NULL) { l2.pHead = p3; l2.pTail = l2.pHead; } else { node* e = l2.pHead; while (e != NULL) { if (e->info == p3->info) { goto xy; } e = e->pNext; } l2.pTail->pNext = p3; l2.pTail = p3; } } xy: { } } } int main() { List l, l1, l2; CreateList(l); CreateList(l1); CreateList(l2); Nhap(l); if (DemSoPhanTu(l) == 0) cout << "Danh sach rong." << endl; else { cout << "Danh sach vua nhap la: "; Xuat(l); cout << endl; Split(l, l1, l2); cout << "Cac so chan trong danh sach la: "; Xuat(l1); cout << endl; cout << "Cac so le trong danh sach la: "; Xuat(l2); cout << endl; } return 0; }
true
39991391a8ca7210b1ac9e783c87d893d042ce15
C++
naimovfayyoz/cpp-projects
/Projects based on particular topics/4.Loop control structures/lab-4/Source4.cpp
WINDOWS-1252
323
3.265625
3
[]
no_license
/*Name:Fayyoz Naimov ID:U1910071 ASSIGNMENT: 4 5.Program to display sum of series 1+1/2+1/3+.+1/n. .*/ #include <iostream> using namespace std; int main5() { float a, sum = 0; cout << "Enter the number of series" << endl; cin >> a; for (float i = 1; i <= a; i++) { sum = sum + (1 / i); } cout << sum << endl; }
true
1e3e86d05af9a049a7b989b4c58da514e9941a9f
C++
alikhalid/UVA-Submissions
/WordSearch.cpp
UTF-8
3,288
2.59375
3
[]
no_license
#include <string> #include <iostream> using namespace std; #define endl '\n' string direction, *a; int matrixRow, matLength; int check(string word) throw() { string n, ne, e, se, s, sw, w, nw; bool found = false; int index = 0, col = 32, length; length = word.length(); while (index <= matLength) { for (int i = 32; i < matrixRow + 32; i++) { if (a[i][col] == word[0]) { n = ne = e = se = s = sw = w = nw = word[0]; for (int x = 1; x < length; x++) { n += a[i - x][col]; ne += a[i - x][col + x]; nw += a[i - x][col - x]; s += a[i + x][col]; se += a[i + x][col + x]; sw += a[i + x][col - x]; w += a[i][col - x]; e += a[i][col + x]; } if (n == word) { direction = "N"; found = true; } else if (ne == word) { direction = "NE"; found = true; } else if (e == word) { direction = "E"; found = true; } else if (se == word) { direction = "SE"; found = true; } else if (s == word) { direction = "S"; found = true; } else if (sw == word) { direction = "SW"; found = true; } else if (w == word) { direction = "W"; found = true; } else if (nw == word) { direction = "NW"; found = true; } if (found == true)return index; } index++; } col++; } return -1; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); string input, *searchWords; int l, x, i, k(0), n, inLines, numWords, index; cin >> n;//number of data sets while (k < n) { if (k != 0) cout << endl; matLength =0; input = ""; x = 0; i = 0; inLines = 0; cin >> matrixRow; cin >> numWords; searchWords = new string[numWords]; for (int i = 0; i < numWords; i++) { cin >> searchWords[i]; } cin >> inLines; cin.ignore(); i = 32; a = new string[matrixRow + 64]; if (matrixRow != 0) { for (int z = 32; z < matrixRow + 32; z++) { a[z] += "++++++++++++++++++++++++++++++++"; } for (int d = 0; d < inLines; d++) { getline(cin, input); l = input.length(); for (int x = 0; x < l; x++) { if (isalpha(input[x])) { if (i == (matrixRow + 32)) i = 32; a[i] += input[x]; i++; matLength++; } } } for (int z = 32; z < matrixRow + 32; z++) { a[z] += "++++++++++++++++++++++++++++++++++"; } for (int g = 0; g < 32; g++) { a[g].resize((matLength / matrixRow) + 65, '+'); a[g + 32 + matrixRow].resize((matLength / matrixRow) + 65, '+'); } for (int i = 0; i < numWords; i++) { index = check(searchWords[i]); cout << searchWords[i]; if (index != -1) cout << " " << index << " " << direction << endl; else cout << " NOT FOUND" << endl; } } else { for (int i = 0; i < inLines; i++) { getline(cin, input); } for (int i = 0; i < numWords; i++) { cout << searchWords[i] << " NOT FOUND" << endl; } } if (numWords > 0) delete[]searchWords; delete[]a; k++; } return 0; }
true
88af6377221e94fc36db490b287d11b17f51d1e3
C++
iamslash/learntocode
/leetcode/DiagonalTraverse/a.cpp
UTF-8
1,497
3.21875
3
[]
no_license
/* Copyright (C) 2019 by iamslash */ #include <cstdio> #include <vector> // O(N) O(1) // 72ms 100.00% class Solution { public: std::vector<int> findDiagonalOrder( std::vector<std::vector<int>>& M) { std::vector<int> rslt; if (M.empty() || M[0].empty()) return rslt; int h = M.size(); int w = M[0].size(); int dy[2] = {-1, 1}; // delta y int dx[2] = {1, -1}; // delta x int bdir = 0; // true: up, false: down int sy = 0, sx = 0; // start y, x while (sy < h && sx < w) { int ny = sy; int nx = sx; // printf("sy: %d, sx: %d\n", sy, sx); while (ny >= 0 && ny < h && nx >= 0 && nx < w) { // printf(" ny: %d, nx: %d\n", ny, nx); rslt.push_back(M[ny][nx]); ny += dy[bdir]; nx += dx[bdir]; } sy = ny - dy[bdir]; sx = nx - dx[bdir]; if (bdir == 0) { if (sx == w - 1) sy += 1; else sx += 1; } else { if (sy == h - 1) sx += 1; else sy += 1; } bdir = bdir == 0 ? 1 : 0; } return rslt; } }; int main() { // std::vector<std::vector<int>> M = { // {1, 2, 3}, // {4, 5, 6}, // {7, 8, 9} // }; std::vector<std::vector<int>> M = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, }; Solution sln; auto l = sln.findDiagonalOrder(M); for (int a : l) printf("%d ", a); printf("\n"); return 0; }
true
d8576bb8bfa1af34777aa0d75a1cf3628d975b06
C++
xandrl09/ISA
/main.cpp
UTF-8
835
2.625
3
[]
no_license
#include <iostream> #include <getopt.h> #include <netinet/ip.h> #include <netinet/tcp.h> using namespace std; void help() { cerr << "Run the program with arguments -i or -r." << endl; } int check_params(int argc, char *argv[]) { string promena; if(argc < 2) { } else if(argc == 3) { while (( opt = getopt(argc, argv, "ir")) != -1) { switch (opt) { case 'a': argv[optind]; /// break; case 'm': /// break; } } } else { help(); exit(0); } } int main(int argc, char *argv[]) { int result = check_params(argc, argv); cout << "Hello, World!" << endl; return 0; }
true
30902ceea9eac986a50bb3f569d7e0d87297502c
C++
THISISAGOODNAME/SkelAnimation
/src/RHI/Backend/OpenGL/Uniform.cpp
UTF-8
1,599
2.59375
3
[ "LicenseRef-scancode-public-domain", "MIT" ]
permissive
#include "RHI/Uniform.h" #include <glad/gl.h> #include "Math/vec2.h" #include "Math/vec3.h" #include "Math/vec4.h" #include "Math/mat4.h" #include "Math/quat.h" template Uniform<int>; template Uniform<ivec4>; template Uniform<ivec2>; template Uniform<float>; template Uniform<vec2>; template Uniform<vec3>; template Uniform<vec4>; template Uniform<quat>; template Uniform<mat4>; #define UNIFORM_IMPL(gl_func, tType, dType) \ template<> \ void Uniform<tType>::Set(unsigned int slot, tType* data, unsigned int length) { \ gl_func(slot, (GLsizei)length, (dType*)&data[0]); \ } UNIFORM_IMPL(glUniform1iv, int, int) UNIFORM_IMPL(glUniform4iv, ivec4, int) UNIFORM_IMPL(glUniform2iv, ivec2, int) UNIFORM_IMPL(glUniform1fv, float, float) UNIFORM_IMPL(glUniform2fv, vec2, float) UNIFORM_IMPL(glUniform3fv, vec3, float) UNIFORM_IMPL(glUniform4fv, vec4, float) UNIFORM_IMPL(glUniform4fv, quat, float) template<> void Uniform<mat4>::Set(unsigned int slot, mat4* inputArray, unsigned int arrayLength) { glUniformMatrix4fv(slot, (GLsizei)arrayLength, false, (float*)&inputArray[0]); } template <typename T> void Uniform<T>::Set(unsigned int slot, const T& value) { Set(slot, (T*)&value, 1); } template <typename T> void Uniform<T>::Set(unsigned int slot, std::vector<T>& value) { Set(slot, &value[0], (unsigned int)value.size()); } #include "Math/DualQuaternion.h" template Uniform<DualQuaternion>; template<> void Uniform<DualQuaternion>::Set(unsigned int slot, DualQuaternion* inputArray, unsigned int arrayLength) { glUniformMatrix2x4fv(slot, (GLsizei)arrayLength, false, inputArray[0].v); }
true
1eadc05f0122bd7a103a5f9a8bc03f5ae1317d49
C++
artnitolog/cpp-grammars_course
/other/mutex1.cpp
UTF-8
1,129
3
3
[]
no_license
#include <thread> #include <mutex> #include <vector> #include <iostream> // volatile long long v1 = 0; // volatile long long v2 = 0; long long v1, v2 = 0; // несколько нитей => НЕ НАДО ВОЛАТАЙЛ ЕСТЬ МЬЮТЕКС std::mutex m, m2; int main() { std::vector<std::thread> thrs; for (int i = 0; i < 10; i++) { thrs.emplace_back([](int i) { for (int j = 0; j < 100000; ++j) { // std::lock_guard lock{m}; // std::unique_lock lock{m}; // семантика владения, можно передавать внутрь кому-то // std::shared_lock lock{m}; // std::scoped_lock lock{m, m2}; // умеет захватывать несколько мьютексов одновременно std::lock_guard l1{m}, l2{m2}; // обедающие философы -> дедлок из-за порядка v1 += i; v2 -= i; } }, i); } for (auto &t : thrs) { t.join(); } std::cout << v1 << " " << v2 << std::endl; }
true
73be6b1a4e9de8b25a7388e5d6c4bf300fea39fa
C++
gxshao/LeetCode
/Array/LeetCode_628_Maximum_Product_of_Three_Numbers.cpp
UTF-8
987
3.703125
4
[]
no_license
#include <iostream> #include <stdlib.h> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; /** * Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 2: Input: [1,2,3,4] Output: 24 Note: The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000]. Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer. * * */ //考点:求最大乘积 ,先排序,然后取出数组最大三位数乘积和最小两个数和最后一位乘积,因为可能存在负数 int maximumProduct(vector<int> &nums) { int n=nums.size(); sort(nums.begin(),nums.end()); return max(nums[n-1]*nums[n-2]*nums[n-3],nums[0]*nums[1]*nums[2]); } int main() { vector<int> nums = {1, 2, 3, 4, 5}; std::cout <<maximumProduct(nums) << std::endl; system("pause"); return 0; }
true
d575ea600e14281506cf12b9f7e13489a1725a26
C++
billiesu/EE599-HW4
/Q1/src/lib/solution.h
UTF-8
401
2.734375
3
[]
no_license
#ifndef TEMPLATE_SOLUTION_H #define TEMPLATE_SOLUTION_H #include <string> #include <vector> #include <algorithm> #include <iostream> #include <numeric> using std::vector; using std::cout; using std::endl; class Solution { public: vector<int> Filter(vector<int> input); vector<int> Map(vector<int> input); int Reduce(vector<int> input); void PrintVector(const vector<int> &input); }; #endif
true
a011f3a56961993e3ab24922446953a0445d348d
C++
kekekeks/prowingen
/native/include/com.h
UTF-8
2,588
2.640625
3
[ "MIT" ]
permissive
#pragma clang diagnostic push #pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection" #ifndef COM_H_INCLUDED #define COM_H_INCLUDED #include <cstring> typedef struct _GUID { unsigned int Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[ 8 ]; } GUID; typedef GUID IID; typedef const IID* REFIID; typedef unsigned int HRESULT; typedef unsigned int DWORD; typedef DWORD ULONG; #define STDMETHODCALLTYPE #define S_OK 0x0L #define E_NOINTERFACE 0x80004002UL #define E_FAIL 0x80004005L typedef struct _IUnknown { virtual HRESULT STDMETHODCALLTYPE QueryInterface( REFIID riid, void **ppvObject) = 0; virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0; virtual ULONG STDMETHODCALLTYPE Release( void) = 0; } IUnknown; template<class TInterface, GUID const* TIID> class ComObject : public TInterface { private: unsigned int _refCount; public: virtual ULONG AddRef() { _refCount++; return _refCount; } virtual ULONG Release() { _refCount--; ULONG rv = _refCount; if(_refCount == 0) delete(this); return rv; } virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppvObject) { const GUID IID_IUnknown = { 0x00, 0x0, 0x0, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } }; if(0 == memcmp(riid, &IID_IUnknown, sizeof(GUID))) *ppvObject = (IUnknown*)this; else if(0 == memcmp(riid, TIID, sizeof(GUID))) { TInterface* casted = this; *ppvObject = casted; } else return E_NOINTERFACE; _refCount++; return S_OK; } ComObject() { _refCount = 1; } virtual ~ComObject() { } }; template<class TInterface> class ComPtr { private: TInterface* _obj; public: ComPtr(TInterface* pObj) { _obj = 0; if (pObj) { _obj = pObj; _obj->AddRef(); } } ~ComPtr() { if (_obj) { _obj->Release(); _obj = 0; } } public: operator TInterface*() const { return _obj; } TInterface& operator*() const { return *_obj; } TInterface** operator&() { return &_obj; } TInterface* operator->() const { return _obj; } }; #endif // COM_H_INCLUDED #pragma clang diagnostic pop
true
7115c2e11ba00c7f703928a16428677695a08594
C++
PlumpMath/earSight-openFrameworks
/src/testApp.cpp
UTF-8
3,649
2.53125
3
[]
no_license
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ // initialise sound soundStream.setup(this, 2, 0, SAMPLE_RATE, BUFFER_SIZE, 4); camWidth = 640; camHeight = 480; // init web cam vidGrabber.setDeviceID(0); vidGrabber.setDesiredFrameRate(60); vidGrabber.initGrabber(camWidth, camHeight); // set size of image that we're grabbing image = new unsigned char[camWidth*camWidth*3]; videoTexture.allocate(camWidth, camHeight, GL_RGB); // TODO what does this do? ofSetVerticalSync(true); } //-------------------------------------------------------------- void testApp::audioOut(float * output, int bufferSize, int nChannels){ synth.addAudioOut(output, bufferSize, nChannels); } //-------------------------------------------------------------- void testApp::update(){ // grab frame of video vidGrabber.update(); if(vidGrabber.isFrameNew()) { image = vidGrabber.getPixels(); videoTexture.loadData(image, camWidth, camHeight, GL_RGB); } scaling = MIN(ofGetWidth()/(float)camWidth, ofGetHeight()/(float)camHeight); xOffset = (ofGetWidth() - (camWidth * scaling)) / 2; yOffset = (ofGetHeight() - (camHeight * scaling)) / 2; } //-------------------------------------------------------------- // test of finger/mouse is on image covered part of screen bool testApp::onImage(int x, int y){ return x > xOffset && y > yOffset && x < ofGetWidth() - xOffset && y < ofGetHeight() - yOffset; } //-------------------------------------------------------------- void testApp::getImagePixelRGB(int x, int y, int * r, int * g, int * b){ // scale position on screen x -= xOffset; y -= yOffset; x *= scaling; y *= scaling; // double check image scaling hasn't put us out of bounds if(x >= camWidth) { x = camWidth - 1; } if(x < 0) { x = 0; } if(y >= camHeight) { y = camHeight - 1; } if(y < 0) { y = 0; } // work out position in image to read back int imagePos = ((y * camWidth) + x) * 3; *r = (int)image[imagePos]; *g = (int)image[imagePos + 1]; *b = (int)image[imagePos + 2]; } //-------------------------------------------------------------- void testApp::draw(){ videoTexture.draw(xOffset, yOffset, camWidth * scaling, camHeight * scaling); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y){ if(onImage(x, y)) { int r, g, b; // get rgb from image int r, g, b; getImagePixelRGB(x, y, &r, &g, &b); // get colour magnitudes double white, black, grey, blue, yellow, green, red; rgbToColourMags(&white, &black, &grey, &green, &red, &blue, &yellow, r, g, b); synth.mapColourMags(white, black, grey, green, red, blue, yellow); } else { synth.fadeOut(); } } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
true
590a0e9aa7a025ad69f8413d9167b3be005361e9
C++
kobortor/Competitive-Programming
/cf-gym/NWERC-2021/G.cpp
UTF-8
2,712
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define allof(x) (x).begin(), (x).end() const int MAXN = 5005; typedef pair<int, int> pii; int n, w; string words[MAXN]; int max_width[MAXN][MAXN]; int prv[MAXN]; int cost[MAXN]; bool good(int rows) { memset(cost, 0x3f, sizeof cost); cost[0] = 0; for (int j = 1; j <= n; j++) { for (int i = j; i >= 1 && j - i + 1 <= rows; i--) { int new_cost = cost[i - 1] + max_width[i][j] + 1; cost[j] = min(cost[j], new_cost); } } return cost[n] - 1 <= w; } void output(int rows) { memset(cost, 0x3f, sizeof cost); cost[0] = 0; for (int j = 1; j <= n; j++) { for (int i = j; i >= 1 && j - i + 1 <= rows; i--) { int new_cost = cost[i - 1] + max_width[i][j] + 1; if (new_cost < cost[j]) { cost[j] = new_cost; prv[j] = i; } } } vector<int> widths; vector<pii> groups; int idx = n; while (idx != 0) { widths.push_back(max_width[prv[idx]][idx]); groups.push_back({prv[idx], idx}); idx = prv[idx] - 1; } reverse(allof(widths)); reverse(allof(groups)); // int total_widths = std::accumulate(widths.begin(), widths.end(), -1) + widths.size(); cout << rows << " " << widths.size() << "\n"; for (int w : widths) { cout << w << " "; } cout << "\n"; vector<vector<string>> answer_grid(rows, vector<string>(widths.size())); for (int i = 0; i < (int)groups.size(); i++) { for (int j = groups[i].first; j <= groups[i].second; j++) { answer_grid[j - groups[i].first][i] = words[j]; } } for (int i = 0; i < (int)answer_grid.size(); i++) { for (int j = 0; j < (int)answer_grid[i].size(); j++) { cout << answer_grid[i][j]; for (int k = answer_grid[i][j].size(); k < widths[j]; k++) { cout << " "; } cout << " "; } cout << "\n"; } } int main() { cin.tie(0); cin.sync_with_stdio(0); cin >> n >> w; for (int i = 1; i <= n; i++) { cin >> words[i]; } for (int i = 1; i <= n; i++) { int maxw = -1; for (int j = i; j <= n; j++) { maxw = max(maxw, (int)words[j].size()); max_width[i][j] = maxw; // cout << "max_width[" << i << "][" << j << "] = " << maxw << endl; } } int lo = 0, hi = 1e6 + 6; while (lo <= hi) { int mid = (lo + hi) / 2; if (good(mid)) { hi = mid - 1; } else { lo = mid + 1; } } output(hi + 1); // cout << hi + 1 << "\n"; }
true
e17579fd8c4e7d2438284bc5187067bc2743c769
C++
xmuliushuo/learn
/cplusplus/e_4_28.cpp
UTF-8
439
3.09375
3
[]
no_license
/* * e_4_28.cpp * * Created on: 2012-12-3 * Author: liushuo */ #include <vector> #include <iostream> using std::cin; using std::cout; using std::vector; void e_4_28() { vector<int> ivec; int num; while (cin >> num) { ivec.push_back(num); } int *array = new int[ivec.size()]; int *p = array; for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); iter++, p++) { *p = *iter; cout << *p << " "; } }
true
99aacc9848f71f0733d1e162ad7044853736d32c
C++
EXPmaster/CouseProjectC
/综合设计/dataset.cpp
UTF-8
7,858
2.96875
3
[]
no_license
#include "dataset.h" extern void Append(ppStudent head, int number, int subject); extern void TraverseList(pStudent head); void GetInfo(ppStudent student) { int number = 0, subject = 0; if (*student == NULL) { puts("请输入考试科目总数"); while (!scanf("%d", &subject) || (subject <= 0 || subject > 6)) { puts("格式不对,请重新输入"); clean_cache(); } } puts("请输入要录入的考生人数"); while (!scanf("%d", &number) || (number <= 0 || number > 30)) { puts("格式不对,请重新输入"); clean_cache(); } clean_cache(); Append(student, number, subject); puts("录入成功"); } char *s_gets(char *str, int n) { char *find, *ret_val; ret_val = fgets(str, n, stdin); if (ret_val) { find = strchr(str, '\n'); if (find) *find = '\0'; else clean_cache(); } return ret_val; } void Traverse(pStudent student) { if (!student) { puts("请先录入成绩"); return; } puts("成绩单"); printf(" 学号\t\t"); printf("姓名\t\t"); char index[6][20] = {"Chinese", "math", "English", "C programming", "Politics", "Engineering"}; for (int i = 0; i < 6; i++) { if (student->score[i] != 999) printf("%s\t\t", index[i]); } printf("\t"); printf("总分\t\t"); printf("排名\n"); TraverseList(student); } void GetFile(ppStudent student) { FILE *fp; *student = NULL; if ((fp = fopen("studengdata.txt", "r")) == NULL) { puts("no such file"); exit(1); } pStudent node, current = *student; /* while (after) { current = after; after = after->next; } */ while (!feof(fp)) //bug: if the file is empty then it'll get all 0 { node = (pStudent) malloc(sizeof(Student)); if (!node) { puts("memory allocate failure"); exit(1); } if (!*student) { *student = node; current = *student; } current->next = node; node->next = NULL; current = node; s_gets(node->id, 10, fp); s_gets(node->name, 20, fp); fscanf(fp, "\t"); for (int i = 0; i < 6; i++) { fscanf(fp, "%lf\t", &node->score[i]); } fscanf(fp, "%lf\t", &node->TotalScore); fscanf(fp, "%d\n", &node->rank); } fclose(fp); } void Output_to_file(ppStudent student) { FILE *fp; fp = fopen("studengdata.txt", "w"); pStudent current = *student; while (current) { fprintf(fp, "%s\n", current->id); fprintf(fp, "%s\n", current->name); for (int i = 0; i < 6; i++) { fprintf(fp, "%lf\t", current->score[i]); } fprintf(fp, "%lf\n", current->TotalScore); fprintf(fp, "%d\n", current->rank); current = current->next; } fclose(fp); puts("写入文件成功"); } char *s_gets(char *str, int n, FILE *fp) { char *find, *ret_val; ret_val = fgets(str, n, fp); if (ret_val) { find = strchr(str, '\n'); if (find) *find = '\0'; else while (getchar() != '\n'); } return ret_val; } void SearchID(ppStudent student) { if (!*student) { puts("请先录入成绩"); return; } pStudent current = *student; char index[6][20] = {"Chinese", "math", "English", "C programming", "Politics", "Engineering"}; puts("输入你要查找到学号"); char search[10]; s_gets(search, 10); puts("搜索结果:"); printf("学号\t\t\t"); printf("姓名\t\t"); for (int i = 0; i < 6; i++) { if ((*student)->score[i] != 999) printf("%s\t", index[i]); } printf("\t"); printf("总分\t\t"); printf("排名\n"); while (current) { //if find existing student information if (strcmp(current->id, search) == 0) { printf("%s\t\t", current->id); printf("%s\t\t", current->name); for (int i = 0; i < 6; i++) { if (current->score[i] != 999) printf("%.2lf\t", current->score[i]); } printf("\t"); printf("%.2lf\t\t", current->TotalScore); printf("%d\n", current->rank); return; } current = current->next; } //cannot find information puts("找不到结果"); } void SearchName(ppStudent student) { if (!*student) { puts("请先录入成绩"); return; } pStudent current = *student; char index[6][20] = {"Chinese", "math", "English", "C programming", "Politics", "Engineering"}; puts("输入你要查找到姓名"); char search[10]; s_gets(search, 10); puts("搜索结果:"); printf("学号\t\t"); printf("姓名\t\t"); for (int i = 0; i < 6; i++) { if ((*student)->score[i] != 999) printf("%s\t", index[i]); } printf("\t"); printf("总分\t\t"); printf("排名\n"); bool find = false; while (current) { //if find existing student information if (strstr(current->name, search)) { find = true; printf("%s\t\t", current->id); printf("%s\t\t", current->name); for (int i = 0; i < 6; i++) { if (current->score[i] != 999) printf("%.2lf\t", current->score[i]); } printf("\t"); printf("%.2lf\t\t", current->TotalScore); printf("%d\n", current->rank); } current = current->next; } //cannot find information if (!find) puts("找不到结果"); } void CalcuCategory(ppStudent student) { if (!*student) { puts("请先录入成绩"); return; } int classify[6][5] = {0}, total = 0; double portion[6][5] = {0}; char index[][10] = {"优秀", "良好", "中等", "及格", "不及格"}; char subject[][20] = {"Chinese", "math", "English", "C programming", "Politics", "Engineering"}; pStudent current = *student; while (current) { total++; for (int i = 0; i < 6; i++) { if (current->score[i] != 999) { if (current->score[i] >= 90 && current->score[i] <= 100) classify[i][0]++; else if (current->score[i] >= 80 && current->score[i] < 90) classify[i][1]++; else if (current->score[i] >= 70 && current->score[i] < 80) classify[i][2]++; else if (current->score[i] >= 60 && current->score[i] < 70) classify[i][3]++; else classify[i][4]++; } } current = current->next; } for (int i = 0; i < 6; i++) { if ((*student)->score[i] != 999) { for (int j = 0; j < 5; j++) portion[i][j] = (double) classify[i][j] / total; } } puts("总体数据:"); printf("\t "); for (int i = 0; i < 5; i++) printf("%s ", index[i]); printf("\n"); for (int i = 0; i < 6; i++) { if ((*student)->score[i] != 999) { printf("%15s:\t", subject[i]); for (int j = 0; j < 5; j++) { printf("人数:%d 占比:%.1lf ", classify[i][j], portion[i][j]); } printf("\n"); } } printf("\n"); } void clean_cache() { while (getchar() != '\n'); }
true
b75ed88f32bd95b6093ccb80330f76bed9f134fa
C++
kohutjan/HABCforNRP
/src/scheduling_period/employee.cpp
UTF-8
2,191
2.953125
3
[]
no_license
#include "scheduling_period/employee.hpp" using namespace std; using namespace boost::gregorian; void Employee::LoadFromStream(ifstream &periodStream) { string ignore; periodStream >> this->id; cout << this->id << ", "; periodStream >> ignore; periodStream >> this->name; this->name.pop_back(); cout << this->name << ", "; periodStream >> this->contractId; cout << this->contractId; periodStream >> ignore; int numberOfSkills; periodStream >> numberOfSkills; periodStream >> ignore; string skill; for (int i = 0; i < (numberOfSkills - 1); ++i) { periodStream >> skill; this->skills.push_back(skill); cout << ", " << this->skills[i]; } periodStream >> skill; skill.pop_back(); this->skills.push_back(skill); cout << ", " << this->skills.back(); cout << endl; return; } void Employee::LoadDayRequest(ifstream &periodStream, bool on) { string ignore; string requestDateStr; periodStream >> requestDateStr; requestDateStr.pop_back(); int weight; periodStream >> weight; periodStream >> ignore; date requestDate = from_simple_string(requestDateStr); cout << requestDate << ", " << weight << endl; if (on) { this->dayOnRequest.push_back(make_pair(requestDate, weight)); } else { this->dayOffRequest.push_back(make_pair(requestDate, weight)); } return; } void Employee::LoadShiftRequest(ifstream &periodStream, bool on) { string ignore; string requestDateStr; periodStream >> requestDateStr; requestDateStr.pop_back(); char shiftType; periodStream >> shiftType; if (shiftType == DAY) { periodStream >> shiftType; if (shiftType != HEAD_DAY) { shiftType = DAY; } else { periodStream >> ignore; } } else { periodStream >> ignore; } int weight; periodStream >> weight; periodStream >> ignore; date requestDate = from_simple_string(requestDateStr); cout << requestDate << ", " << shiftType << ", " << weight << endl; if (on) { this->shiftOnRequest[shiftType].push_back(make_pair(requestDate, weight)); } else { this->shiftOffRequest[shiftType].push_back(make_pair(requestDate, weight)); } return; }
true
21e4a149ffc2865d3fcee66b1bdb31367609f876
C++
helldongdae/COCO
/answers/H.cpp
UTF-8
1,472
2.90625
3
[]
no_license
#include <cstdio> #include <vector> #include <queue> #include <iostream> #include <math.h> #include <stdlib.h> #include<fstream> using namespace std; vector<int> tree[50001]; int level[50001] = { 0 }; int parent[50001] = { 0 }; queue<int> q; void DFS(int src){ q.push(src); level[src] = 0; parent[src] = 0; while (q.empty() == false){ int p = q.front(); q.pop(); for (int j = 0; j < tree[p].size(); j++){ if (tree[p][j] != parent[p]){ q.push(tree[p][j]); level[tree[p][j]] = level[p] + 1; parent[tree[p][j]] = p; } } } } int LCA(int src, int dst){ int a = src; int b = dst; while (level[a] > level[b]){ a = parent[a]; } while (level[a] < level[b]){ b = parent[b]; } while (parent[a] != parent[b]){ a = parent[a]; b = parent[b]; } if (a == b) return a; else return parent[a]; } int main(){ ifstream f("H.txt"); ofstream f2("H_out.txt"); int T; f>>T; for(int k = 0;k<T;k++){ for (int i = 0; i < 50001; i++){ level[i] = 0; parent[i] = 0; tree[i].clear(); } int n; f >> n; for (int i = 0; i < n-1; i++){ int a, b; f >> a >> b; tree[a].push_back(b); tree[b].push_back(a); } DFS(1); int m; f >> m; int root = 1; int tot = 0; for (int i = 0; i < m; i++){ int a; f >> a; int lca = LCA(root, a); int n1 = level[root] - level[lca]; int n2 = level[a] - level[lca]; tot += abs(n1) + abs(n2); root = a; } f2 << tot << endl; } f.close(); f2.close(); }
true
2433241c28df5b0633934488cf48a4e42803260f
C++
othis001/solutions
/subsetsXOR.cpp
UTF-8
2,209
4.125
4
[]
no_license
/******************************* * subsetsXOR.cpp by Oliver Thistlethwaite * * Purpose: This is a program that takes an input an array of nonnegative integers. * It will then compute the sum of the XORs of all the subsets. ******************************/ #include <cmath> #include <vector> #include <iostream> using namespace std; long long XORsubsets(vector<int> input) { int k, i, size = input.size(); /* First we count the number of entries that have the kth bit set for each 0<=k<31 and store that information in bitset. */ int bitset[31]; for(k=0; k<31; k++) { bitset[k] = 0; for(i=0; i<size; i++) { if( (input[i] & (1 << k)) != 0) bitset[k]++; } } /* Now we traverse each bit position. Any choice of subset with an odd number of 1s in the kth positions will contribute a 2^k to the total sum. The number of subsets that will contribute a 2^k will be the number of ways to chose a subset where each element has a 0 in the kth position times the number of ways to choose a subset of odd size where each element has a 1 in the kth position. If you do the math, you will find this number is always 2^(size-1) provided at least one entry has a 1 in its kth bit position. The key is to realize exactly half of all subsets have odd size. So if we multiply this number by 2^k, we obtain the total contribution. */ long long total = 0, number = pow(2, size - 1); for(k=0; k<31; k++) { if(bitset[k] != 0) { total += pow(2, k) * number; } } return total; } int main() { int i,j,K, N, a; cout << "\nThis is a program that takes an input an array of nonnegative integers.\n" "It will then compute the sum of the XORs of all the subsets.\n" << endl; cout << "Enter the size of the array: "; cin >> N; cout << "Enter the array: "; vector<int> input; for(j=0; j<N; j++) { cin >> a; input.push_back(a); } cout << "The sum of the XORs of all the subsets is " << XORsubsets(input) << "." << endl; return 0; }
true
49590bbf74359e3f3e986346e916bef478416193
C++
kl456123/cpp_best_practice
/src/executor.cc
UTF-8
1,648
2.5625
3
[]
no_license
#include <vector> #include "core/graph/executor.h" class ExecutorImpl: public Executor{ public: explicit ExecutorImpl(const LocalExecutorParams& param):param_(param){ } virtual void RunAsync(const Args& args)override; Status Initialize(const Graph& graph); private: LocalExecutorParams param_; std::vector<const Node*> root_nodes_; }; class ExecutorState{ Status Process(); void RunAsync(const Args& args); Status PrepareInputs(); Status ProcessOutputs(); void Finish(); }; Status ExecutorImpl::RunAsync(const Args& args, DoneCallback done){ (new ExecutorState(args, this))->RunAsync(done); } Status ExecutorImpl::Initialize(const Graph& graph) { // preprocess ops for(auto& node: param_.nodes){ OpKernel* op_kernel=nullptr; Status s = param_.create_kernel(node.node_def_, &op_kernel); if(!s.ok()){ LOG(ERROR)<<"Executor failed to create kernel. "<<s; return s; } } } void ExecutorImpl::RunAsync(DoneCallback done){ Status s = Process(); done(s); } Status ExecutorState::Process(){ for(const Node* item: impl_->root_nodes_){ DCHECK_EQ(item->num_inputs, 0); ready.push_back(); } Device* device = impl_->params_.device; // bfs while(!ready.empty()){ node = ready.front(); // construct OpKernelContext OpKernelContext ctx(&params); OpKernel* op_kernel = node.op_kernel_; device->Compute(op_kernel, &ctx); } } Status ExecutorState::PrepareInputs(){} Status ExecutorState::ProcessOutputs(){}
true
8030391dca0f9d8fc66957591b6cff7fa3dd9eb8
C++
LiYuRio/leetcode-daily
/leetcode/2-Add-Two-Numbers.cpp
UTF-8
1,625
3.8125
4
[]
no_license
#include <iostream> using namespace std; 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) {} }; ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* result = new ListNode(-1); ListNode* ptr = result; int carry = 0; while (l1 != nullptr && l2 != nullptr) { int add_result = l1->val + l2->val + carry; carry = add_result / 10; ptr->next = new ListNode(add_result % 10); l1 = l1->next; l2 = l2->next; ptr = ptr->next; } while (l1 != nullptr) { int add_result = l1->val + carry; carry = add_result / 10; ptr->next = new ListNode(add_result % 10); carry = add_result / 10; l1 = l1->next; ptr = ptr->next; } while (l2 != nullptr) { int add_result = l2->val + carry; carry = add_result / 10; ptr->next = new ListNode(add_result % 10); carry = add_result / 10; l2 = l2->next; ptr = ptr->next; } if (carry != 0) { ptr->next = new ListNode(carry); } return result->next; } ListNode* create(int arr[], int nums) { ListNode* l1 = new ListNode(arr[0]); ListNode* ptr = l1; for (int i = 1; i < nums; i++) { ptr->next = new ListNode(arr[i]); ptr = ptr->next; } return l1; } int main() { int arr1[] = {2, 4, 3}; int arr2[] = {5, 6, 4}; ListNode* l1 = create(arr1, 3); ListNode* l2 = create(arr2, 3); ListNode* result = addTwoNumbers(l1, l2); for (ListNode* ptr = result; ptr != NULL; ptr = ptr->next) { cout << ptr->val << " "; } cout << std::endl; }
true
2b2dd249e383ba6ca2b71b9aab153b214580a3b1
C++
minghsu0107/workspace
/C++/Practice3/exam2.cc
UTF-8
2,077
3.140625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct Test { int seq; int math; int total; }; bool compare1(const Test &a, const Test &b){ return a.total > b.total; } bool compare2(const Test &a, const Test &b){ return a.math > b.math; } bool compare(const Test &a, const Test &b){ if(a.total==b.total){ return a.math > b.math; } return a.total > b.total; } void exam(vector<Test> &tests){ sort(tests.begin(), tests.end(), compare1); int i=0; int pos=0; bool count=false; int len=0; for(int i=0;i<tests.size()-1;i++){ if(tests[i].total==tests[i+1].total){ if(count==false){ pos=i; len+=2; count=true; } else{ len++; } } else if(tests[i].total!=tests[i+1].total && count==true){ sort(&tests[pos],&tests[pos+len],compare2); count=false; len=0; } } if(count==true){ sort(&tests[pos],&tests[pos+len],compare2); } for(int i=0;i<tests.size();i++){ cout<<tests[i].seq<<endl; } } void exam2(vector<Test> &arr){ int flag = 1; for(int i = 0; i < arr.size()-1 && flag == 1; i++) { flag = 0; for(int j = 0; j < arr.size()-i-1; j++) { if(compare(arr[j+1], arr[j])) { Test t=arr[j+1]; arr[j+1]=arr[j]; arr[j]=t; flag = 1; } } } for(int i=0;i<arr.size();i++){ cout<<arr[i].seq<<endl; } } void exam3(vector<Test> &arr){ sort(arr.begin(),arr.end(),compare); for(int i=0;i<arr.size();i++){ cout<<arr[i].seq<<endl; } } int main(){ int n; cin>>n; vector<Test> tests; for(int i=0;i<n;i++){ int seq,lit,eng,math,phy,chem; cin>>seq>>lit>>eng>>math>>phy>>chem; int total=lit+eng+math+phy+chem; Test test; test.seq=seq; test.math=math; test.total=total; tests.push_back(test); } exam3(tests); }
true
37a52127ee632e83838eaa150ae2b8bc67b3f907
C++
HaochenLiu/My-LeetCode-CPP
/030.cpp
UTF-8
1,436
3.5
4
[]
no_license
/* 030. Substring with Concatenation of All Words You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters. For example, given: S: "barfoothefoobarman" L: ["foo", "bar"] You should return the indices: [0,9]. (order does not matter). */ /* Time: O((nS-n*nL+1)*(n*nL)) Space: O(n*nL) Extra space: O(n*nL) nS is the length of S. nL is the length of L. n is number of strings in L. */ class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; res.clear(); int n = L.size(); int len = L[0].size(); if(n == 0 || len == 0) return res; if(S.length() < n * len) return res; map<string, int> m; for(int i = 0; i < n; ++i) { m[L[i]]++; } for(int i = 0; i <= S.length() - n * len; ++i) { map<string, int> t; bool flag = true; for(int j = i; j < i + n * len; j += len) { string tmp = S.substr(j, len); t[tmp]++; if(t[tmp] > m[tmp]) { flag = false; break; } } if(flag) { res.push_back(i); } } return res; } };
true
e9cd20f19991ac8b77c84c6072c152d1454b15a8
C++
ketlynsena/LogiKids
/LogiKids/Test-LogiKids/test_map_coloring.cpp
UTF-8
5,255
2.578125
3
[]
no_license
#include "pch.h" //#include "../LogiKids/game.h" #include "../LogiKids/map_coloring.h" TEST(TestMapColoring, TestInit) { Map_Coloring* colorindo_bh = new Map_Coloring(); EXPECT_TRUE(colorindo_bh); } TEST(TestMapColoring, TestAddRegion) { Map_Coloring* colorindo_bh = new Map_Coloring(); Regiao regiao; SDL_Color color = { 204, 204, 204 }; colorindo_bh->addRegion(BARREIRO, 420, 392, "assets/map_coloring/barreiro.png"); regiao = colorindo_bh->getRegion(BARREIRO); EXPECT_EQ(regiao.nome, BARREIRO); EXPECT_EQ(regiao.cor.r, color.r); EXPECT_EQ(regiao.cor.g, color.g); EXPECT_EQ(regiao.cor.b, color.b); EXPECT_EQ(regiao.nome_cor, BRANCO); EXPECT_TRUE(regiao.mapa); } TEST(TestMapColoring, TestResetMap) { Map_Coloring* colorindo_bh = new Map_Coloring(); Regiao regiao; SDL_Color color = { 204, 204, 204 }; Nome nome_regioes[N_REGIOES_BH] = {VENDA_NOVA,NORTE,PAMPULHA,NORDESTE,NOROESTE,LESTE,OESTE,CENTRO_SUL,BARREIRO}; colorindo_bh->setRegionColorByIndex(1, AZUL); colorindo_bh->setRegionColorByIndex(0, AZUL); colorindo_bh->resetMap(); for (int i = 0; i < N_REGIOES_BH; i++) { regiao = colorindo_bh->getRegion(nome_regioes[i]); EXPECT_EQ(regiao.nome, nome_regioes[i]); EXPECT_EQ(regiao.nome_cor, BRANCO); EXPECT_EQ(regiao.cor.r, color.r); EXPECT_EQ(regiao.cor.g, color.g); EXPECT_EQ(regiao.cor.b, color.b); } } TEST(TestMapColoring, TestGameNotWon) { Map_Coloring* colorindo_bh = new Map_Coloring(); EXPECT_FALSE(colorindo_bh->gameWon()); } TEST(TestMapColoring, TestGetColorFromName) { Map_Coloring* colorindo_bh = new Map_Coloring(); SDL_Color azul = { 0, 158, 161 }; SDL_Color roxo = { 96, 62, 149 }; SDL_Color amarelo = { 250, 195, 43 }; SDL_Color rosa = { 215, 38, 93 }; SDL_Color branco = { 204, 204, 204 }; SDL_Color color; color = colorindo_bh->getColorFromName(AZUL); EXPECT_EQ(azul.r, color.r); EXPECT_EQ(azul.g, color.g); EXPECT_EQ(azul.b, color.b); color = colorindo_bh->getColorFromName(ROXO); EXPECT_EQ(roxo.r, color.r); EXPECT_EQ(roxo.g, color.g); EXPECT_EQ(roxo.b, color.b); color = colorindo_bh->getColorFromName(AMARELO); EXPECT_EQ(amarelo.r, color.r); EXPECT_EQ(amarelo.g, color.g); EXPECT_EQ(amarelo.b, color.b); color = colorindo_bh->getColorFromName(ROSA); EXPECT_EQ(rosa.r, color.r); EXPECT_EQ(rosa.g, color.g); EXPECT_EQ(rosa.b, color.b); color = colorindo_bh->getColorFromName(BRANCO); EXPECT_EQ(branco.r, color.r); EXPECT_EQ(branco.g, color.g); EXPECT_EQ(branco.b, color.b); } TEST(TestMapColoring, TestSetRegionColor) { Map_Coloring* colorindo_bh = new Map_Coloring(); Regiao regiao; Nome nome_regioes[N_REGIOES_BH] = { VENDA_NOVA,NORTE,PAMPULHA,NORDESTE,NOROESTE,LESTE,OESTE,CENTRO_SUL,BARREIRO }; SDL_Color color = colorindo_bh->getCurrentColor(); regiao = colorindo_bh->getRegion(BARREIRO); colorindo_bh->setRegionColor(&regiao); regiao = colorindo_bh->getRegion(BARREIRO); EXPECT_EQ(regiao.cor.r, color.r); EXPECT_EQ(regiao.cor.g, color.g); EXPECT_EQ(regiao.cor.b, color.b); } TEST(TestMapColoring, TestIsSafe) { Map_Coloring* colorindo_bh = new Map_Coloring(); EXPECT_TRUE(colorindo_bh->isSafe()); colorindo_bh->setRegionColorByIndex(1, AZUL); colorindo_bh->setRegionColorByIndex(0, AZUL); EXPECT_FALSE(colorindo_bh->isSafe()); } TEST(TestMapColoring, TestSetToCurrentColor) { Map_Coloring* colorindo_bh = new Map_Coloring(); SDL_Color color = colorindo_bh->getCurrentColor(); Regiao regiao; regiao = colorindo_bh->getRegion(BARREIRO); colorindo_bh->setToCurrentColor(&regiao); EXPECT_EQ(regiao.cor.r, color.r); EXPECT_EQ(regiao.cor.g, color.g); EXPECT_EQ(regiao.cor.b, color.b); } TEST(TestMapColoring, TestCurrentColor) { Map_Coloring* colorindo_bh = new Map_Coloring(); SDL_Color color = colorindo_bh->getCurrentColor(); SDL_Color expectedColor = colorindo_bh->getColorFromName(BRANCO); EXPECT_EQ(expectedColor.r, color.r); EXPECT_EQ(expectedColor.g, color.g); EXPECT_EQ(expectedColor.b, color.b); } TEST(TestMapColoring, TestCheckWin) { //setRegionColorByIndex(int i, Cor color) Map_Coloring* colorindo_bh = new Map_Coloring(); Nome nome_regioes[N_REGIOES_BH] = { VENDA_NOVA,NORTE,PAMPULHA,NORDESTE,NOROESTE,LESTE,OESTE,CENTRO_SUL,BARREIRO }; // Barreiro, Noroeste e Norte colorindo_bh->setRegionColorByIndex(8, AZUL); colorindo_bh->setRegionColorByIndex(4, AZUL); colorindo_bh->setRegionColorByIndex(1, AZUL); // Pampulha, Oeste e Leste colorindo_bh->setRegionColorByIndex(2, ROXO); colorindo_bh->setRegionColorByIndex(6, ROXO); colorindo_bh->setRegionColorByIndex(5, ROXO); EXPECT_FALSE(colorindo_bh->checkWin()); // Venda Nova, Nordeste e Centro-Sul colorindo_bh->setRegionColorByIndex(0, ROSA); colorindo_bh->setRegionColorByIndex(3, ROSA); colorindo_bh->setRegionColorByIndex(7, ROSA); EXPECT_TRUE(colorindo_bh->checkWin()); colorindo_bh->setRegionColorByIndex(0, AZUL); EXPECT_FALSE(colorindo_bh->checkWin()); } TEST(TestMapColoring, TestSetCurrentColor) { Map_Coloring* colorindo_bh = new Map_Coloring(); SDL_Color color = colorindo_bh->getColorFromName(BRANCO); colorindo_bh->setCurrentColor(BRANCO); SDL_Color currColor = colorindo_bh->getCurrentColor(); EXPECT_EQ(currColor.r, color.r); EXPECT_EQ(currColor.g, color.g); EXPECT_EQ(currColor.b, color.b); }
true
52325bf325bb70ad39e3df0279e2c3e8cc6d4114
C++
xUhEngwAng/oj-problems
/nowcoder/NC39 N皇后问题.cpp
UTF-8
1,124
2.828125
3
[]
no_license
class Solution { public: /** * * @param n int整型 the n * @return int整型 */ vector<pair<int, int>> positions; int ret = 0; bool is_violate(const pair<int, int>& lh, const pair<int, int>& rh){ if(lh.first == rh.first || lh.second == rh.second) return true; if(lh.first - lh.second == rh.first - rh.second) return true; if(lh.first + lh.second == rh.first + rh.second) return true; return false; } void dfs(int row, int col, int n){ positions.push_back({row, col}); for(int ix = 0; ix != positions.size() - 1; ++ix){ if(is_violate(positions[ix], positions.back())) goto clean; } if(row == n - 1){ ret += 1; goto clean; } for(int ix = 0; ix != n; ++ix){ dfs(row + 1, ix, n); } clean: positions.pop_back(); } int Nqueen(int n) { // write code here for(int ix = 0; ix != n; ++ix) dfs(0, ix, n); return ret; } };
true
efd67ddbf6ca26e3a6e258e9f21ebbceb11fdf41
C++
ajmarkestad/Fys4150
/Project3/main.cpp
UTF-8
6,893
2.953125
3
[]
no_license
#include <iostream> #include <cmath> #include <stdlib.h> #include "ensemble.h" #include "solver.h" #include <ostream> #include <sstream> #include <string> #include <fstream> using namespace std; ofstream ifile; void createparticles(Ensemble &system,int nargs, char **vargs, string input_file); int main(int nargs, char **vargs) { double years; int numTimesteps; if(nargs<7){ cout << "Incorrect usage!" << endl; cout << "Usage:$ ./Project3 <Choose method> <input file name> <output file name> <years> <numTimesteps> <planet1> <planet2> ..." << endl; cout << "Choose method: 0 for Euler, 1 for Verlet, 2 for Verlet with GR corrections" << endl; cout << "3 for Energies using Euler, and 4 for energies using Verlet" << endl; cout << "For all bodies in initial_data.txt use <planet1> = 0" << endl; return 1; } if (vargs[4]<0){ cout << "Negative years is not good!" << endl; return 1; }else{ years = atof(vargs[4]); } if (vargs[5]<0){ cout << "Negative timesteps is not good!" << endl; return 1; }else{ numTimesteps = atoi(vargs[5]); } string input_file(vargs[2]); string output_file(vargs[3]); Ensemble solarSystem; createparticles(solarSystem, nargs, vargs, input_file); vector<Particle> &bodies = solarSystem.bodies(); double dt = (double)years/(double)numTimesteps; if (atoi(vargs[1]) == 0){ Euler integrator(dt); for(int timestep=0; timestep<numTimesteps; timestep++) { integrator.integrateOneStep(solarSystem); solarSystem.writeToFile(output_file); } }else if(atoi(vargs[1]) == 1){ Verlet integrator(dt,solarSystem); for(int timestep=0; timestep<numTimesteps; timestep++) { integrator.integrateOneStep(solarSystem); solarSystem.writeToFile(output_file); } }else if (atoi(vargs[1]) == 2){ // Set some helper variables before we start the time integration. double rPreviousPrevious = 0; // Mercury-Sun-distance two times steps ago. double rPrevious = 0; // Mercury-Sun-distance of the previous time step. double angle = 0; vec3 previousPosition(0,0,0); // Mercury-Sun position vector of the previous time step. Verlet_GR integrator(dt, solarSystem); // This is the integration loop, in which you advance the solution (usually via a integrateOneStep() // function located in an integrator object, e.g. the Verlet class). for (int timeStep = 0; timeStep < numTimesteps; timeStep++) { // Integrate the solution one step forward in time, using the GR corrected force calcuation // and the Verlet algorithm. integrator.integrateOneStep(solarSystem); // Compute the current Mercury-Sun distance. This assumes there is a vector of planets, // called m_bodies, available, in which the Sun is m_bodies[0] and Mercury is m_bodies[1]. double rCurrent = (solarSystem.bodies()[1].position - solarSystem.bodies()[0].position).length(); // Check if the *previous* time step was a minimum for the Mercury-Sun distance. I.e. check // if the previous distance is smaller than the current one *and* the previous previous one. if ( rCurrent > rPrevious && rPrevious < rPreviousPrevious ) { // If we are perihelion, print *previous* angle (in radians) to terminal. double x = previousPosition.x(); double y = previousPosition.y(); angle = atan2(y,x); solarSystem.writeAngleToFile(output_file, angle); } // Update the helper variables (current, previous, previousPrevious). rPreviousPrevious = rPrevious; rPrevious = rCurrent; previousPosition = solarSystem.bodies()[1].position - solarSystem.bodies()[0].position; }}else if (atoi(vargs[1]) == 3){ solarSystem.calculateEnergy(); solarSystem.writeEnergiesToFile(output_file); Euler integrator(dt); for(int timestep=0; timestep<numTimesteps; timestep++) { integrator.integrateOneStep(solarSystem); solarSystem.calculateEnergy(); solarSystem.writeEnergiesToFile(output_file); } }else if (atoi(vargs[1]) == 4){ solarSystem.calculateEnergy(); solarSystem.writeEnergiesToFile(output_file); Verlet integrator(dt,solarSystem); for(int timestep=0; timestep<numTimesteps; timestep++) { integrator.integrateOneStep(solarSystem); solarSystem.calculateEnergy(); solarSystem.writeEnergiesToFile(output_file); } }else{ cout << "Choose method: 0 for Euler, 1 for Verlet, 2 for Verlet with GR corrections" << endl; return 1; } cout << "The final positions are: " << endl; for(int i = 0; i<(int)bodies.size(); i++) { Particle &body = bodies[i]; // Reference to this body cout << "Final status for particle with position: " << body.position << "length: " << body.position.length() << " and velociy: " << body.velocity << " and mass: " << body.mass << endl; } return 0; } void createparticles(Ensemble &system, int nargs, char **vargs, string input_file){ string line; ifstream myfile (input_file); if(myfile.is_open()){ getline(myfile,line); //skips date getline(myfile,line); //skips headerline while (getline(myfile,line)) { istringstream iss(line); string sub; iss >> sub; for(int i = 0; i<(nargs-6); i++){ if((atoi(sub.c_str())==atoi(vargs[i+6])) || ((nargs == 7) && atoi(vargs[6])==0)){ vec3 position(0,0,0); vec3 velocity(0,0,0); iss >> sub; position(0)=atof(sub.c_str()); iss >> sub; position(1)=atof(sub.c_str()); iss >> sub; position(2)=atof(sub.c_str()); iss >> sub; velocity(0)=atof(sub.c_str())*365; iss >> sub; velocity(1)=atof(sub.c_str())*365; iss >> sub; velocity(2)=atof(sub.c_str())*365; iss >> sub; system.createParticle( position, velocity, atof(sub.c_str())); cout << "Created a particle with initial position: " << position << "length: " << position.length() << " and velociy: " << velocity << " and mass: " << atof(sub.c_str()) << endl; } } } myfile.close(); }else{ cout << "Unable to open file" << endl; } }
true
d38b83315b2c471c72cdc2d77acec33828b523dc
C++
daixinye/zjucst
/c&cpp/1008/exam/7-1.cpp
UTF-8
1,279
3.25
3
[]
no_license
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> using namespace std; class Student { public: int department; string name; int height; int weight; Student(int d, string n, int h, int w){ department = d; name = n; height = h; weight = w; } void print(){ printf("%06d", department); cout<<" "<<name<<" "<<height<<" "<<weight<<endl; } }; int main(){ int N; cin>>N; map<int, int> stu_map; Student *stu_list[N+1]; string n; int d, h,w; for(int i = 1; i <= N; i++){ cin>>d; cin>>n; cin>>h; cin>>w; stu_list[i] = new Student(d, n, h, w); if(!stu_map[d]){ stu_map[d] = i; } else{ int c = stu_map[d]; stu_map[d] = stu_list[c]->height > h ? c : i; } } map<int,int>::iterator it; vector<int> s_v; it = stu_map.begin(); while(it != stu_map.end()){ s_v.push_back(it->first); it ++; } sort(s_v.begin(), s_v.end()); for(int j = 0; j < s_v.size(); j++){ stu_list[stu_map[s_v[j]]]->print(); } return 0; }
true
1e1fa0c7b8df40bf687cf079a021e39676ff04d4
C++
laomd-2/high-performance
/cuda/matrix/host_s.cpp
UTF-8
714
3.125
3
[]
no_license
// // Created by laomd on 2018/12/6. // #include <iostream> #include <vector> #include <ctime> using namespace std; typedef vector<double> DVector1D; void cal_one_ele(size_t i, size_t j, size_t n, double* P) { double sum = 0; for (int k = 0; k < n; ++k) { double a_ik = i - 0.1 * k + 1, b_kj = 0.2 * j - 0.1 * k; sum += a_ik * b_kj; } *(P + i * n + j) = sum; } int n = 5000; DVector1D result(n * n, 0); int main() { clock_t start = clock(); int i, j; for (i = 0; i < n; ++i) { for (j = 0; j < n; ++j) { cal_one_ele(i, j, n, result.data()); } } clock_t end = clock(); cout << (double)(end - start) / CLOCKS_PER_SEC << endl; }
true
46a20f08349ae242488e5ada874dd962224d21b9
C++
mskoenz/arduino_crash_course
/program/acc_recap/W3_01_eeprom_serialize/eeprom_serialize.cpp
UTF-8
2,621
3.328125
3
[ "WTFPL" ]
permissive
// Author: Mario S. Könz <mskoenz@gmx.net> // Date: 02.11.2013 14:47:10 CET // File: eeprom_serialize.cpp #include <Arduino.h> #include <EEPROM.h> //don't forget this header // main idea: -read and write to the EEPROM (is like a harddrive) // -EEPROM data remains even after the power is lost (no matter how long) // -serialize a type that is longer then a byte // -deserialize this type again // -(E)lectrically (E)rasable (P)rogrammable (R)ead (O)nly (M)emory // -read only just means that write is super slow (~ms) // connect: nothing class program { public: program() { setup(); } void setup() { Serial.begin(460800); Serial.println("-------------------Start EEPROM program"); //=================== read and write =================== for(int adr = 0; adr < 5; ++adr) { Serial.print("Old value at EEPROM adress "); Serial.print(adr); Serial.print(" = "); Serial.println(int(EEPROM.read(adr))); // adr has to be between 0-1023 / read return a byte } Serial.println("-------------------Starting to write in EEPROM"); for(int adr = 0; adr < 5; ++adr) EEPROM.write(adr, 255); //write takes the adress an a byte / this takes long (~ms) / change value to see an effect for(int adr = 0; adr < 10; ++adr) { Serial.print("New value at EEPROM adress "); Serial.print(adr); Serial.print(" = "); Serial.println(int(EEPROM.read(adr))); } //=================== serialize =================== // we can only store bytes in EEPROM. Larges types like an uint16_t (2 bytes) need to be serialized Serial.println("-------------------serialize example"); uint16_t val = 12345; Serial.print("the value to serialized is "); Serial.println(val); EEPROM.write(0, val & 0xFF); //0xFF = 0b11111111 is a mask that kills (set to 0) all but the last byte EEPROM.write(1, (val >> 8) & 0xFF); //val>>8 is a bit-shift operator that just shifts the bit 8 times to the right uint16_t val_from_eeprom = 0; val_from_eeprom += EEPROM.read(0); val_from_eeprom += EEPROM.read(1) << 8; //we need to shift this byte back again Serial.print("the deserialized value is "); Serial.println(val_from_eeprom); } void loop() { //nothing... } private: }; #include <main.hpp>
true
25623381d9cde6fa4161867bdd33b40105d7220a
C++
kwdeveloper/migrando-c-cpp
/cap12/lambda.cc
UTF-8
1,209
2.96875
3
[]
no_license
// Este programa utiliza a biblioteca Boost #include <iostream> #include <vector> #include <cmath> #include <boost\lambda\lambda.hpp> #include <boost\lambda\bind.hpp> #include <boost\lambda\if.hpp> using namespace std; using namespace boost::lambda; int f() { static int x = 0; return x++; } template<typename T> void Imprimir( const T &c, const string &header=" ", const string &sep=" ") { cout << header; for_each(c.begin(),c.end(), cout << _1 << sep); } int main() { vector<int> v1(10,0); for_each(v1.begin(),v1.end(),_1=bind(f)); Imprimir(v1,"\nv1: "); int arr1[] = {-1,10,2,3,-5,4,6,-7,0}; vector<int> v2(arr1,arr1+(sizeof(arr1)/sizeof(int))); for_each(v2.begin(),v2.end(), if_then(_1<0,_1=-_1) ); Imprimir(v2,"\nv2: "); vector<int> v3(arr1,arr1+(sizeof(arr1)/sizeof(int))); transform( v2.begin(),v2.end(),v3.begin(),v3.begin(), _1+_2 ); Imprimir(v3,"\nv3: "); int arr2[] = {4,16,25,49,64,81,144}; vector<int> v4(arr2,arr2+(sizeof(arr2)/sizeof(int))); vector<float> v5(sizeof(arr2)/sizeof(int),0); transform( v4.begin(),v4.end(),v5.begin(), bind<float,float>(sqrt,_1) ); Imprimir(v5,"\nv5: "); }
true
8d425620cb75fefd8e46a432fc766a25ec66ad6d
C++
Avraham1820/code-in-c
/Rational/main.cpp
UTF-8
843
2.71875
3
[]
no_license
//AUTHOR: Eliran shaharabani //IDs: 032472664 //KVUTZA: Gay yehezkel //TITTLE: Targil 1 Seif 1 //SUBJECT: /**************************************** * * * rational * * * * *****************************************/ #include <iostream> using namespace std; #include "Rational.h" int main() { cout << "enter two rational numbers\n"; bool bit=true; int a, b, c, d; char helpChar = '/'; cin >> a >> helpChar >> b >> c >> helpChar >> d; if (d==0||b == 0 || helpChar != '/') { cout << "ERROR\n"; return 0; } Rational k(a, b); Rational p(c, d); bit = k.equal(p); //bit = p.equal(k); if (bit|| k.get_mone() == 0 && p.get_mone()==0) cout << "equal"; else { cout << "different\n"; k.print(); cout << " "; p.print(); } system("pause"); return 0; }
true
fa01c06ac8fb3da2fd28b78f37acd1e2fc990ff9
C++
pmienk/hypodermic
/Hypodermic/TypeCaster.hpp
UTF-8
1,097
2.6875
3
[]
no_license
#ifdef HYPODERMIC_TYPE_CASTER_H_ # ifndef HYPODERMIC_TYPE_CASTER_HPP_ # define HYPODERMIC_TYPE_CASTER_HPP_ namespace Hypodermic { template <class ConcreteType, class InterfaceType> TypeCaster< ConcreteType, InterfaceType >::TypeCaster(const std::type_info& typeInfo) : typeInfo_(typeInfo) { } template <class ConcreteType, class InterfaceType> const std::type_info& TypeCaster< ConcreteType, InterfaceType >::typeInfo() const { return typeInfo_; } template <class ConcreteType, class InterfaceType> std::shared_ptr< void > TypeCaster< ConcreteType, InterfaceType >::cast(std::shared_ptr< void > concreteInstance) const { std::shared_ptr< ConcreteType > concreteTypeInstance = std::static_pointer_cast< ConcreteType >(concreteInstance); std::shared_ptr< InterfaceType > interfaceTypeInstance = concreteTypeInstance; return interfaceTypeInstance; } } // namespace Hypodermic # endif /* !HYPODERMIC_TYPE_CASTER_HPP_ */ #endif /* HYPODERMIC_TYPE_CASTER_H_ */
true
0c241e6665b064b9bf450158408f2cca535815dc
C++
hwangdav000/Bus_Simulation
/src/passenger_generator.h
UTF-8
1,567
3.125
3
[]
no_license
/** * @file passenger_generator.h * * @copyright 2019 3081 Staff, All rights reserved. */ #ifndef SRC_PASSENGER_GENERATOR_H_ #define SRC_PASSENGER_GENERATOR_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <list> #include "src/passenger_factory.h" #include "src/stop.h" /******************************************************************************* * Class Definitions ******************************************************************************/ class Stop; // forward declaration /** * @brief Passenger Generator Class * Generation of a passenger which holds list of probabilities and stops */ class PassengerGenerator { public: /** * @brief Constructs PassengerGenerator which takes in a double list and * stop list * * @param[in] std::list<double> holds generation probabilities for a passenger * at a stop * @param[in] std::list<Stop *> holds the stops for which we want to generate * passengers to */ PassengerGenerator(std::list<double>, std::list<Stop *>); // Makes the class abstract, cannot instantiate and forces subclass override /** * @brief generates passengers based on prob and stops given */ virtual int GeneratePassengers() = 0; // pure virtual protected: std::list<double> generation_probabilities_; std::list<Stop *> stops_; // should we be using a singleton here somehow? // PassengerFactory * pass_factory; }; #endif // SRC_PASSENGER_GENERATOR_H_
true
d0d6ff9517da598927f63a30a128119f038647a8
C++
institution/nn5
/src/ext/experimental/vals.hpp
UTF-8
930
3.40625
3
[]
no_license
#pragma once #include <type_traits> template <class I> struct Vals{ using KPV = typename I::value_type; using PV = typename std::tuple_element<1, KPV>::type; using V = typename std::remove_pointer<PV>::type; struct Iter{ I i; Iter(I i): i(i) {} void operator++() { ++i; } V & operator*() { return (*i).second; } V const& operator*() const { return *(*i).second; } bool operator!=(Iter other) const { return i != other.i; } }; Iter b,e; Vals(I && b, I && e): b(b), e(e) {} auto begin() { return b; } auto end() { return e; } }; /*template <class T, class F> void for_each(Vals<T> & xs, F f) { for (auto & x: xs) { F(x); } }*/ template <class T> auto list_values(T & t) { return Vals<typename T::iterator>(t.begin(), t.end()); } template <class T> auto list_values(T const& t) { return Vals<typename T::const_iterator>(t.begin(), t.end()); }
true
68207b3d2782ecd81c50ce01c46c41906082743d
C++
lmhtz/StdOS
/Libraries/Core/List.h
GB18030
1,276
3.40625
3
[]
no_license
#ifndef _List_H_ #define _List_H_ #include "Type.h" typedef int (*IComparer)(const void* v1, const void* v2); // 䳤бڴ洢ָ class IList { public: IComparer Comparer; // Ƚ IList(); inline int Count() const { return _Count; } // ӵԪ void Add(void* item); // ɾָλԪ void RemoveAt(int index); // ɾָԪ int Remove(const void* item); // ָʱ-1 int FindIndex(const void* item) const; // []ָԪصĵһ void* operator[](int i) const; private: int _Count; int _Capacity; uint32_t _tmpbuf[30]; private: void Init(); }; template<typename T> class List : public IList { static_assert(sizeof(T) <= 4, "List only support pointer or int"); public: // ӵԪ void Add(T item) { IList::Add((void*)item); } // ɾָԪ int Remove(const T item) { return IList::Remove((const void*)item); } // ָʱ-1 int FindIndex(const T item) const { return IList::FindIndex((const void*)item); } // []ָԪصĵһ T operator[](int i) const { return (T)IList::operator[](i); } }; #endif
true
6985b2835a26525449709b53791e0bfcfcd42777
C++
AFLplusplus/Grammar-Mutator
/lib/antlr4_shim/antlr4_shim.cpp
UTF-8
3,364
2.515625
3
[ "Apache-2.0" ]
permissive
/* american fuzzy lop++ - grammar mutator -------------------------------------- Written by Shengtuo Hu Copyright 2020 AFLplusplus Project. All rights reserved. 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 A grammar-based custom mutator written for GSoC '20. */ #include <exception> #include <antlr4-runtime.h> #include <GrammarLexer.h> #include <GrammarParser.h> #include "antlr4_shim.h" using namespace antlr4; node_t *node_from_parse_tree(antlr4::tree::ParseTree *t) { node_t *node = nullptr; if (antlrcpp::is<antlr4::tree::ErrorNode *>(t)) { // error - treat the error portion as a terminal node // we do not want to lose test case information auto terminal_node = dynamic_cast<antlr4::tree::TerminalNode *>(t); auto terminal_node_text = terminal_node->getText(); node = node_create(0); node_set_val(node, terminal_node_text.c_str(), terminal_node_text.length()); return node; } // terminal node if (antlrcpp::is<antlr4::tree::TerminalNode *>(t)) { auto terminal_node = dynamic_cast<antlr4::tree::TerminalNode *>(t); auto terminal_node_text = terminal_node->getText(); node = node_create(0); node_set_val(node, terminal_node_text.c_str(), terminal_node_text.length()); return node; } if (!antlrcpp::is<antlr4::ParserRuleContext *>(t)) { // error return nullptr; } // non-terminal node auto non_terminal_node = dynamic_cast<antlr4::ParserRuleContext *>(t); node = node_create_with_rule_id(non_terminal_node->getRuleIndex(), non_terminal_node->getAltNumber() - 1); node_init_subnodes(node, t->children.size()); node_t *subnode; for (uint32_t i = 0; i < node->subnode_count; ++i) { auto &child = t->children[i]; subnode = node_from_parse_tree(child); node->subnodes[i] = subnode; subnode->parent = node; } return node; } tree_t *tree_from_buf(const uint8_t *data_buf, size_t data_size) { node_t *root; /** * Use try/catch to handle exceptions from ANTLR4 runtime library. If any * errors occur, a nullptr will be returned. * * A known issue: ANTLRInputStream does not accept string with special * character (https://github.com/antlr/antlr4/issues/2036) */ try { ANTLRInputStream input((const char *)data_buf, data_size); GrammarLexer lexer(&input); // Disable lexer error output lexer.removeErrorListener(&ConsoleErrorListener::INSTANCE); CommonTokenStream tokens(&lexer); tokens.fill(); GrammarParser parser(&tokens); // Disable parser error output parser.removeErrorListener(&ConsoleErrorListener::INSTANCE); antlr4::tree::ParseTree *parse_tree = parser.entry(); if (!parse_tree->children.size()) { #ifdef DEBUG_BUILD fprintf(stderr, "ANTLR4 parsing error: No child nodes\n"); #endif return nullptr; } root = node_from_parse_tree(parse_tree->children[0]); } catch (std::exception &e) { #ifdef DEBUG_BUILD fprintf(stderr, "ANTLR4 parsing error: %s\n", e.what()); #endif return nullptr; } if (!root) return nullptr; // parse error tree_t *tree = tree_create(); tree->root = root; return tree; }
true
647bd6903204d460b225d6b9e281379437a90b29
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/14_18039_8.cpp
UTF-8
2,015
2.734375
3
[]
no_license
#include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <map> #include <set> #include <unordered_map> #include <unordered_set> using namespace std; int qn, pn; int gcd(int a, int b) { if (b) return gcd(b, a%b); return a; } int ending; int sub(int p1, int q1, int p2, int q2) { if (q1 == 0) { return 0; } // int qn, pn; if (p1 * q2 >= q1 * p2) { pn = p1 * q2 - p2 * q1; qn = q1 * q2; // cout << "pn" << pn << endl; if (pn == 0) { ending = true; // printf("%d/%d - %d/%d stop\n", p1, q1, p2, q2); return 1; } int g = gcd(pn, qn); pn = pn / g; qn = qn / g; // printf("%d/%d - %d/%d yes\n", p1, q1, p2, q2); return 1; } else { pn = p1; qn = q1; // printf("%d/%d - %d/%d no\n", p1, q1, p2, q2); return 0; } } int a[33]; void solve(int p1, int q1) { int p2 = 1; int q2 = 1; for (int i = 1; i < 33; i++) { q2 *= 2; a[i] = sub(p1, q1, p2, q2); if (ending) { break; } p1 = pn; q1 = qn; } // cout << p1 << " " << q1 << endl; } int main() { int t; cin >> t; for (int Case = 1; Case <= t; ++Case) { int p, q; scanf("%d/%d", &p, &q); int g= gcd(p, q); p /= g; q /= g; int i = 1; int t = 0; while (i < q) { i *= 2; t += 1; } // cout << "i" << i << endl; if (i != q) { // cout << "impossible" << endl; printf("Case #%d: impossible\n", Case); } else { int t = 0; while (p < q) { p *= 2; t += 1; } // cout << t << endl; printf("Case #%d: %d\n", Case, t); } } }
true
16fffa521dd1f22d568a714592f3f63afdef94d4
C++
kkyyou/Mini_CAM_Solution
/pad.cpp
UTF-8
1,378
2.796875
3
[]
no_license
#include "pad.h" #include <QPainterPath> CPad::CPad(const QPoint &center) : CFeature(_FEATURE_PAD), m_center(center) { } QPoint CPad::getCenterPoint() { return m_center; } QString CPad::getPointInfo() { QPoint center = getCenterPoint(); double dx = (double) center.x() / _MILLION; double dy = (double) center.y() / _MILLION; QString strX = QString::number(dx, 'f', 3); QString strY = QString::number(dy, 'f', 3); return "x = " + strX + ", " + "y = " + strY; } QString CPad::getSizeInfo() { return shape()->getSizeInfo(); } void CPad::calcArea() { QPainterPath path; SHAPE_TYPE shapeType = shape()->type(); if (shapeType == _SHAPE_ROUND) { long radius = shape()->getRadius(); path.addEllipse(m_center, radius, radius); } else if (shapeType == _SHAPE_RECT) { long width = shape()->getWidth(); long height = shape()->getHeight(); long left = m_center.x() - (width / 2); long right = m_center.x() + (width / 2); long bottom = m_center.y() - (height / 2); long top = m_center.y() + (height / 2); path.moveTo(QPoint(left, bottom)); path.lineTo(QPoint(left, top)); path.lineTo(QPoint(right, top)); path.lineTo(QPoint(right, bottom)); path.lineTo(QPoint(left, bottom)); } m_areaPath = path; }
true
065a199afcb27c927388923096c04c43c115626c
C++
gabb99/tsjson
/gTests/array_object.tests.cpp
UTF-8
13,617
2.53125
3
[ "MIT" ]
permissive
// // array_object.tests.cpp // tsjson // // Created by Gabriel Beauchemin on 2018-12-05. // Copyright © 2018 Gabriel Beauchemin. All rights reserved. // #include "gtest/gtest.h" // Use rapidjson for validation #include "document.h" // rapidjson's DOM-style API using namespace rapidjson; #include "tsobject.hpp" #include "tsstream.hpp" using namespace tsjson; #include "tsjson_cjson.hpp" #include "tsjson_sajson.hpp" #include "tsjson_rapidjson.hpp" #include "tsjson_taocpp.hpp" #include "tsjson_minijson.hpp" #include "tsjson_nlohmannjson.hpp" namespace { std::string enumToString(tsjson::impl t) { switch (t) { case impl::cjson: return "impl::cjson"; case impl::rapidjson: return "impl::rapidjson"; case impl::sajson: return "impl::sajson"; case impl::nlohmannj_son: return "impl::nlohmannj_son"; case impl::minijson: return "impl::minijson"; case impl::taojson: return "impl::taojson"; } assert(false); } template <tsjson::impl T> class CtorStaticArrayTest : public ::testing::Test { struct simple : object<struct simple> { simple() : object<struct simple>(), alive(object<struct simple>::_, "alive", true), age(object<struct simple>::_, "age", 34u), ranking(object<struct simple>::_, "ranking", 0.125f), name(object<struct simple>::_, "name", "Hi"), booleans(object<struct simple>::_, "booleans"), integers(object<struct simple>::_, "integers"), numbers(object<struct simple>::_, "numbers"), strings(object<struct simple>::_, "strings") {} boolean alive; integer age; number ranking; string name; array<boolean, 3> booleans; array<integer> integers; array<number, 5> numbers; array<string> strings; }; public: void TestBody() { simple v; EXPECT_EQ(v.alive, true) << enumToString(T); EXPECT_EQ(v.age, 34u) << enumToString(T); EXPECT_DOUBLE_EQ(v.ranking, 0.125f) << enumToString(T); EXPECT_EQ(v.name, "Hi") << enumToString(T); for (auto&& it : v.booleans) { EXPECT_TRUE(it.undefined()) << enumToString(T); } for (auto&& it : v.integers) { EXPECT_TRUE(it.undefined()) << enumToString(T); } for (auto&& it : v.numbers) { EXPECT_TRUE(it.undefined()) << enumToString(T); } for (auto&& it : v.strings) { EXPECT_TRUE(it.undefined()) << enumToString(T); } } }; template <tsjson::impl T> void CompareSerializations(const std::string& json1, const std::string& json2) { Document document1; // Default template parameter uses UTF8 and MemoryPoolAllocator. EXPECT_FALSE(document1.Parse(json1.c_str()).HasParseError()) << enumToString(T); Document document2; // Default template parameter uses UTF8 and MemoryPoolAllocator. EXPECT_FALSE(document2.Parse(json2.c_str()).HasParseError()) << enumToString(T); if (document1 != document2) { FAIL() << json1 << std::endl << json2 << " :" << enumToString(T); } } template <tsjson::impl T> class SerializationTopLevelArrayTest : public ::testing::Test { struct simple : object<struct simple> { simple() : object<struct simple>(), alive(object<struct simple>::_, "alive", true), age(object<struct simple>::_, "age", 34u), ranking(object<struct simple>::_, "ranking", 0.125f), name(object<struct simple>::_, "name", "Hi") {} boolean alive; integer age; number ranking; string name; }; public: void TestBody() { array<simple, 3> v; std::ostringstream ost; stream<T>(v).serialize(ost, false); CompareSerializations<T>(ost.str(), "[ {\"name\":\"Hi\", \"alive\":true, \"age\":34, \"ranking\":0.125 }, " "{\"name\":\"Hi\", \"alive\":true, \"age\":34, \"ranking\":0.125 }, " "{\"name\":\"Hi\", \"alive\":true, \"age\":34, \"ranking\":0.125 } ]"); { array<simple,4> w; std::istringstream ist("[ {\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 }, " "{\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 }, " "{\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 }, " "{\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 } ]"); stream<T>(w).deserialize(ist); for (auto&& c : w) { EXPECT_TRUE(c.name == "Ho") << enumToString(T); EXPECT_FALSE(c.alive) << enumToString(T); EXPECT_EQ(c.age, 56) << enumToString(T); EXPECT_EQ(c.ranking, 0.5) << enumToString(T); } } { array<simple> w; std::istringstream ist("[ {\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 }, " "{\"name\":\"Ho\", \"alive\":false, \"age\":56, \"ranking\":0.5 } ]"); stream<T>(w).deserialize(ist); EXPECT_EQ(w.size(), 2); for (auto&& c : w) { EXPECT_TRUE(c.name == "Ho") << enumToString(T); EXPECT_FALSE(c.alive) << enumToString(T); EXPECT_EQ(c.age, 56) << enumToString(T); EXPECT_EQ(c.ranking, 0.5) << enumToString(T); } } } }; template <tsjson::impl T> class SerializationArrayTest : public ::testing::Test { struct simple : object<struct simple> { simple() : object<struct simple>(), alive(object<struct simple>::_, "alive", true), age(object<struct simple>::_, "age", 34u), ranking(object<struct simple>::_, "ranking", 0.125f), name(object<struct simple>::_, "name", "Hi"), booleans(object<struct simple>::_, "booleans"), integers(object<struct simple>::_, "integers"), numbers(object<struct simple>::_, "numbers"), strings(object<struct simple>::_, "strings") {} boolean alive; integer age; number ranking; string name; array<boolean, 3> booleans; array<integer> integers; array<number, 5> numbers; array<string> strings; }; public: void TestBody() { simple v; // Add items to integers, strings v.integers.resize(4); for (auto&& it : v.integers) { it = 5; } v.strings.resize(6); for (auto&& it : v.strings) { it = "Me"; } { std::ostringstream ost; stream<T>(v).serialize(ost, false); CompareSerializations<T>(ost.str(), "{ \"booleans\":[], " "\"integers\":[5, 5, 5, 5], " "\"numbers\":[], " "\"strings\":[\"Me\", \"Me\", \"Me\", \"Me\", \"Me\", \"Me\"], " "\"name\":\"Hi\", \"alive\":true, \"age\":34, \"ranking\":0.125 }"); } { std::ostringstream ost; for (auto&& it : v.booleans) { it = true; } for (auto&& it : v.integers) { it += 10; } for (auto&& it : v.numbers) { it += 100.5; } for (auto&& it : v.strings) { it += "Hi"; } stream<T>(v).serialize(ost, false); CompareSerializations<T>(ost.str(), "{ \"booleans\":[true, true, true], " "\"integers\":[15, 15, 15, 15], " "\"numbers\":[100.5, 100.5, 100.5, 100.5, 100.5], " "\"strings\":[\"MeHi\", \"MeHi\", \"MeHi\", \"MeHi\", \"MeHi\", \"MeHi\"], " "\"name\":\"Hi\", \"alive\":true, \"age\":34, \"ranking\":0.125 }"); } } }; template <tsjson::impl T> class DeserializationArrayTest : public ::testing::Test { struct simple : object<struct simple> { simple() : object<struct simple>(), alive(object<struct simple>::_, "alive", true), age(object<struct simple>::_, "age", 34u), ranking(object<struct simple>::_, "ranking", 0.125f), name(object<struct simple>::_, "name", "Hi"), booleans(object<struct simple>::_, "booleans"), integers(object<struct simple>::_, "integers"), numbers(object<struct simple>::_, "numbers"), strings(object<struct simple>::_, "strings") {} boolean alive; integer age; number ranking; string name; struct array<boolean, 3> booleans; struct array<integer> integers; struct array<number, 5> numbers; struct array<string> strings; }; public: void TestBody() { simple v; std::istringstream ist("{ \"booleans\":[true, true, true], " "\"integers\":[10, 10, 10, 10], " "\"numbers\":[100.5, 100.5, 100.5, 100.5, 100.5], " "\"strings\":[\"Hi\", \"Hi\", \"Hi\", \"Hi\", \"Hi\", \"Hi\"], " "\"name\":\"Me\", \"alive\":false, \"age\":56, \"ranking\":0.5 }"); stream<T>(v).deserialize(ist); EXPECT_TRUE(v.alive == false) << enumToString(T); EXPECT_TRUE(v.age == 56u) << enumToString(T); EXPECT_DOUBLE_EQ(v.ranking, .5f) << enumToString(T); EXPECT_TRUE(v.name == "Me") << enumToString(T); EXPECT_EQ(v.booleans.size(), 3); for (auto&& it : v.booleans) { EXPECT_TRUE(it == true) << enumToString(T); } EXPECT_EQ(v.integers.size(), 4); for (auto&& it : v.integers) { EXPECT_TRUE(it == 10) << enumToString(T); } EXPECT_EQ(v.numbers.size(), 5); for (auto&& it : v.numbers) { EXPECT_TRUE(it == 100.5) << enumToString(T); } EXPECT_EQ(v.strings.size(), 6); for (auto&& it : v.strings) { EXPECT_TRUE(it == "Hi") << enumToString(T); } } }; template <tsjson::impl T> class ComplexArrayTest : public ::testing::Test { struct simple : object<struct simple> { struct inner : object<struct inner> { inner() : object<struct inner>(), alive(object<struct inner>::_, "alive"), age(object<struct inner>::_, "age"), ranking(object<struct inner>::_, "ranking") {} boolean alive; integer age; number ranking; }; simple() : object<struct simple>(), name(object<struct simple>::_, "name"), inners(object<struct simple>::_, "inners") {} string name; array<array<array<inner, 2>>> inners; }; public: void TestBody() { simple v; std::istringstream ist("{ \"inners\": [[[{\"alive\": true,\"age\": 34,\"ranking\": 0.125},{\"alive\": false,\"age\": 54,\"ranking\": 0.5}]]],\"name\": \"Me\"}"); stream<T>(v).deserialize(ist); EXPECT_TRUE(v.name == "Me") << enumToString(T); EXPECT_EQ(v.inners.size(), 1) << enumToString(T); EXPECT_EQ(v.inners[0].size(), 1) << enumToString(T); EXPECT_EQ(v.inners[0][0].size(), 2) << enumToString(T); EXPECT_TRUE(v.inners[0][0][0].alive) << enumToString(T); EXPECT_FALSE(v.inners[0][0][1].alive) << enumToString(T); EXPECT_EQ(v.inners[0][0][0].age, 34) << enumToString(T); EXPECT_EQ(v.inners[0][0][1].age, 54) << enumToString(T); EXPECT_EQ(v.inners[0][0][0].ranking, 0.125) << enumToString(T); EXPECT_EQ(v.inners[0][0][1].ranking, 0.5) << enumToString(T); } }; } TEST(array_object, ctor) { CtorStaticArrayTest<impl::cjson>().TestBody(); CtorStaticArrayTest<impl::rapidjson>().TestBody(); CtorStaticArrayTest<impl::sajson>().TestBody(); CtorStaticArrayTest<impl::nlohmannj_son>().TestBody(); CtorStaticArrayTest<impl::minijson>().TestBody(); CtorStaticArrayTest<impl::taojson>().TestBody(); } TEST(array_deserialization, ctor) { DeserializationArrayTest<impl::cjson>().TestBody(); DeserializationArrayTest<impl::rapidjson>().TestBody(); DeserializationArrayTest<impl::sajson>().TestBody(); DeserializationArrayTest<impl::nlohmannj_son>().TestBody(); DeserializationArrayTest<impl::minijson>().TestBody(); DeserializationArrayTest<impl::taojson>().TestBody(); } TEST(array_serialization, ctor) { SerializationArrayTest<impl::cjson>().TestBody(); SerializationArrayTest<impl::rapidjson>().TestBody(); SerializationArrayTest<impl::nlohmannj_son>().TestBody(); SerializationArrayTest<impl::minijson>().TestBody(); SerializationArrayTest<impl::taojson>().TestBody(); } TEST(top_array_serialization, ctor) { SerializationTopLevelArrayTest<impl::cjson>().TestBody(); // SerializationTopLevelArrayTest<impl::rapidjson>().TestBody(); SerializationTopLevelArrayTest<impl::nlohmannj_son>().TestBody(); SerializationTopLevelArrayTest<impl::minijson>().TestBody(); SerializationTopLevelArrayTest<impl::taojson>().TestBody(); } TEST(complex_array, ctor) { ComplexArrayTest<impl::cjson>().TestBody(); ComplexArrayTest<impl::rapidjson>().TestBody(); ComplexArrayTest<impl::sajson>().TestBody(); ComplexArrayTest<impl::nlohmannj_son>().TestBody(); ComplexArrayTest<impl::minijson>().TestBody(); ComplexArrayTest<impl::taojson>().TestBody(); }
true
601df96a57f30920bda9e784471b4ad8d872b8e5
C++
nanocurrency/nano-node
/nano/secure/network_filter.hpp
UTF-8
2,799
2.984375
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <nano/lib/numbers.hpp> #include <mutex> #include <cryptopp/seckey.h> #include <cryptopp/siphash.h> namespace nano { /** * A probabilistic duplicate filter based on directed map caches, using SipHash 2/4/128 * The probability of false negatives (unique packet marked as duplicate) is the probability of a 128-bit SipHash collision. * The probability of false positives (duplicate packet marked as unique) shrinks with a larger filter. * @note This class is thread-safe. */ class network_filter final { public: network_filter () = delete; network_filter (size_t size_a); /** * Reads \p count_a bytes starting from \p bytes_a and inserts the siphash digest in the filter. * @param \p digest_a if given, will be set to the resulting siphash digest * @warning will read out of bounds if [ \p bytes_a, \p bytes_a + \p count_a ] is not a valid range * @return a boolean representing the previous existence of the hash in the filter. **/ bool apply (uint8_t const * bytes_a, size_t count_a, nano::uint128_t * digest_a = nullptr); /** * Sets the corresponding element in the filter to zero, if it matches \p digest_a exactly. **/ void clear (nano::uint128_t const & digest_a); /** * Clear many digests from the filter **/ void clear (std::vector<nano::uint128_t> const &); /** * Reads \p count_a bytes starting from \p bytes_a and digests the contents. * Then, sets the corresponding element in the filter to zero, if it matches the digest exactly. * @warning will read out of bounds if [ \p bytes_a, \p bytes_a + \p count_a ] is not a valid range **/ void clear (uint8_t const * bytes_a, size_t count_a); /** * Serializes \p object_a and clears the resulting siphash digest from the filter. * @return a boolean representing the previous existence of the hash in the filter. **/ template <typename OBJECT> void clear (OBJECT const & object_a); /** Sets every element of the filter to zero, keeping its size and capacity. */ void clear (); /** * Serializes \p object_a and returns the resulting siphash digest */ template <typename OBJECT> nano::uint128_t hash (OBJECT const & object_a) const; private: using siphash_t = CryptoPP::SipHash<2, 4, true>; /** * Get element from digest. * @note must have a lock on mutex * @return a reference to the element with key \p hash_a **/ nano::uint128_t & get_element (nano::uint128_t const & hash_a); /** * Hashes \p count_a bytes starting from \p bytes_a . * @return the siphash digest of the contents in \p bytes_a . **/ nano::uint128_t hash (uint8_t const * bytes_a, size_t count_a) const; std::vector<nano::uint128_t> items; CryptoPP::SecByteBlock key{ siphash_t::KEYLENGTH }; nano::mutex mutex{ mutex_identifier (mutexes::network_filter) }; }; }
true
b5e5f3f4a00d3d6fa45aaffdcfdf1dcb4b5d4bab
C++
bpiatek91/ACC-1337
/Lab5/dateVS.cpp
UTF-8
338
2.734375
3
[]
no_license
#include <iostream> #include <string> #include <iomanip> #include "dateVS.hpp" using namespace std; int main() { Date date; int m, d, y; cout << "Welcome to the date converter"; while (true) { cout << "Please enter the month: "; cin >> m; cout << "Please enter the day: "; cin >> d; cout << "Please enter the year: "; } }
true
fa0062ceed92acf75505654f41413da39e1a1126
C++
phartz/Whac-A-Mol
/src/main.cpp
UTF-8
2,839
2.703125
3
[]
no_license
#include <MD_Parola.h> #include <MD_MAX72xx.h> #include <SPI.h> // Define the number of devices we have in the chain and the hardware interface // NOTE: These pin numbers will probably not work with your hardware and may // need to be adapted #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 8 #define CLK_PIN 13 #define DATA_PIN 11 #define CS_PIN 10 // Hardware SPI connection MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); // Arbitrary output pins // MD_Parola P = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES); #define SPEED_TIME 25 #define PAUSE_TIME 1000 int moleCnt[] = {0,0}; int effectSpeed = 0; int maxCount = 50; const char *countdown[] = { "- 1 -", "- 2 -", "- 3 -", }; textEffect_t effect[] = { PA_SCROLL_LEFT, PA_WIPE, PA_RANDOM, PA_FADE, PA_OPENING_CURSOR, PA_CLOSING, PA_SCAN_VERT, PA_WIPE_CURSOR, PA_OPENING, PA_CLOSING_CURSOR, PA_SCROLL_DOWN_RIGHT, PA_SCROLL_RIGHT, PA_SCROLL_DOWN, }; void doCountdown() { for (int i = 2; i >= 0; i--) { P.displayZoneText(0, countdown[i], PA_CENTER, effectSpeed, PAUSE_TIME, PA_OPENING_CURSOR, PA_PRINT); P.displayZoneText(1, countdown[i], PA_CENTER, effectSpeed, PAUSE_TIME, PA_OPENING_CURSOR, PA_PRINT); while (!P.getZoneStatus(0)) P.displayAnimate(); } } void setup(void) { P.begin(2); P.setZone(0,0,3); P.setZone(1,4,7); randomSeed(analogRead(0)); effectSpeed = P.getSpeed() * 5; } void incCount(uint8_t id){ moleCnt[id]++; char buffer1[32]; char buffer2[32]; itoa(moleCnt[0], buffer1, 10); P.displayZoneText(0, buffer1, PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); itoa(moleCnt[1], buffer2, 10); P.displayZoneText(1, buffer2, PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); P.displayAnimate(); } void loop(void) { P.displayZoneText(0, "Mole 1", PA_CENTER, effectSpeed, PAUSE_TIME, effect[random(13)], PA_PRINT); P.displayZoneText(1, "Mole 2", PA_CENTER, effectSpeed, PAUSE_TIME, effect[random(13)], PA_PRINT); while (!P.getZoneStatus(0)) P.displayAnimate(); delay(2000); doCountdown(); while (true) { incCount(random(50)%2); if (moleCnt[0] == maxCount || moleCnt[1] == maxCount) { if (moleCnt[0] > moleCnt[1]) { P.displayZoneText(0, "Winner!", PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); P.displayZoneText(1, "Lost!", PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); } else { P.displayZoneText(0, "Lost!", PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); P.displayZoneText(1, "Winner!", PA_CENTER, 0, 0, PA_PRINT, PA_PRINT); } P.displayAnimate(); moleCnt[0] = 0; moleCnt[1] = 0; delay(5000); P.displayClear(); break; } delay(80); } }
true
d12db87dafaac21edf9e569d9d783b962c3be91b
C++
parhelia512/core-impact
/source/CIStardustModel.cpp
UTF-8
3,423
2.828125
3
[]
no_license
// // CIStardustModel.cpp // CoreImpact // // This model class represents all the information for a single stardust. // // Created by Brandon Stein on 3/1/21. // Copyright © 2021 Game Design Initiative at Cornell. All rights reserved. // #include "CIStardustModel.h" /** Maximum speed of a stardust */ #define MAX_SPEED 10.0f #pragma mark Properties /** * Sets the velocity of this stardust. * * This value is necessary to control momementum in stardust movement. * * @param value the velocity of this stardust */ void StardustModel::setVelocity(cugl::Vec2 value) { _velocity = value; if (_velocity.length() > MAX_SPEED) { _velocity.scale(MAX_SPEED / _velocity.length()); } } #pragma mark Constructors /** * Creates a new stardust at the origin. */ StardustModel::StardustModel() { _position.set(0,0); _color = CIColor::blue; } /** * Destroys this stardust, releasing all resources. */ void StardustModel::dispose() { _mass = 0; } /** * Initializes a new stardust at the given location * * This method does NOT create a scene graph node for this stardust. You * must call setTexture for that. * * @param position The initial position of the stardust * @param velocity The initial velocity of the stardust * @param c The color code of the stardust * * @return true if the initialization was successful */ bool StardustModel::init(cugl::Vec2 position, cugl::Vec2 velocity, CIColor::Value c) { _position = position; _color = c; _mass = 1; _radius = 1; _isDragged = false; _isInteractable = true; _velocity = velocity; _stardust_location = CILocation::Value::ON_SCREEN; _previous_owner = -1; _stardust_type = Type::NORMAL; _hitCooldown = 0; return true; } /** * Initializes a new stardust at the given location * * This method does NOT create a scene graph node for this stardust. You * must call setTexture for that. * * @param position The initial position of the particle * @param velocity The initial velocity of the particle * @param c The color code of the particle * @param size The size of the particle * @param lifespan Time to live of the particle * * @return true if the initialization was successful */ bool StardustModel::initParticle(cugl::Vec2 position, cugl::Vec2 velocity, CIColor::Value c, float size, float lifespan) { _position = position; _color = c; _mass = lifespan; _radius = size; _isDragged = false; _isInteractable = false; _velocity = velocity; _stardust_location = CILocation::Value::ON_SCREEN; _previous_owner = -1; _stardust_type = Type::NORMAL; _hitCooldown = 0; return true; } /** * Flags the stardust for deletion. * * This just sets the mass of the stardust to be negative. * That way it is removed soon after during the collection phase. */ void StardustModel::destroy() { _mass = -1; } #pragma mark Movement /** * Updates the state of the model * * This method moves the stardust in accordance with the forces applied. * It also steps the hit cooldown timer if it is active. * * @param timestep Time elapsed since last called. */ void StardustModel::update(float timestep) { _position += _velocity; if (_hitCooldown > 0) { _hitCooldown -= timestep; if (_hitCooldown < 0) { _hitCooldown = 0; } } if (!_isInteractable) { _mass -= 1; } }
true
c4ef821c7f177b484c20c734ad5d9d04714714b6
C++
SimonaMihai31/C-Math-Programs
/Edge_covering_number_and_a_minimum-edge_cover;/Edge_Cover/edge-cover/main.cpp
UTF-8
286
3.515625
4
[]
no_license
// C++ program to find Edge Cover #include <bits/stdc++.h> using namespace std; // Function that calculates Edge Cover int edgeCover(int n) { float result = 0; result = ceil(n / 2.0); return result; } // Driver Code int main() { int n = 5; cout << edgeCover(n); return 0; }
true
d455c81221bfc0dee38ac3d176c4cf113d2e900c
C++
kk4ne/First-Repsitory
/sum.cpp
UTF-8
214
3.125
3
[]
no_license
#include <iostream> using namespace std; int Sum (int a, int b) { return a+b; } void main() { cout <<" Hello, GIT" << endl; int a, b; cout << "Enter two numbers: "; cin >> a >> b; Sum(a,b) }
true
c3545d17c3ca894fa46f830499fb740292f1bfdf
C++
teohklun/imdc2020_DHL_Google
/building-an-app/building-an-app-2/abc.cpp
UTF-8
6,837
3.015625
3
[]
no_license
#include <iostream> #include <ctime> #include <stdlib.h> #include <stdio.h> #include <fstream> using namespace std; //declare constant - problem specification, population size const int GENE = 8; const int CAPACITY = 104; const int POP_SIZE = 30; const int WEIGHT[GENE] = { 25, 35, 45, 5, 25, 3, 2, 2 }; const float CO_probability = 0.9; const float MUT_PROBABILITY = 0.9; const int MAX_GENERATION = 10; double bestFitness = 99.9; double avgFitness = 0.0; int bestChromosome[GENE]; ofstream bestFitnessFile, avgFitnessFile, bestChromosomeFile; //declare chromosomes data structure int chromosome[POP_SIZE][GENE]; //declare fitness data structure double fitness[POP_SIZE]; //declare parents data structure int parents[2][GENE]; //declare children data structure int children[2][GENE]; //declare chromosomes data structure = buffer int newChromosome[POP_SIZE][GENE]; //declare the new hromosome counter int newChromoCounter=0; void initializePopulation() { int randNum; //initialize random seed srand(time(NULL)); //SOURCE;http://www.cplusplus.com/reference/cstdlib/srand/ for (int c = 0; c < POP_SIZE; c++) { for (int i = 0; i < GENE; i++) { randNum = rand() % 2; chromosome[c][i] = randNum; } } } /* rand(): Returns a pseudo-random integral number in the range between 0 and RAND_MAX. RAND_MAX: This value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation. example: v1 = rand() % 100; // v1 in the range 0 to 99 v2 = rand() % 100 + 1; // v2 in the range 1 to 100 v3 = rand() % 30 + 1985; // v3 in the range 1985-2014 */ void printChromosome() { for (int c = 0; c < POP_SIZE; c++) { cout << "\tC" << c << "\t"; for (int i = 0; i < GENE; i++) { cout << chromosome[c][i] << " "; } cout << endl; } } void evaluateChromosome() { int accumulatedWeight = 0; for (int c = 0; c < POP_SIZE; c++) { accumulatedWeight = 0; for (int i = 0; i < GENE; i++) { if (chromosome[c][i] == 1) { accumulatedWeight = accumulatedWeight + WEIGHT[i]; } } fitness[c] = abs(CAPACITY - accumulatedWeight) / (float)CAPACITY; cout << "\tC" << c << "\tDifference\t" << abs(CAPACITY - accumulatedWeight) << "\tFV\t" << fitness[c] << endl; } } void parentSelection() { int player1, player2;//for players int indexParents[2];//index of selected players do { for (int i = 0; i < 2; i++) { do { player1 = rand() % POP_SIZE; player2 = rand() % POP_SIZE; } while (player1 == player2); cout << "Round" << i << "Player1:" << player1 << endl; cout << "Round" << i << "Player2:" << player2 << endl; if (fitness[player1] <= fitness[player2]) { indexParents[i] = player1; } else { indexParents[i] = player2; } cout << "Winner Chromosome: Chromosome " << indexParents[i] << " " << fitness[indexParents[i]] << endl << endl; } } while (indexParents[0] == indexParents[1]); for (int p = 0; p < 2; p++) { cout << "Parents" << p + 1; for (int g = 0; g < GENE; g++) { parents[p][g] = chromosome[indexParents[p]][g]; cout << " " << parents[p][g]; } cout << endl; } } void crossover() { float prob = 0; int co_point; for (int p = 0; p < 2; p++) { for (int g = 0; g < GENE; g++) { children[p][g] = parents[p][g]; } } prob = ((rand() % 10) + 1) / 10.0; if (prob < CO_probability) { co_point = rand() % GENE; cout << "\nChildren crossover at =" << co_point; for (int g = co_point; g < GENE; g++) { children[0][g] = parents[1][g]; children[1][g] = parents[0][g]; } } else { cout << "\nCrossover did not happen "; } for (int c = 0; c < 2; c++) { cout << "\nChildren" << c + 1 << ": "; for (int g = 0; g < GENE; g++) { cout << children[c][g] << " "; } cout << endl; } } void mutation() { float prob; int mut_point; for (int c = 0; c < 2; c++) { prob = (rand() % 11) / 10.0; if (prob < MUT_PROBABILITY) { mut_point = rand() % GENE; cout << "Mutation at gene " << mut_point << endl; if (children[c][mut_point] == 1) children[c][mut_point] = 0; else children[c][mut_point] = 1; } else cout << "\nMutation did not happen.\n"; } for (int c = 0; c < 2; c++) { cout << "\nChildren" << c + 1 << "after mutation: "; for (int g = 0; g < GENE; g++) { cout << children[c][g] << " "; } cout << endl; } } void survivalSelection() { for (int c = 0; c < 2; c++) {//copy children to newChromosome for (int g = 0; g < GENE; g++) { newChromosome[newChromoCounter][g] = children[c][g]; } newChromoCounter++; } for (int c = 0; c < newChromoCounter; c++) { cout << "\nNew Chromosome " << c << ": "; for (int g = 0; g < GENE; g++) { cout << newChromosome[c][g] << " "; } } } void copyChromosome() { for (int c = 0; c < POP_SIZE; c++) { for (int g = 0; g < GENE; g++) { chromosome[c][g] = newChromosome[c][g]; } } } void recordBestFitness() { for (int c = 0; c < POP_SIZE; c++) { if (bestFitness > fitness[c]) { bestFitness = fitness[c]; for (int g = 0; g < GENE; g++) { bestChromosome[g] = chromosome[c][g]; }//close for gene }//close for if }//close for c //output for the best chromosome to monitor cout << "\n Best Fitness = " << bestFitness; cout << "\n Best Chromosome = "; for (int g = 0; g < GENE; g++) { cout << bestChromosome[g]; } cout << endl; //output for the file bestFitnessFile << bestFitness << endl; for (int g = 0; g < GENE; g++) { bestChromosomeFile << bestChromosome[g]; } bestChromosomeFile << endl; } void calcAvgFitness() { double sum = 0; for (int c = 0; c < POP_SIZE; c++) { sum += fitness[c]; } avgFitness = sum / POP_SIZE; //output to monitor cout << "\n Average Fitness = " << avgFitness << endl; //output to file avgFitnessFile << avgFitness << endl; } int main() { bestFitnessFile.open("bestFitness.txt"); avgFitnessFile.open("avgFitness.txt"); bestChromosomeFile.open("bestChromosome.txt"); cout << "\nGA START! \n"; cout << "First generation \n\n"; cout << "\nINITIALIZATION... \n"; //LAB 3 initializePopulation(); //getchar(); //LAB 3 for (int g = 0; g < MAX_GENERATION; g++) {//start of generation cout << "\n GENERATION" << g + 1 << endl; cout << "\nPRINT POPULATION \n"; printChromosome(); //LAB 4 cout << "\nEVALUATE CHROMOSOME \n"; evaluateChromosome(); recordBestFitness(); calcAvgFitness(); //getchar(); newChromoCounter = 0; for (int i = 0; i < POP_SIZE / 2; i++) { cout << "\nPARENT SELECTION \n"; parentSelection(); cout << "\nCROSSOVER \n"; crossover(); cout << "\nMUTATION \n"; mutation(); cout << "\nSURVIVAL SELECTION \n"; survivalSelection(); } cout << "\nNEW CHROMOSOMES COPIED TO CHROMOSOME\n"; copyChromosome(); //getchar(); } bestFitnessFile.close(); avgFitnessFile.close(); bestChromosomeFile.close(); }
true
30f59963a89c0ee0ef9f9a7744086be18bf9ef47
C++
slaakko/soulng
/sngxml/example/library/Config/Config.cpp
UTF-8
5,032
2.5625
3
[]
no_license
#include <Config/Config.hpp> #include <Config/Configuration.hpp> #include <Config/Ids.hpp> #include <sngxml/dom/Document.hpp> #include <sngxml/dom/Parser.hpp> #include <soulng/util/Path.hpp> #include <boost/filesystem.hpp> #include <fstream> namespace config { using namespace soulng::util; const int defaultServerPortNumber = 55000; Configuration* LoadConfiguration(const std::string& configFilePath) { std::unique_ptr<Configuration> configuration(new Configuration()); std::unique_ptr<sngxml::dom::Document> configurationDoc = sngxml::dom::ReadDocument(configFilePath); configuration->FromXml(configurationDoc->DocumentElement()); return configuration.release(); } void SaveConfiguration(Configuration* configuration, const std::string& configFilePath) { sngxml::dom::Document configurationDoc; configurationDoc.AppendChild(std::unique_ptr<sngxml::dom::Node>(configuration->ToXml("configuration"))); std::ofstream configFile(configFilePath); CodeFormatter formatter(configFile); formatter.SetIndentSize(1); configurationDoc.Write(formatter); } Configuration* MakeConfiguration() { Configuration* configuration = new Configuration(); configuration->serverPortNumber = defaultServerPortNumber; return configuration; } Ids* LoadIds(const std::string& idsFilePath) { std::unique_ptr<Ids> ids(new Ids()); std::unique_ptr<sngxml::dom::Document> idsDoc = sngxml::dom::ReadDocument(idsFilePath); ids->FromXml(idsDoc->DocumentElement()); return ids.release(); } void SaveIds(Ids* ids, const std::string& idsFilePath) { sngxml::dom::Document idsDoc; idsDoc.AppendChild(std::unique_ptr<sngxml::dom::Node>(ids->ToXml("ids"))); std::ofstream idsFile(idsFilePath); CodeFormatter formatter(idsFile); formatter.SetIndentSize(1); idsDoc.Write(formatter); } Ids* MakeIds() { Ids* ids = new Ids(); return ids; } std::string SoulngRoot() { std::string soulngRoot; char* soulngRootEnv = std::getenv("SOULNG_ROOT"); if (soulngRootEnv && *soulngRootEnv) { soulngRoot = GetFullPath(soulngRootEnv); } else { throw std::runtime_error("SOULNG_ROOT environment variable not found, please set it to contain /path/to/soulng directory"); } return soulngRoot; } std::string LibraryRoot() { std::string soulngRoot = SoulngRoot(); return Path::Combine(Path::Combine(Path::Combine(soulngRoot, "sngxml"), "example"), "library"); } std::string ConfigFilePath() { return Path::Combine(Path::Combine(LibraryRoot(), "Data"), "Library.config.xml"); } std::string IdsFilePath() { return Path::Combine(Path::Combine(LibraryRoot(), "Data"), "ids.xml"); } class Config { public: static void Init(); static void Done(); static Config& Instance() { return *instance; } Configuration* GetConfiguration() const { return configuration.get(); } Ids* GetIds() const { return ids.get(); } private: Config(); static std::unique_ptr<Config> instance; std::unique_ptr<Configuration> configuration; std::unique_ptr<Ids> ids; }; std::unique_ptr<Config> Config::instance; void Config::Init() { instance.reset(new Config()); } void Config::Done() { instance.reset(); } Config::Config() { std::string configFilePath = ConfigFilePath(); if (!boost::filesystem::exists(configFilePath)) { configuration.reset(MakeConfiguration()); SaveConfiguration(configuration.get(), configFilePath); } configuration.reset(LoadConfiguration(configFilePath)); std::string idsFilePath = IdsFilePath(); if (!boost::filesystem::exists(idsFilePath)) { ids.reset(MakeIds()); SaveIds(ids.get(), idsFilePath); } ids.reset(LoadIds(idsFilePath)); } int GetServerPortNumber() { return Config::Instance().GetConfiguration()->serverPortNumber; } void ClearLibraries() { Configuration* configuration = Config::Instance().GetConfiguration(); configuration->libraries.clear(); } std::vector<std::string> GetLibraries() { Configuration* configuration = Config::Instance().GetConfiguration(); return configuration->libraries; } void AddLibrary(const std::string& library) { Configuration* configuration = Config::Instance().GetConfiguration(); configuration->libraries.push_back(library); } void SaveIds() { SaveIds(Config::Instance().GetIds(), IdsFilePath()); } boost::uuids::uuid GetId(int index) { return Config::Instance().GetIds()->Get(index); } std::string DataDirectoryPath() { return Path::Combine(LibraryRoot(), "Data"); } std::string GetLibraryFilePath(const std::string& libraryName) { return Path::Combine(DataDirectoryPath(), libraryName + ".bundle.xml"); } std::string BinDirectoryPath() { return Path::Combine(SoulngRoot(), "bin"); } void SaveConfiguration() { SaveConfiguration(Config::Instance().GetConfiguration(), ConfigFilePath()); } void InitConfig() { Config::Init(); } void DoneConfig() { Config::Done(); } } // config
true
96797d728cd17f03d255c7ce24ca609c14a2d100
C++
tectronics/nwmc
/DesignatedDrinkers_NWMC/source/EntitySystem/ConcreteEntity.cpp
UTF-8
11,276
2.59375
3
[]
no_license
/************************************************************* | File: ConcreteEntity.cpp | Author: Ryan T. Miller (metalhead71@Hotmail.com) with references from Doug Monroe (dmonroe@fullsail.com) | Course: SGP 1307 | Purpose: ConcreteEntity class is used for a velocity-based game object. It is the parent class for all other objects. *************************************************************/ #include "ConcreteEntity.h" #include "../SGDWrappers/CSGD_TextureManager.h" #include "../AnimationSystem/AnimationManager.h" #include "../StateMachine/GameplayState.h" #include "../GameCore/Game.h" #include <cassert> #define TELEPORTTIMERMAX 1.0f ////////////////////////////////////////////////////////////// // Constructor // - set ALL data members to 'clean' values ConcreteEntity::ConcreteEntity( void ) { // Set the entity's type baseType = ENT_CONCRETE; specificType = ENT_BASE; baseImageID = -1; positionX = -1; positionY = -1; moveVelocityX = -1; moveVelocityY = -1; rotation = -1; baseWidth = 5; baseHeight = 5; moveSpeedX = -1; moveSpeedY = -1; refCount = 1; // calling 'new' gives the 'prime' reference facingLeft = false; isGrounded = false; //Tracking info lastKnownX = -1; lastKnownY = -1; teleportedRecently = false; teleportedRecentlyTimer = -1.0f; teleRandTimer = 1.0f; } ////////////////////////////////////////////////////////////// // Destructor ConcreteEntity::~ConcreteEntity( void ) { } ////////////////////////////////////////////////////////////// // Update // - move the entity by velocity each frame // (velocity is pixels per second)@concreteEntityupdate /*virtual*/ void ConcreteEntity::Update( float fElapsedTime ) { GameplayState* myGameplay = GameplayState::GetInstance(); //Continue only if in gameplay if (myGameplay != nullptr) { //////////////////// // Timer Update //////////////////// if (teleportedRecentlyTimer > 0.0f) { teleportedRecentlyTimer -= fElapsedTime; if (teleportedRecentlyTimer <= 0.0f) { teleportedRecently = false; } } //teleRand if (teleRandTimer > 0.0f) { teleRandTimer -= fElapsedTime; if (teleRandTimer <= 0.0f) { ResetRandTimer(); } } bool shouldMoveX = false; bool shouldMoveY = false; ///////////////////////////////// //Collision checking //////////////////////////////// RECT rOverlap = { }; //Making a RECT of where you WOULD be going RECT ourRECT = this->GetRect(); ourRECT.top += (LONG)(moveVelocityY * fElapsedTime); ourRECT.bottom += (LONG)(moveVelocityY * fElapsedTime); ourRECT.left += (LONG)(moveVelocityX * fElapsedTime); ourRECT.right += (LONG)(moveVelocityX * fElapsedTime); ///////////////////////////////// //Collision checking for walls ///////////////////////////////// if (myGameplay->GetWallBucketSize() == 0) { shouldMoveX = true; } RECT wallRECT; for (unsigned int z = 0; z < myGameplay->GetWallBucketSize(); z++) { wallRECT = myGameplay->GetWall(z); if (abs(GetPosX() - wallRECT.left) < 200) { //If there is an overlap between two of them, send a message if( IntersectRect( &rOverlap, &ourRECT, &wallRECT ) == TRUE ) { //Calling collision with wall function. If it returns false, that means you should NOT update position if (HandleCollideWithWall(wallRECT, rOverlap) == false) { //return; } } } //If you did not collide with anything, or you did and dont care, continue updating X shouldMoveX = true; } ///////////////////////////////// //Collision checking for floors ///////////////////////////////// if (myGameplay->GetFloorBucketSize() == 0) { shouldMoveY = true; } shouldMoveY = true; if(GetType() != ENT_PROJECTILE) { if(CGame::GetInstance()->GetChosenLevel() != 5) { //Colliding with the middle floor if (GetPosY() > 288 && GetRect().top < 288) { SetPosY(288); SetVelY(0); isGrounded = true; shouldMoveY = false; } } //Colliding with the bottom floor if (GetPosY() > 576 && GetRect().top < 576) { SetPosY(576); SetVelY(0); isGrounded = true; shouldMoveY = false; } } //RECT floorRECT; //for (unsigned int p = 0; p < myGameplay->GetFloorBucketSize(); p++) //{ // floorRECT = myGameplay->GetFloor(p); // //If there is an overlap between two of them, call a function for colliding with floor // if( IntersectRect( &rOverlap, &ourRECT, &floorRECT ) == TRUE ) // { // //Calling collision with floor function. If it returns false, that means you should NOT update position // if (HandleCollideWithFloor(floorRECT, rOverlap) == false) // { // //return; // } // } // //If you did not collide with anything, or you did and dont care, continue updating Y // shouldMoveY = true; //} //If you did not detect a collision with a wall, go ahead and update the X if (shouldMoveX == true) { positionX += moveVelocityX * fElapsedTime; } //If you did not detect a collision with a floor, go ahead and update the Y if (shouldMoveY == true) { positionY += moveVelocityY * fElapsedTime; } }//Checking for gameplay state } ////////////////////////////////////////////////////////////// // Render // - render the entity's image at its position /*virtual*/ void ConcreteEntity::Render( void ) { // Validate the image assert( baseImageID != -1 && "ConcreteEntity::Render - image was not set" ); // Use the Texture Manager singleton (TEMPORARY) CSGD_TextureManager::GetInstance()->Draw( baseImageID, (int)positionX - CGame::GetInstance()->GetCameraPosX(), (int)positionY, 1.0f, 1.0f, nullptr, (float)(baseWidth/2), (float)(baseHeight/2), rotation ); } ////////////////////////////////////////////////////////////// // GetRect // - return the entity's bounding rectangle /*virtual*/ RECT ConcreteEntity::GetRect( void ) const { //As long as it is not a projectile, return the animation rect if (baseType != ENT_PROJECTILE) { // if you touch this, I will kill you... RECT rSelf = AnimationManager::GetInstance()->GetCurrCollisionRect(AnimationInfo, (int)positionX, (int)positionY, GetFacingLeft()); /* if(GetFacingLeft() == true) { LONG offsetX = (LONG)(rSelf.right - GetPosX()); LONG width = rSelf.right - rSelf.left; rSelf.left = GetPosX() - offsetX; rSelf.right = rSelf.left+width; } */ return rSelf; } //(TEMPORARY) RECT rSelf = { (LONG)positionX, (LONG)positionY, (LONG)(positionX + baseHeight), (LONG)(positionY + baseWidth) }; return rSelf; } ////////////////////////////////////////////////////////////// // HandleCollision // - respond to collision with other entity /*virtual*/ void ConcreteEntity::HandleCollision( BaseEntity* otherEntity ) { /* concreteEntity does not care about collision */ } ////////////////////////////////////////////////////////////// // CheckCollision // - returns true if the entities are overlapping // - global function does NOT have invoking object // & does NOT have access to ConcreteEntity privates bool ::CheckCollision( const BaseEntity* baseEntity1, const BaseEntity* baseEntity2 ) { // Local variables allow for easier debugging RECT rOverlap = { }; RECT rEntity1 = baseEntity1->GetRect(); RECT rEntity2 = baseEntity2->GetRect(); //If there is no overlap between the two, return false if( IntersectRect( &rOverlap, &rEntity1, &rEntity2 ) == FALSE ) { return false; } //Else carry on to return true return true; } ////////////////////////////////////////////////////////////// // AddRef // - increase the reference count /*virtual*/ void ConcreteEntity::AddRef( void ) { assert( refCount != UINT_MAX && "ConcreteEntity::AddRef - reference count has exceeded max" ); ++refCount; } ////////////////////////////////////////////////////////////// // Release // - decrease the reference count // - self-destruct when the count reaches 0 /*virtual*/ void ConcreteEntity::Release( void ) { --refCount; if( refCount == 0 ) delete this; } ////////////////////////////////////////////////////////////// // HandleCollideWithWall // - Stops the velocity // - should be overridden if you need it to do anything besides stop moving // - return true if you should continue, or false if you dont want update to keep going bool ConcreteEntity::HandleCollideWithWall (const RECT myWall, const RECT myOverlap) { //////////////////////////////// // Pushing you off the wall /////////////////////////////// LONG wallWidth = (myWall.right - myWall.left); LONG wallCenterX = myWall.right - (LONG)( wallWidth* 0.5f); if (GetPosX() > wallCenterX)//If you are on the RIGHT of the wall { //Push me back by the amount I am over SetPosX(GetPosX() +( myOverlap.right - myOverlap.left)); } else if (GetPosX() < wallCenterX)//If you are on the LEFT of the wall { //Push me back by the amount I am over SetPosX(GetPosX() - ( myOverlap.right - myOverlap.left)); } SetVelX(0.0f); return false; } ////////////////////////////////////////////////////////////// // HandleCollideWithFloor // - Stops the velocity // - should be overridden if you need it to do anything besides stop moving // - return true if you should continue, or false if you dont want update to keep going bool ConcreteEntity::HandleCollideWithFloor (const RECT myFloor, const RECT myOverlap) { //////////////////////////////// // Pushing you off the floor /////////////////////////////// LONG floorHeight = (myFloor.bottom - myFloor.top); LONG floorCenterY = (LONG)(myFloor.bottom - ( floorHeight* 0.5f)); if (GetCenterPointY() > floorCenterY)//If you are BELOW the floor { //Push me back by the amount I am over SetPosY(GetPosY() + ( myOverlap.bottom - myOverlap.top)); } else if (GetCenterPointY() < floorCenterY)//If you are ABOVE the floor { //Push me back by the amount I am over SetPosY(GetPosY() - ( myOverlap.bottom - myOverlap.top)); } if (this->GetCenterPointY() < floorCenterY) { //Stopping vertical movement SetVelY(0.0f); isGrounded = true; } return false; } ///////////////////////////////// //Setting the last known location void ConcreteEntity::SetLastKnown( int newX, int newY ) { lastKnownX = newX; lastKnownY = newY; } ///////////////////////////////// //Returning width based on current animation rect int ConcreteEntity::GetRealWidth ( void ) const { return (GetRect().right - GetRect().left); } ///////////////////////////////// //IJustTeleported // - Called whenever you teleport, to update your position void ConcreteEntity::IJustTeleported (void) { teleportedRecentlyTimer = TELEPORTTIMERMAX; SetLastKnown((int)GetPosX(), (int)GetPosY()); teleportedRecently = true; } ///////////////////////////////// //Shutdown // - Is obsolete and should be overridden everywhere void ConcreteEntity::Shutdown(void) { } ///////////////////////////////// //GetCenterPointX // - Returns the center of the current GETRECT x int ConcreteEntity::GetCenterPointX(void) { int tempWidth = GetRect().right - GetRect().left; return GetRect().right - (tempWidth/2); } ///////////////////////////////// //GetCenterPointY // - Returns the center of the current GETRECT y int ConcreteEntity::GetCenterPointY(void) { int tempHeight = GetRect().bottom - GetRect().top; return GetRect().bottom - (tempHeight/2); }
true
f20f0e1a42ba3595a569b4326f743945790b6260
C++
runngezhang/sword_offer
/nowcoder/cpp/牛客. 出现次数的TopK问题.cpp
UTF-8
2,313
3.546875
4
[]
no_license
class Solution { public: // 交换vec内两个元素的值 template <class T> void swap(vector<T>& vec, int l, int h) { T tmp = vec[l]; vec[l] = vec[h]; vec[h] = tmp; } // 大顶堆下沉函数,出现次数越多,字典序越小的,放在前面 void heapify(vector<string>& strs, vector<int>& cnts, int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && (cnts[l] > cnts[largest] || (cnts[l] == cnts[largest] && strs[l] < strs[largest]))) { largest = l; } if (r < n && (cnts[r] > cnts[largest] || (cnts[r] == cnts[largest] && strs[r] < strs[largest]))) { largest = r; } if (largest != i) { swap(strs, i, largest); swap(cnts, i, largest); heapify(strs, cnts, n, largest); } } /** * return topK string * @param strings string字符串vector strings * @param k int整型 the k * @return string字符串vector<vector<>> */ vector<vector<string> > topKstrings(vector<string>& strings, int k) { // write code here // 特殊情况 if (strings.empty() || k <= 0) { return vector<vector<string>>{}; } // 确定每个字符串出现的次数 std::map<std::string, int> map; for (auto & s : strings) { map[s] += 1; } // 转换为两个数组,分别存储cnts, strs int n = map.size(); std::vector<int> cnts; std::vector<std::string> strs; for (auto it = map.begin(); it != map.end(); it++) { strs.push_back(it->first); cnts.push_back(it->second); } // 建立大顶堆 for (int i = n - 1; i >= 0; i--) { heapify(strs, cnts, n, i); } // 进行堆排序,获取前k个元素,搬移到末尾,并保存到ret vector<vector<string>> ret; for (int i = n - 1; i > n - 1 - k; i--) { vector<string> tmp = {strs[0], std::to_string(cnts[0])}; ret.push_back(tmp); swap(strs, 0, i); swap(cnts, 0, i); heapify(strs, cnts, i, 0); } // 返回结果 return ret; } };
true
563e2dd3dc4d9af305b996620bb3647c3fbacb6f
C++
chreden/trview
/trview.app/Tools/Measure.h
UTF-8
2,030
2.796875
3
[ "MIT", "BSD-3-Clause", "Zlib" ]
permissive
#pragma once #include <optional> #include <trview.app/Geometry/IMesh.h> #include "IMeasure.h" namespace trview { class Measure final : public IMeasure { public: /// Create a new measure tool. /// @param device The device to use to create graphics resources. explicit Measure(const std::shared_ptr<graphics::IDevice>& device, const IMesh::Source& mesh_source); virtual ~Measure() = default; /// Start measuring or reset the current measurement. virtual void reset() override; /// Add the position to the measurement. /// @param position The position to add to the measurement. /// @returns True if the measurement is complete. virtual bool add(const DirectX::SimpleMath::Vector3& position) override; /// Set the position as the current temporary end of the measurement. /// @param position The position to use as the new end. virtual void set(const DirectX::SimpleMath::Vector3& position) override; /// Render the measurement. /// @param camera The camera being used to render the scene. /// @param texture_storage Texture storage for the level. virtual void render(const ICamera& camera, const ILevelTextureStorage& texture_storage) override; /// Get the current text version of the distance measured. /// @returns The text version of the distance. virtual std::string distance() const override; /// Get whether a distance is actively being measured. /// @returns True if start and end is set. virtual bool measuring() const override; /// Set whether the measure tool should be rendered. virtual void set_visible(bool value) override; private: std::shared_ptr<graphics::IDevice> _device; std::optional<DirectX::SimpleMath::Vector3> _start; std::optional<DirectX::SimpleMath::Vector3> _end; std::shared_ptr<IMesh> _mesh; bool _visible{ true }; }; }
true
8ab48969fbc96d5ded51b99182cf06880633e542
C++
Omlovee/codingback
/LeetCode/1.hpp
UTF-8
389
3.078125
3
[]
no_license
#pragma once class 1 { public: vector<int> twoSum(vector<int> nums, int target) { vector<int> res; for(int i = 0;i < nums.size();++i) { for(int j = i + 1;j < nums.size();++j) { res.push_back(i); res.push_back(j); break; } } return res; } private: };
true
917473895dc6104a3d12023a175f0467d5796fb8
C++
offamitkumar/UVA--Online-Judge
/Solution/Problem_000927/Solution.cpp
UTF-8
1,678
2.796875
3
[]
no_license
/* * As the given constraints are very tight * so even a single mistake in the input and output will certainly * lead you to the wrong answer. */ #include <cstdio> #include <iostream> #include <string> #include <algorithm> #include <utility> #include <queue> #include <stack> #include <string> #include <cstring> #include <cmath> #include <map> #include <vector> #include <array> #include <set> #include <climits> #include <cassert> #include <bitset> #include <numeric> using namespace std; #define mod 1000000007 array<long long,1000000>sq; void utility(void){ long long sum = 0ll; // sequence 1 , 2 , 2 , 3 , 3 , 3 , 4 , 4 , ....... sq[0] = sum; for(int i=0;;++i){ sum+=i; if(sum>=1000000) break; sq[sum]=i+1ll; } } // simple function implementation unsigned long long sol(long long t , long long n,vector<long long>&coff , long long i){ if(i==t){ return 0ll; } return coff[i] * pow(n , i) + sol(t,n,coff,i+1); } int main(void){ ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); #ifdef HELL_JUDGE freopen("input","r",stdin); freopen("output","w",stdout); freopen("error","w",stderr); #endif utility(); int c; cin>>c; while(c--){ long long n;cin>>n;n++; vector<long long>coff(n); for(auto &itr:coff){ cin>>itr; } long long d,k; cin>>d>>k; long long index = (k-1ll)/d; //finding the correct position as generated string is not perfect while(index>0ll and sq[index]==0ll) index--; cout<<sol(n,sq[index],coff,0ll)<<endl; } return 0; }
true
ab91ea6e21d19f448ccef94c5b51a02e00295c62
C++
vintageplayer/Arduino-Sample-Codes
/nodeMCU/connection_setup.ino
UTF-8
8,608
2.53125
3
[ "MIT" ]
permissive
/** * BasicHTTPClient.ino * * Created on: 24.05.2015 * */ #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> #define USE_SERIAL Serial ESP8266WiFiMulti WiFiMulti; int sensorInterrupt = 5; // 5 = digital pin d1 int sensorInterrupt2 = 4; // 5 = digital pin d2 float calibrationFactor = 4.5; volatile byte pulseCount; volatile byte pulseCount2; float flowRate; float flowRate2; unsigned int flowMilliLitres; unsigned long totalMilliLitres; unsigned long oldTime; unsigned int flowMilliLitres2; unsigned long totalMilliLitres2; unsigned long oldTime2; int flag1,flag2; void setup() { USE_SERIAL.begin(115200); USE_SERIAL.println(); USE_SERIAL.println(); USE_SERIAL.println(); for(uint8_t t = 4; t > 0; t--) { USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); USE_SERIAL.flush(); delay(1000); } WiFiMulti.addAP("MotoG3 4232", "987654321"); Serial.begin(115200); pinMode(sensorInterrupt, INPUT_PULLUP); pulseCount = 0; flowRate = 0.0; flowMilliLitres = 0; totalMilliLitres = 0; oldTime = 0; flag1 = 0; flag2 = 0; // The Hall-effect sensor is connected to pin 2 which uses interrupt 0. // Configured to trigger on a FALLING state change (transition from HIGH // state to LOW state) attachInterrupt(sensorInterrupt, pulseCounter, FALLING); pinMode(sensorInterrupt2, INPUT_PULLUP); pulseCount2 = 0; flowRate2 = 0.0; flowMilliLitres2 = 0; totalMilliLitres2 = 0; oldTime2 = 0; // The Hall-effect sensor is connected to pin 2 which uses interrupt 0. // Configured to trigger on a FALLING state change (transition from HIGH // state to LOW state) attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING); } void sendReport(String device,float amount) { if((WiFiMulti.run() == WL_CONNECTED)) { HTTPClient http; USE_SERIAL.print("[HTTP] begin...\n"); String url = "http://192.168.43.28:3001/data/"+ device +"/"+ String(amount) + "/"; http.begin(url); USE_SERIAL.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if(httpCode > 0) { // HTTP header has been send and Server response header has been handled USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if(httpCode == HTTP_CODE_OK) { String payload = http.getString(); USE_SERIAL.println(payload); } } else { USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); } http.end(); } } void loop() { if((millis() - oldTime) > 1000) // Only process counters once per second { // Disable the interrupt while calculating flow rate and sending the value to // the host detachInterrupt(sensorInterrupt); // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor; // Note the time this processing pass was executed. Note that because we've // disabled interrupts the millis() function won't actually be incrementing right // at this point, but it will still return the value it was set to just before // interrupts went away. oldTime = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres = (flowRate / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres += flowMilliLitres; unsigned int frac; // Print the flow rate for this second in litres / minute Serial.print("Flow rate 1: "); Serial.print(int(flowRate)); // Print the integer part of the variable Serial.print("."); // Print the decimal point // Determine the fractional part. The 10 multiplier gives us 1 decimal place. frac = (flowRate - int(flowRate)) * 10; Serial.print(frac, DEC) ; // Print the fractional part of the variable Serial.print("L/min"); // Print the number of litres flowed in this second Serial.print(" Current Liquid 1 Flowing: "); // Output separator Serial.print(flowMilliLitres); Serial.print("mL/Sec"); // Print the cumulative total of litres flowed since starting Serial.print(" Output 1 Liquid Quantity: "); // Output separator Serial.print(totalMilliLitres); if(totalMilliLitres > 0){ flag1 = 1; } if(flowRate==0 && flag1 == 1){ flag1 = 2; } Serial.println("mL"); // Reset the pulse counter so we can start incrementing again pulseCount = 0; // Enable the interrupt again now that we've finished sending output attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } if((millis() - oldTime2) > 1000) // Only process counters once per second { // Disable the interrupt while calculating flow rate and sending the value to // the host detachInterrupt(sensorInterrupt2); // Because this loop may not complete in exactly 1 second intervals we calculate // the number of milliseconds that have passed since the last execution and use // that to scale the output. We also apply the calibrationFactor to scale the output // based on the number of pulses per second per units of measure (litres/minute in // this case) coming from the sensor. flowRate2 = ((1000.0 / (millis() - oldTime2)) * pulseCount2) / calibrationFactor; // Note the time this processing pass was executed. Note that because we've // disabled interrupts the millis() function won't actually be incrementing right // at this point, but it will still return the value it was set to just before // interrupts went away. oldTime2 = millis(); // Divide the flow rate in litres/minute by 60 to determine how many litres have // passed through the sensor in this 1 second interval, then multiply by 1000 to // convert to millilitres. flowMilliLitres2 = (flowRate2 / 60) * 1000; // Add the millilitres passed in this second to the cumulative total totalMilliLitres2 += flowMilliLitres2; unsigned int frac2; // Print the flow rate for this second in litres / minute Serial.print("Flow rate 2: "); Serial.print(int(flowRate2)); // Print the integer part of the variable Serial.print("."); // Print the decimal point // Determine the fractional part. The 10 multiplier gives us 1 decimal place. frac2 = (flowRate2 - int(flowRate2)) * 10; Serial.print(frac2, DEC) ; // Print the fractional part of the variable Serial.print("L/min"); // Print the number of litres flowed in this second Serial.print(" Current Liquid 2 Flowing: "); // Output separator Serial.print(flowMilliLitres2); Serial.print("mL/Sec"); // Print the cumulative total of litres flowed since starting Serial.print(" Output Liquid 2 Quantity: "); // Output separator Serial.print(totalMilliLitres2); Serial.println("mL"); if(totalMilliLitres2 > 0){ flag2 = 1; } if(flowRate2==0 && flag2 == 1){ flag2 = 2; } // Reset the pulse counter so we can start incrementing again pulseCount2 = 0; // Enable the interrupt again now that we've finished sending output attachInterrupt(sensorInterrupt2, pulseCounter2, FALLING); } if(flag1==2){ String name = "dev1"; sendReport(name,totalMilliLitres); flag1 = 0; totalMilliLitres = 0; } if(flag2==2){ String name = "dev2"; sendReport(name,totalMilliLitres2); flag2 = 0; totalMilliLitres2 = 0; } } /* Insterrupt Service Routine */ void pulseCounter() { // Increment the pulse counter pulseCount+=1; } voud pulseCounter2() { pulseCount2+=1; }
true
ec2b8dfba335cb98a72f31535f802265ea8643a0
C++
jmurrayufo/Gaia-Forge
/Src/system/noise/Noise.cpp
UTF-8
3,135
2.671875
3
[]
no_license
#include "Noise.h" Noise::Noise() { Seed=0; Period=1; Amplitude=1; Octaves=1; Persistance=1; InterpType=NOISE_INTERP_CUBIC; } void Noise::test(void) { int start=SDL_GetTicks(); int i; Period=100; Octaves=50; Amplitude=10; Persistance=2; InterpType=NOISE_INTERP_CUBIC; i=0; while(SDL_GetTicks() - start < 1000) { std::cout << i << "," << Perlin1d(i) << std::endl; i++; } return; } double Noise::Perlin1d(int x) { double total=0; double p=Period; double a=Amplitude; for(int i=0;i<Octaves;i++) { if(p==0 || a==0) break; switch(InterpType) { case NOISE_INTERP_LINEAR: double y0,y1; y0=FloatNoise((int)(x / p)); y1=FloatNoise((int)(x / p) + 1); total += InterpLin(y0,y1,fmod(x/p,1)) * a; break; case NOISE_INTERP_CUBIC: double n0,n1,n2,n3; n0=FloatNoise((int)x / p - 1); n1=FloatNoise((int)x / p + 0); n2=FloatNoise((int)x / p + 1); n3=FloatNoise((int)x / p + 2); total += InterpCubic(n0,n1,n2,n3,fmod(x/p,1)) * a; break; } p = p / 2; a = a / Persistance; } return total; } double Noise::Perlin2d(int x,int y) { double total=0; double p=Period; double a=Amplitude; for(int i=0;i<Octaves;i++) { if(p==0 || a==0) break; switch(InterpType) { case NOISE_INTERP_LINEAR: double vx[2]; double vy[2]; double xy[2]; vx[0] = FloatNoise( (int)(x / p), (int)(y / p) ); vx[1] = FloatNoise( (int)(x / p) + 1, (int)(y / p) ); vy[0] = FloatNoise( (int)(x / p), (int)(y / p) + 1 ); vy[1] = FloatNoise( (int)(x / p) + 1, (int)(y / p) + 1 ); xy[0] = InterpLin(vx[0],vx[1],fmod(x/p,1)); xy[1] = InterpLin(vy[0],vy[1],fmod(x/p,1)); total += InterpLin(xy[0],xy[1],fmod(y/p,1)) * a; break; case NOISE_INTERP_CUBIC: break; } p = p / 2; a = a / Persistance; } return total; } double Noise::FloatNoise(float x,float y) { int n = x + y * 57; n = (n << 13) ^ n; int t = (n * (n * n * 15731 + 789221) + 1376312589 * Seed * Seed) & 0x7fffffff; return 1.0 - double(t) * 0.931322574615478515625e-9;/// 1073741824.0); } double Noise::FloatNoiseStdlib(int x,int y) { srand(Seed*Seed*98809 + 15731*x*x + 13339*y*y); int n=rand(); return (double)n/RAND_MAX; } double Noise::InterpLin(float a,float b,float x) { return a*(1-x)+b*x; } double Noise::InterpCos(float a,float b,float x) { x = x * 3.14159265359; x = (1 - cos(x)) * 0.5; return a*(1-x)+b*x; } double Noise::InterpCubic(float v0,float v1,float v2,float v3,float x) { double P = (v3 - v2) - (v0 - v1); return P * x * x * x + ((v0 - v1) - P) * x * x + (v2 - v0) * x + v1; }
true
32faac2a823cc058a11aed7b4c11460fc58b34b0
C++
othmanabdulsalam/Abdulsalam_Othman_CG_Assignment_1
/chLinkedList/chLinkedList.cpp
UTF-8
4,509
2.859375
3
[]
no_license
#include "stdafx.h" #include "chLinkedList.h" void initList(chLinkedList* pList, unsigned int uiType) { if(pList) { pList->m_pHead = 0; pList->m_pTail = 0; pList->m_uiType = uiType; } } void destroyList(chLinkedList* pList, chListDeletor* pDeletor) { if(pList) { if(pDeletor) for(chLinkedListElement *pE=pList->m_pHead;pE;pE=pE->m_pNext) pDeletor(pE); while(pList->m_pHead) delete popTail(pList); } } chLinkedListElement* initElement(chLinkedListElement* pElement, void* pData, unsigned uiType) { if(pElement) { pElement->m_pNext = 0; pElement->m_pLast = 0; pElement->m_pData = pData; pElement->m_uiType = uiType; } return pElement; } chLinkedListElement* destroyElement(chLinkedListElement* pElement, chListDeletor* pDeletor) { if(pElement && !(pElement->m_pNext||pElement->m_pLast)) { if (pDeletor) pDeletor(pElement); delete pElement; return 0; } return pElement; } void pushHead(chLinkedList* pList, chLinkedListElement* pElement) { if (pList && pElement && !(pElement->m_pNext || pElement->m_pLast)) { pElement->m_pNext = pList->m_pHead; if (!pList->m_pTail) pList->m_pTail = pElement; if (pList->m_pHead) pList->m_pHead->m_pLast = pElement; pList->m_pHead = pElement; } } void pushTail(chLinkedList* pList, chLinkedListElement* pElement) { if (pList && pElement && !(pElement->m_pNext || pElement->m_pLast)) { pElement->m_pLast = pList->m_pTail; if (!pList->m_pHead) pList->m_pHead = pElement; if (pList->m_pTail) pList->m_pTail->m_pNext = pElement; pList->m_pTail = pElement; } } chLinkedListElement* head(chLinkedList* pList) { return pList ? pList->m_pHead : 0; } chLinkedListElement* tail(chLinkedList* pList) { return pList ? pList->m_pTail : 0; } unsigned count(chLinkedList* pList) { unsigned int uiCount = 0; if(pList) for (chLinkedListElement *pE = pList->m_pHead; pE; pE = pE->m_pNext, uiCount++); return uiCount; } chLinkedListElement* item(chLinkedList* pList, unsigned uiIndex) { if (pList) { chLinkedListElement *pE = pList->m_pHead; if(pE) for (; pE&&uiIndex; pE = pE->m_pNext); return pE; } return 0; } void visit(chLinkedList* pList, chListActor* pActor) { if(pList && pActor) for (chLinkedListElement *pE = pList->m_pHead; pE; pE = pE->m_pNext) pActor(pE); } chLinkedListElement* popHead(chLinkedList* pList) { chLinkedListElement *pE = 0; if(pList && pList->m_pHead) { pE = pList->m_pHead; if (pList->m_pHead == pList->m_pTail) pList->m_pHead = pList->m_pTail = 0; else { pList->m_pHead = pE->m_pNext; pList->m_pHead->m_pLast = 0; pE->m_pNext = 0; } } return pE; } chLinkedListElement* popTail(chLinkedList* pList) { chLinkedListElement *pE = 0; if (pList && pList->m_pTail) { pE = pList->m_pTail; if (pList->m_pHead == pList->m_pTail) pList->m_pHead = pList->m_pTail = 0; else { pList->m_pTail = pE->m_pLast; pList->m_pTail->m_pNext = 0; pE->m_pLast = 0; } } return pE; } bool insertBefore(chLinkedList* pList, chLinkedListElement *pCurrentElement, chLinkedListElement *pNewElement) { if(pList && pCurrentElement && pNewElement) { if (pCurrentElement == pList->m_pHead) pushHead(pList, pNewElement); else { pNewElement->m_pLast = pCurrentElement->m_pLast; pNewElement->m_pNext = pCurrentElement; pNewElement->m_pLast->m_pNext = pNewElement; pCurrentElement->m_pLast = pNewElement; } return true; } return false; } bool insertAfter(chLinkedList* pList, chLinkedListElement *pCurrentElement, chLinkedListElement *pNewElement) { if (pList && pCurrentElement && pNewElement) { if (pCurrentElement == pList->m_pTail) pushTail(pList, pNewElement); else { pNewElement->m_pNext = pCurrentElement->m_pNext; pNewElement->m_pLast = pCurrentElement; pNewElement->m_pNext->m_pLast = pNewElement; pCurrentElement->m_pNext = pNewElement; } return true; } return false; } bool remove(chLinkedList* pList, chLinkedListElement* pElement) { if(pList && pElement) { if (pElement == pList->m_pHead) return popHead(pList) ? true: false; if (pElement == pList->m_pTail) return popTail(pList) ? true: false; pElement->m_pNext->m_pLast = pElement->m_pLast; pElement->m_pLast->m_pNext = pElement->m_pNext; pElement->m_pNext = 0; pElement->m_pLast = 0; return true; } return false; } bool isMember(chLinkedList* pList, chLinkedListElement* pElement) { if (pList && pElement) for (chLinkedListElement *pE = pList->m_pHead; pE; pE = pE->m_pNext) if (pE == pElement) return true; return false; }
true
a6666776fd739b917f4aea761d1691dfc85f6304
C++
narghyriou99/syspro-project1
/include/skiplist.h
UTF-8
1,594
3.03125
3
[]
no_license
#ifndef SKIPLIST_H_ #define SKIPLIST_H_ #include <iostream> #include <cstdlib> #include <cmath> #include <cstring> #include "citizen.h" using namespace std; #define MAXLEVEL 10 struct SLN { //Skip List Node int citizenId, level; CN* citizen; //Ptr to citizen SLN** next; //Array of ptrs SLN(int level, int citizenId, CN* citizen) { this->level = level; this->citizenId = citizenId; this->citizen = citizen; next = new SLN * [level + 1]; memset(next, 0, sizeof(SLN*) * (level + 1)); } ~SLN() { delete[] next; } }; class SkipList { private: SLN* head; int level; int maxLevel = MAXLEVEL; public: SkipList( CN* citizen) { level = 0; head = new SLN(maxLevel, -1, NULL); } ~SkipList() { SLN* temp = head; SLN* next = NULL; while (temp != NULL) { next = temp->next[0]; delete temp; temp = next; } head = NULL; } void insertCitizen(int citizenId, CN* citizen); //insert citizen at skiplist int getRandomLevel(); int checkIfCitizenExists(int citizenId); //Search citizen at skip list SLN* getHead(); void deleteCitizen(int citizenId); int getPopulationVirus(const string& countryName); //Get total nodes of a country on a skip list int getPopulationAgeGroup(const string& countryName, int minAge, int maxAge); //Get total nodes in the specific age range from country }; #endif
true
800645e8b6079d0d5d9bf5014429c59b9ca23ccd
C++
imranhasanhira/opengl-oop-framework
/Terrain/SkyBox.cpp
UTF-8
3,745
2.875
3
[]
no_license
/* * File: SkyBox.cpp * Author: Ibrahim * * Created on June 30, 2012, 3:50 AM */ #include "SkyBox.h" GLuint SkyBox::skyTopId = -1; GLuint SkyBox::skyLeftId = -1; GLuint SkyBox::skyRightId = -1; GLuint SkyBox::skyFrontId = -1; GLuint SkyBox::skyBackId = -1; SkyBox::SkyBox(double width, double height, Vector cameraPosition) { this->width = width; this->height = height; this->setPosition(cameraPosition); } SkyBox::SkyBox(const SkyBox& orig) { } SkyBox::~SkyBox() { } void SkyBox::setPosition(Vector position) { this->position = Vector(position.x - width / 2, position.y - width / 2, position.z - width / 2); } void SkyBox::frontBack() { glPushMatrix(); { glNormal3f(0, 1, 0); // glRotatef(270, 0, 0, 1); glBindTexture(GL_TEXTURE_2D, skyFrontId); glBegin(GL_QUAD_STRIP); { glTexCoord2f(0, 0); glVertex3f(width, 0, 0); glTexCoord2f(0, 1); glVertex3f(width, 0, height); glTexCoord2f(1, 0); glVertex3f(0, 0, 0); glTexCoord2f(1, 1); glVertex3f(0, 0, height); } glEnd(); glTranslatef(0, height, 0); glBindTexture(GL_TEXTURE_2D, skyBackId); glBegin(GL_QUAD_STRIP); { glTexCoord2f(0, 0); glVertex3f(0, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, height); glTexCoord2f(1, 0); glVertex3f(width, 0, 0); glTexCoord2f(1, 1); glVertex3f(width, 0, height); } glEnd(); } glPopMatrix(); } void SkyBox::leftRight() { glPushMatrix(); { glNormal3f(0, 1, 0); glBindTexture(GL_TEXTURE_2D, skyRightId); glBegin(GL_QUAD_STRIP); { glTexCoord2f(0, 0); glVertex3f(width, 0, 0); glTexCoord2f(0, 1); glVertex3f(width, 0, height); glTexCoord2f(1, 0); glVertex3f(0, 0, 0); glTexCoord2f(1, 1); glVertex3f(0, 0, height); } glEnd(); glTranslatef(0, height, 0); glBindTexture(GL_TEXTURE_2D, skyLeftId); glBegin(GL_QUAD_STRIP); { glTexCoord2f(0, 0); glVertex3f(0, 0, 0); glTexCoord2f(0, 1); glVertex3f(0, 0, height); glTexCoord2f(1, 0); glVertex3f(width, 0, 0); glTexCoord2f(1, 1); glVertex3f(width, 0, height); } glEnd(); } glPopMatrix(); } void SkyBox::top() { glPushMatrix(); { glNormal3f(0, 0, 1); glBindTexture(GL_TEXTURE_2D, skyTopId); glBegin(GL_QUAD_STRIP); { glTexCoord2f(0, 0); glVertex3f(height, height, height); glTexCoord2f(0, 1); glVertex3f(0, height, height); glTexCoord2f(1, 0); glVertex3f(height, 0, height); glTexCoord2f(1, 1); glVertex3f(0, 0, height); } glEnd(); } glPopMatrix(); } void SkyBox::paint() { // position.showln(); glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); glPushMatrix(); { glEnable(GL_TEXTURE_2D); { frontBack(); glTranslatef(0, width, 0); glRotatef(-90, 0, 0, 1); leftRight(); top(); } glDisable(GL_TEXTURE_2D); } glPopMatrix(); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); }
true
992e18ff5e0b04fbda002fce1157d86eb67356ed
C++
jiri/constellation
/src/Foundation/Infrastructures/Wiring.hpp
UTF-8
2,516
2.828125
3
[]
no_license
#pragma once #include <set> #include <Foundation/Infrastructures/Infrastructure.hpp> class Wiring; class Connector { public: virtual ~Connector() = default; virtual void merge(Connector* other) = 0; virtual void split(Connector* other) = 0; virtual glm::vec2& position() = 0; bool magnetic = false; Connector* other = nullptr; }; class CableConnector : public Connector { public: CableConnector(glm::vec2 pos) : cablePosition { new glm::vec2 { pos } } { } virtual ~CableConnector() { if (this->owner) { delete this->cablePosition; } } void merge(Connector* other) override; void split(Connector* other) override; glm::vec2& position() override { return *cablePosition; } private: glm::vec2* cablePosition; bool owner = false; }; class EndpointConnector : public Connector { friend class Wiring; public: explicit EndpointConnector(Endpoint* e); void merge(Connector* other) override; void split(Connector* other) override; glm::vec2& position() override { fakePosition = endpoint->globalPosition(); return fakePosition; } private: Endpoint* endpoint; glm::vec2 fakePosition; }; class Cable { friend class Wiring; public: CableConnector a; CableConnector b; private: Cable(glm::vec2 aPos, glm::vec2 bPos); }; class Socket : public Endpoint { friend class Wiring; public: EndpointConnector connector; private: explicit Socket(Capabilities c); }; class WiringConnection { public: /* Ensures that a < b */ WiringConnection(Connector* a, Connector* b, bool internal); Connector* a = nullptr; Connector* b = nullptr; bool internal = false; }; static bool operator<(const WiringConnection& a, const WiringConnection& b) { if (a.a == b.a) { if (a.b == b.b) { return false; } else { return a.b < b.b; } } else { return a.a < b.a; } } class Wiring : public Infrastructure { friend void DrawGraph(Universe& universe); public: using Infrastructure::Infrastructure; ~Wiring() final; void update() override; bool occupied(Connector* c) const; Socket* createSocket(Capabilities c); Cable* createCable(glm::vec2 aPos, glm::vec2 bPos); private: std::set<WiringConnection> connections; std::vector<Cable*> cables; std::set<Connector*> connectors; void join(Connector* a, Connector* b, bool internal = false); void separate(Connector* a, Connector* b, bool internal = false); EndpointConnector* findOther(EndpointConnector* connector); };
true
b25344e9feff13863bcde8f4ca32da5547e1b45e
C++
southpawgeek/perlweeklychallenge-club
/challenge-153/ulrich-rieke/cpp/ch-2.cpp
UTF-8
761
3.09375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <vector> #include <algorithm> #include <numeric> int factorial( int num ) { if ( num == 0 ) { return 1 ; } else { int fac = 1 ; for ( int i = 1 ; i < num + 1 ; i++ ) fac *= i ; return fac ; } } int main( int argc, char* argv[] ) { int n = std::atoi( argv[1] ) ; int c = n ; //we are "destroying" n in the next lines std::vector<int> digits ; while ( n != 0 ) { digits.push_back( n % 10 ) ; n /= 10 ; } std::transform( digits.begin( ) , digits.end( ) , digits.begin( ) , factorial ) ; if ( std::accumulate( digits.begin( ) , digits.end( ) , 0 ) == c ) std::cout << 1 << std::endl ; else std::cout << 0 << std::endl ; return 0 ; }
true
71bcf56432621dd7487e8b8ed1c05ca4836717d8
C++
nploi/Cplusplus
/Exercise/HackerRank/Data Structures/Heap/JesseAndCookies.cpp
UTF-8
736
2.84375
3
[]
no_license
//https://www.hackerrank.com/challenges/jesse-and-cookies/problem #include<iostream> #include <queue> #include <vector> using namespace std; #define ll long long int main() { priority_queue<ll, vector<ll>, greater<ll> > pq; ll n, k; cin >> n >> k; for (int i = 0; i < n; ++i) { ll val; cin >> val; pq.push(val); } ll sweetness = 0, count = 0, top1, top2; while(pq.size() >= 2 && pq.top() < k) { top1 = pq.top(); pq.pop(); top2 = pq.top(); pq.pop(); sweetness = top1 + 2 * top2; count++; pq.push(sweetness); }; if(pq.top() < k){ cout << "-1"; }else { cout << count; } return 0; }
true
a7e870e5599f0bd3d53acc8476a4a8f31cc318d1
C++
WhiZTiM/coliru
/Archive2/a2/fe9847b43e2d0e/main.cpp
UTF-8
665
3.3125
3
[]
no_license
#include <iostream> #include <vector> #include <cstdlib> #include <ctime> using namespace std; struct Foo { string str; int a; vector<int> vec; int b; int *ptr; }; int main() { // simulating memory randomizing // { srand(time(0)); unsigned char *buf = new unsigned char[1024]; for (size_t i = 0; i < 1024; ++i) { buf[i] = (unsigned char)(rand() % 256); } delete buf; // } Foo *ptr = new Foo(); cout << "str = " << ptr->str << endl; cout << "a = " << ptr->a << endl; cout << "b = " << ptr->b << endl; cout << "ptr = " << ptr->ptr << endl; return 0; }
true
df2a616e844a968b25a2068d90fcda090af8f59e
C++
bluepine/topcoder
/topcoder-master/Jewelry.cpp
UTF-8
3,680
2.53125
3
[]
no_license
#include<iostream> #include<cstdio> #include<cctype> #include<cmath> #include<cstdlib> #include<algorithm> #include<vector> #include<string> #include<list> #include<deque> #include<map> #include<set> #include<queue> #include<stack> #include<utility> #include<sstream> #include<cstring> using namespace std; typedef vector<int> VI; class Jewelry { public: static const int max_pieces = 35; static const int max_value = 1005; void calc(VI::iterator a, VI::iterator b, long long t[], long long s) { VI::iterator i; long long tmp[max_value*max_pieces]; memset(t, 0, sizeof(long long)*max_value*max_pieces); // cout << endl; // cout << "uzywam: "; for (i = a; i != b; i++) { memset(tmp, 0, sizeof(long long)*max_value*max_pieces); // cout << *i << " "; for (int j = 1; j <= s; ++j) { if (t[j]) { tmp[j+(*i)] += t[j]; } } tmp[*i]++; for (int j = 1; j <= s; ++j) { t[j] += tmp[j]; } } // cout << endl; } long long howMany(VI vs) { long long ta[max_value*max_pieces]; long long tb[max_value*max_pieces]; long long tmp[max_value*max_pieces]; long long result = 0; long long sa = vs[0]; long long sb = 0; VI::iterator ii; memset(ta, 0, sizeof(long long)*max_value*max_pieces); for (int i = 1; i < vs.size(); ++i) sb += vs[i]; sort(vs.begin(), vs.end()); for (int i = 1; i < vs.size(); ++i) { // cout << "a (" << sa << ") : "; // for (int j = 0; j < i; ++j) { // cout << vs[j] << " "; // } // cout << endl; // calc(vs.begin(), vs.begin()+i, ta, min(sa, sb)); for (int j = 1; j <= sa; ++j) { if (ta[j]) { tmp[j+vs[i-1]] += ta[j]; } } tmp[vs[i-1]]++; // cout << endl; cout << "tmp: "; for (int j = 1; j < 20; ++j) { cout << j << " "; } cout << endl; cout << "tmp: "; for (int j = 1; j < 20; ++j) { cout << tmp[j] << " "; } cout << endl; calc(vs.begin()+i, vs.end(), tb, min(sa, sb)); cout << "b (" << sb << ") : "; for (int j = i; j < vs.size(); ++j) { cout << vs[j] << " "; } cout << endl; cout << "b: "; for (int j = 1; j < 20; ++j) { cout << j << " "; } cout << endl; cout << "b: "; for (int j = 1; j < 20; ++j) { cout << tb[j] << " "; } cout << endl; for (int j = 0; j < max_pieces*max_value; ++j) { if (tmp[j] && tb[j]) { result += tmp[j]*tb[j]; } } for (int j = 1; j <= sa; ++j) { ta[j] += tmp[j]; } memset(tmp, 0, sizeof(long long)*max_value*max_pieces); sa += vs[i]; sb -= vs[i]; } return result; } };
true
fa68dc6385ba7e804b5c1b4aba5d1c3fbcbcc990
C++
WarlordRises/Odyssey
/src/myengine/Keyboard.cpp
UTF-8
477
2.609375
3
[]
no_license
#include "Keyboard.h" Keyboard::Keyboard() { } Keyboard::~Keyboard() { } //bool Keyboard::GetKey(int _keyCodes) //{ // //} // //bool Keyboard::GetKeyDown(int _keyCodes) //{ // //} // //bool Keyboard::GetKeyUp(int _keyCodes) //{ // //} bool Keyboard::Events() { SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_KEYDOWN) { std::cout << "hey" << std::endl; } if (event.type == SDL_QUIT) { return false; } } return true; }
true
3433e57bae179a51d3658db4adf9423290a1a2e9
C++
mrfeod/libstepparser
/src/tokenizer/token.cpp
UTF-8
1,178
3.453125
3
[]
no_license
#include "token.hpp" using namespace std; Token::Token(const Token::Id& i) : id_(i) { if (i == Id::NUMBER) { data_ = 0.; } else { data_ = string(); } } Token::Token(const string& str) : id_(Id::STR) { data_ = str; } Token::Token(double num) : id_(Id::NUMBER) { data_ = num; } bool Token::empty() const { return id_ == Id::NIL; } Token& Token::clear() { id_ = Id::NIL; data_ = string(); return *this; } Token::Id Token::get_id() const { return id_; } string Token::to_str() const { string result; if (holds_alternative<string>(data_)) result = get<string>(data_); return result; } double Token::to_number() const { double result = 0; if (holds_alternative<double>(data_)) result = get<double>(data_); return result; } string Token::raw() const { string result; switch (id_) { case Id::NIL: break; case Id::STR: result = to_str(); break; case Id::NUMBER: result = to_string(to_number()); break; } return result; } ostream& operator<<(ostream& os, const Token& x) { return os << x.raw(); }
true
9d71459b3ec10f05c761463566efa5fa0548733c
C++
alexandraback/datacollection
/solutions_1483488_1/C++/itsuper/C.cc
UTF-8
1,258
2.71875
3
[]
no_license
#include <iostream> #include <cstring> #include <fstream> #include <string> #include <cstring> #include <vector> #include <algorithm> using namespace std; ifstream input; ofstream output; long long f[12]; int icount(long long num,int n,long long up) { if ( n == 1) return 0; int res = 0; vector <long long> vec; vec.clear(); for (int i = 1;i< n;++i) { long long k = num / f[i]; long long t = num % f[i]; long long newnum = t * f[n-i] + k; if (newnum > num && newnum <= up && find(vec.begin(),vec.end(), newnum) == vec.end()) { vec.push_back(newnum); ++res; } } return res; } void Work() { long long A, B; input >> A >>B; int sum = 0; int n = 0; long long t = B; while(t) { ++n; t/=10; } for (long long i = A; i<= B;++i) { sum += icount(i,n,B); } // cout<<sum<<endl; output<<sum<<endl; } void init() { f[0] = 1; for (int i = 1;i< 12;++i) { f[i] = f[i-1]*10; } } int main() { int t = 0; string inputfile("inputC.in"); string outputfile("outputC.out"); input.open(inputfile.c_str()); output.open(outputfile.c_str()); input>>t; int tcase = 0; init(); while( t--) { ++tcase; output<<"Case #"<<tcase<<": "; Work(); } }
true
e5b57e1c4bd2181fbb148c0adba4bf96120e38c8
C++
znvmk/Study
/CPP/STL/2.C++程序标准库/5.8-以函数作为算法的参数/print.hpp
UTF-8
261
3
3
[ "WTFPL" ]
permissive
#include <iostream> template<class T> inline void PRINT_ELEMENTS(const T& col1, const char* optcstr="") { typename T::const_iterator pos; std::cout<<optcstr; for(pos=col1.begin();pos!=col1.end();++pos) { std::cout<<*pos<<' '; } std::cout<<std::endl; }
true
35c2965cc653df307ea346d6da22bc34ed122c83
C++
llu0120/Cpp-Algorithm
/DataStructure/array/GameofLife.cpp
UTF-8
3,541
3.9375
4
[]
no_license
/* According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by over-population.. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Example: Input: [ [0,1,0], [0,0,1], [1,1,1], [0,0,0] ] Output: [ [0,0,0], [1,0,1], [0,1,1], [0,1,0] ] Follow up: Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? */ //O(mn) class Solution { public: void gameOfLife(vector<vector<int>>& board) { //Corner Case: if (board.size() == 0) { return; } //General Case: int m = board.size(); int n = board[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int liveNeighbor = liveNeighborsNum(board, m, n, i, j); //Died case --> use 3 to represent if ((board[i][j] == 1 && liveNeighbor < 2) || (board[i][j] == 1 && liveNeighbor > 3)) { board[i][j] = 3; } //Recover case --> use 4 to represent if (board[i][j] == 0 && liveNeighbor == 3) { board[i][j] = 4; } } } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 3) { //if board[i][j] == 3 -> the cell will die next gen board[i][j] = 0; } if (board[i][j] == 4) { //if board[i][j] == 4 -> the cell will recover next gen board[i][j] = 1; } } } return; } int liveNeighborsNum(vector<vector<int>>& board, int m, int n, int i, int j) { int neighborsNum = 0; for (int y = i - 1; y <= i + 1; y++) { if (y < 0 || y >= m) continue; for (int x = j - 1; x <= j + 1; x++) { if (x < 0 || x >= n) continue; if (board[y][x] == 1 || board[y][x] == 3) { //board[y][x] == 3 means the cell is originally alive == 1 but will died == 0 next generation neighborsNum++; } } } if (board[i][j] == 1) { //If the cell itself is 1 --> need to substract one to the calculated number of live neighbor neighborsNum--; } return neighborsNum; } };
true
d696089a0993219434db4c8e397554a9d3ed0975
C++
nguyentrungduc08/Socks5_Scan
/socScanPort.cpp
WINDOWS-1252
19,582
2.78125
3
[]
no_license
#include "definition.h" int sendData_s(SOCKET s, const void *buffer, int buflen) { const char *pbuf = (const char*) buffer; while (buflen > 0) { int numSent = send(s, pbuf, buflen, 0); if (numSent == SOCKET_ERROR) return SOCKET_ERROR; pbuf += numSent; buflen -= numSent; } return 1; } int recvData_s(SOCKET s, void *buffer, int buflen) { char *pbuf = (char*) buffer; while (buflen > 0) { int numRecv = recv(s, pbuf, buflen, 0); if (numRecv == SOCKET_ERROR) return SOCKET_ERROR; if (numRecv == 0) return 0; pbuf += numRecv; buflen -= numRecv; } return 1; } SOCKET connnectSOCKS5packet1_s(GETQ * get,fd_set * rset, fd_set * wset){ int initPacket1Length = 3; char initPacket1[initPacket1Length]; initPacket1[0] = 5; initPacket1[1] = 1; initPacket1[2] = 0; if (sendData_s(get->fd, initPacket1, initPacket1Length) < 0){ std::cerr << "Can't send first init packet to SOCKS server!" << std::endl; //closesocket(get->fd); return INVALID_SOCKET; } else { FD_CLR(get->fd, wset); FD_SET(get->fd, rset); get->flags = READRES1; return 1; } } bool checkConnnectSOCKS5packet1_s(GETQ * get, fd_set * rset, fd_set * wset){ char reply1[2]; //recv(get->fd, reply1, 2, 0); if (recvData_s(get->fd, reply1, 2) <= 0) { std::cerr<< "Error reading first init packet response!" <<"" << reply1 << std::endl; return false; } //std::cerr << "read 1: " << reply1 << std::endl; //std::cout <<"check 1" << reply1 << std::endl; //reply[0] = our version //reply[1] = out method. [X00 NO AUTHENTICATION REQUIRED] if( !(reply1[0] == 5 && reply1[1] == 0) ) { std::cerr << "Bad response for init packet!" << std::endl; return false; } FD_CLR(get->fd, rset); FD_SET(get->fd, wset); return true; } SOCKET connnectSOCKS5packet2_s(GETQ * get, fd_set * rset, fd_set * wset){ DestInfo destInfo; destInfo.hostname = "google.com"; destInfo.port = 80; int hostlen = std::max((int)destInfo.hostname.size(), 255); //Building that packet char *initPacket2 = new char[7+hostlen]; initPacket2[0] = 5; //SOCKS Version; initPacket2[1] = 1; //1 = CONNECT, 2 = BIND, 3 = UDP ASSOCIATE; initPacket2[2] = 0; //Reserved byte initPacket2[3] = 3; //1 = IPv4, 3 = DOMAINNAME, 4 = IPv6 initPacket2[4] = (char) hostlen; memcpy(&initPacket2[5], destInfo.hostname.c_str(), hostlen); *((u_short*) &(initPacket2[5+hostlen])) = htons(destInfo.port); //Send the second init packet to server. This will inform the SOCKS5 server //what is our target. if (sendData_s(get->fd, initPacket2, 7+hostlen) < 0) { std::cerr << "Can't send second init packet!" << std::endl; delete[] initPacket2; return INVALID_SOCKET; } //std::cout <<"send 2" << std::endl; FD_CLR(get->fd, wset); FD_SET(get->fd, rset); get->flags = READRES2; delete[] initPacket2; return 1; } bool checkConnnectSOCKS5packet2_s(GETQ * get , fd_set * rset, fd_set * wset) { char reply2[262]; if (recvData_s(get->fd, reply2, 4) <= 0) { std::cerr << "Error while reading response for second init packet!"<< std::endl; //closesocket(hSocketSock); return false; } //std::cout <<"check 2" << reply2 << std::endl; FD_CLR(get->fd, rset); FD_SET(get->fd, wset); if (!(reply2[0] == 5 && reply2[1] == 0)) { std::cerr << "The connection between and SOCKS and DESTINATION can't be established!"<< std::endl; //closesocket(hSocketSock); return false; } return true; } int sendNon_s(GETQ *get, fd_set * rset, fd_set * wset, int * maxfd){ WSADATA wsaData; int iResults = WSAStartup(MAKEWORD(2,2), &wsaData); int n, flags; struct sockaddr_in addr; addr.sin_family = AF_INET; // host byte order addr.sin_port = htons(get->port); // short, network byte order addr.sin_addr.S_un.S_addr = inet_addr(get->host.c_str()); // adding socks server IP address into structure int sendfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); u_long iMode = 1; int iResult = ioctlsocket(sendfd, FIONBIO, &iMode); if (sendfd < 0){ puts("can't create socket!!"); closesocket(sendfd); return -1; } get->fd = sendfd; if ( (n = connect(sendfd, (struct sockaddr*) &addr, sizeof(addr) ) ) < 0 ){ get->flags = CONNECTING; FD_SET(sendfd, rset); FD_SET(sendfd, wset); if (sendfd > *maxfd ){ //std::cout <<"max : " << *maxfd << " " << sendfd <<std::endl; *maxfd = sendfd; } return sendfd; } else{ //closesocket(sendfd); connnectSOCKS5packet1_s(get, rset,wset); //return -1; } } bool checkPort(int port, std::vector<std::string>listIP, std::ofstream& outF){ WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); std::vector<GETQ> listCon; listCon.clear(); std::stack<GETQ> sCon; fd_set rset, wset; FD_ZERO(&rset); FD_ZERO(&wset); int maxfd = -1; rep(i,listIP.size()){ GETQ que; que.fd = 0; que.host = listIP[i]; que.flags = 0; que.port = port; sCon.push(que); } int nconn = 0; while ( !sCon.empty() || nconn > 0){ while (!sCon.empty() && nconn < NOS_DEFAULT) { int fdu = -1; GETQ con = sCon.top(); sCon.pop(); fdu = sendNon_s(&con, &rset, &wset, &maxfd); if (fdu >= 0 ){ listCon.pb(con); ++nconn; } } fd_set rs,ws; rs = rset; ws = wset; struct timeval timeout; timeout.tv_sec = TIMEOUT; timeout.tv_usec = 0; int n = select(maxfd + 1, &rs, &ws, NULL, &timeout); //std::cout << "max: " << maxfd << std::endl; //rep(i,listCon.size()) // std::cout << listCon.size()<<" " <<listCon[i].host <<" " <<listCon[i].flags << " " <<maxfd<< std::endl; if (n > 0){ rep(i,listCon.size()){ int fdu = listCon[i].fd; int flags = listCon[i].flags; //std::cout << fdu <<" " << flags << std::endl; if ( (flags & CONNECTING) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( connnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } } else if ( (flags & READRES1) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( checkConnnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) ){ if (connnectSOCKS5packet2_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } //std::cout <<listC[i].host <<" " <<listC[i].flags <<" "<<fdu << " " << listC[i].port << std::endl; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } } else if ( (flags & READRES2) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ //std::cout <<"ok reciver 2" << std::endl; if ( checkConnnectSOCKS5packet2_s(&listCon[i], &rset,&wset)){ outF <<listCon[i].host <<":" << listCon[i].port <<"\n"; std::cout << " socks5 "<<listCon[i].host <<":" << listCon[i].port << " ok\n"; FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); listCon[i].flags = DONE; closesocket(fdu); --nconn; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); } } } } else{ rep(i,listCon.size()){ if (listCon[i].flags != DONE) { closesocket(listCon[i].fd); --nconn; } } FD_ZERO(&rset); FD_ZERO(&wset); listCon.clear(); } } } bool checkPortNoConfirm(int port, std::vector<std::string>listIP, std::ofstream& outF){ WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); std::vector<GETQ> listCon; listCon.clear(); std::stack<GETQ> sCon; fd_set rset, wset; FD_ZERO(&rset); FD_ZERO(&wset); int maxfd = -1; rep(i,listIP.size()){ GETQ que; que.fd = 0; que.host = listIP[i]; que.flags = 0; que.port = port; sCon.push(que); } int nconn = 0; while ( !sCon.empty() || nconn > 0){ while (!sCon.empty() && nconn < NOS_DEFAULT) { int fdu = -1; GETQ con = sCon.top(); sCon.pop(); fdu = sendNon_s(&con, &rset, &wset, &maxfd); if (fdu >= 0 ){ listCon.pb(con); ++nconn; } } fd_set rs,ws; rs = rset; ws = wset; struct timeval timeout; timeout.tv_sec = TIMEOUT; timeout.tv_usec = 0; int n = select(maxfd + 1, &rs, &ws, NULL, &timeout); //std::cout << "max: " << maxfd << std::endl; //rep(i,listCon.size()) // std::cout << listCon.size()<<" " <<listCon[i].host <<" " <<listCon[i].flags << " " <<maxfd<< std::endl; if (n > 0){ rep(i,listCon.size()){ int fdu = listCon[i].fd; int flags = listCon[i].flags; //std::cout << fdu <<" " << flags << std::endl; if ( (flags & CONNECTING) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( connnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); --nconn; } else{ //std::cout <<"ok send 1 " << listCon[i].flags <<"\n"; } } else if (flags & READRES1 && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( checkConnnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) ){ outF <<listCon[i].host <<":" << listCon[i].port <<"\n"; std::cout << " socks5 "<<listCon[i].host <<":" << listCon[i].port << " ok\n"; FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); listCon[i].flags = DONE; closesocket(fdu); --nconn; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); --nconn; } } } } else{ rep(i,listCon.size()){ if (listCon[i].flags != DONE) { closesocket(listCon[i].fd); --nconn; } } FD_ZERO(&rset); FD_ZERO(&wset); listCon.clear(); } } } bool checkPort_P(std::vector<std::pair<std::string, int> > checkList, std::ofstream& outF, int nos, int timeout){ WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2,2), &wsaData); std::vector<GETQ> listCon; listCon.clear(); std::stack<GETQ> sCon; fd_set rset, wset; FD_ZERO(&rset); FD_ZERO(&wset); int maxfd = -1; rep(i,checkList.size()){ GETQ que; que.fd = 0; que.host = checkList[i].X; que.flags = 0; que.port = checkList[i].Y; sCon.push(que); } int nconn = 0; while ( !sCon.empty() || nconn > 0){ while (!sCon.empty() && nconn < NOS_DEFAULT) { int fdu = -1; GETQ con = sCon.top(); sCon.pop(); fdu = sendNon_s(&con, &rset, &wset, &maxfd); if (fdu >= 0 ){ listCon.pb(con); std::cout <<"fd: " << con.fd << std::endl; ++nconn; } } fd_set rs,ws; rs = rset; ws = wset; struct timeval timeout; timeout.tv_sec = TIMEOUT; timeout.tv_usec = 0; int n = select(maxfd + 1, &rs, &ws, NULL, &timeout); //std::cout << "max: " << maxfd << std::endl; //rep(i,listCon.size()) // std::cout << listCon.size()<<" " <<listCon[i].host <<" " <<listCon[i].flags << " " <<maxfd<< std::endl; if (n > 0){ rep(i,listCon.size()){ int fdu = listCon[i].fd; int flags = listCon[i].flags; //std::cout << fdu <<" " << flags << std::endl; if ( (flags & CONNECTING) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( connnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } } else if ( (flags & READRES1) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( checkConnnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) ){ if (connnectSOCKS5packet2_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } //std::cout <<listC[i].host <<" " <<listC[i].flags <<" "<<fdu << " " << listC[i].port << std::endl; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); --nconn; closesocket(fdu); } } else if ( (flags & READRES2) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ //std::cout <<"ok reciver 2" << std::endl; if ( checkConnnectSOCKS5packet2_s(&listCon[i], &rset,&wset)){ outF <<listCon[i].host <<":" << listCon[i].port <<"\n"; std::cout << " socks5 "<<listCon[i].host <<":" << listCon[i].port << " ok\n"; FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); listCon[i].flags = DONE; closesocket(fdu); --nconn; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); } } } } else{ rep(i,listCon.size()){ if (listCon[i].flags != DONE) { closesocket(listCon[i].fd); --nconn; } } FD_ZERO(&rset); FD_ZERO(&wset); listCon.clear(); } } } bool checkPortNoConfirm_P(std::vector<std::pair<std::string, int> > checkList, std::ofstream& outF, int nos, int timeout){ std::vector<GETQ> listCon; listCon.clear(); std::stack<GETQ> sCon; fd_set rset, wset; FD_ZERO(&rset); FD_ZERO(&wset); int maxfd = -1; rep(i,checkList.size()){ GETQ que; que.fd = 0; que.host = checkList[i].X; que.flags = 0; que.port = checkList[i].Y; sCon.push(que); } int nconn = 0; while ( !sCon.empty() || nconn > 0){ while (!sCon.empty() && nconn < NOS_DEFAULT) { int fdu = -1; GETQ con = sCon.top(); sCon.pop(); fdu = sendNon_s(&con, &rset, &wset, &maxfd); if (fdu > 0 ){ //std::cout <<"fd: " << fdu << std::endl; listCon.pb(con); ++nconn; } } fd_set rs,ws; rs = rset; ws = wset; struct timeval timeout; timeout.tv_sec = TIMEOUT; timeout.tv_usec = 0; int n = select(maxfd + 1, &rs, &ws, NULL, &timeout); //std::cout << "max: " << maxfd <<" " << " "<< sCon.size() << " " << listCon.size() << " " << n <<" ";// std::endl; //rep(i,listCon.size()) //std::cout << listCon.size()<<" " <<listCon[i].host <<" " <<listCon[i].flags << " " <<maxfd << " ";// std::endl; if (n > 0){ rep(i,listCon.size()){ int fdu = listCon[i].fd; int flags = listCon[i].flags; //std::cout << fdu <<" " << flags << std::endl; if ( (flags & CONNECTING) && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ std::cout <<listCon[i].host <<":"<< listCon[i].port << std::endl; if ( connnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) == INVALID_SOCKET){ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); --nconn; } else{ //std::cout <<"ok send 1 " << listCon[i].flags <<"\n"; } } else if (flags & READRES1 && ( FD_ISSET(fdu,&rs) || FD_ISSET(fdu,&ws) ) ){ if ( checkConnnectSOCKS5packet1_s(&listCon[i] , &rset,&wset) ){ outF <<listCon[i].host <<":" << listCon[i].port <<"\n"; std::cout << " socks5 "<<listCon[i].host <<":" << listCon[i].port << " ok\n"; FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); listCon[i].flags = DONE; closesocket(fdu); --nconn; }else{ FD_CLR(fdu, &wset); FD_CLR(fdu, &rset); closesocket(fdu); --nconn; } } } } else{ rep(i,listCon.size()){ if (listCon[i].flags != DONE) { closesocket(listCon[i].fd); --nconn; } } FD_ZERO(&rset); FD_ZERO(&wset); listCon.clear(); } } }
true
37a9a81174c8ff1e8786eac11a1b02ca64926cdb
C++
S0mas/ChessNew
/bishop.cpp
UTF-8
4,186
2.78125
3
[]
no_license
#include "pieces.h" #include <typeinfo> Bishop::Bishop(int player, int x, int y) { owner = player; if(owner>0) { value = 105; } else { value = -105; } i=x; j=y; activeOn=false; this->setText("B"); } Bishop::~Bishop() { } void Bishop::checkActive() { if(activeOn==false) { activeOn=true; this->setStyleSheet("background:#F0F000"); } else { activeOn=false; this->setStyleSheet("background: transparent;"); } } bool Bishop::checkMove(int x, int y, Pieces ***pPieces) { int c2 = j; if(x-i==y-j||x-i==j-y)//Warunki ruchu Królowa { if(x>i&&y>j) { for(int c1 = i+1; c1<=x; c1++) { c2 = c2 + 1; if(c2!=y&&pPieces[c1][c2]->owner!=0) { return false; } if(c2==y&&pPieces[x][y]->owner==pPieces[i][j]->owner) { return false; } } } if(x<i&&y>j) { for(int c1 = i-1; c1>=x; c1--) { c2 = c2 + 1; if(c2!=y&&pPieces[c1][c2]->owner!=0) { return false; } if(c2==y&&pPieces[x][y]->owner==pPieces[i][j]->owner) { return false; } } } if(x>i&&y<j) { for(int c1 = i+1; c1<=x; c1++) { c2 = c2 - 1; if(c2!=y&&pPieces[c1][c2]->owner!=0) { return false; } if(c2==y&&pPieces[x][y]->owner==pPieces[i][j]->owner) { return false; } } } if(x<i&&y<j) { for(int c1 = i-1; c1>=x; c1--) { c2 = c2 - 1; if(c2!=y&&pPieces[c1][c2]->owner!=0) { return false; } if(c2==y&&pPieces[x][y]->owner==pPieces[i][j]->owner) { return false; } } } return true; } return false; } bool Bishop::checkMove(int x, int y, Pieces ***pPieces, bool roszadaL, bool roszadaP){} bool Bishop::checkCheck(int x, int y, Pieces*** pPieces) { return false; } /*{ int c2 = j; for(int c1 = i+1; c1<=7; c1++) { c2 = c2 + 1; if(c2>7) { break; } if(pPieces[c1][c2]->owner==owner||(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])!=typeid(King))) { break; } if(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])==typeid(King)) { return true; } } c2 = j; for(int c1 = i+1; c1<=7; c1++) { c2 = c2 - 1; if(c2<0) { break; } if(pPieces[c1][c2]->owner==owner||(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])!=typeid(King))) { break; } if(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])==typeid(King)) { return true; } } c2 = j; for(int c1 = i-1; c1>=0; c1--) { c2 = c2 + 1; if(c2>7) { break; } if(pPieces[c1][c2]->owner==owner||(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])!=typeid(King))) { break; } if(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])==typeid(King)) { return true; } } c2 = j; for(int c1 = i-1; c1>=0; c1--) { c2 = c2 - 1; if(c2<0) { break; } if(pPieces[c1][c2]->owner==owner||(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])!=typeid(King))) { break; } if(pPieces[c1][c2]->owner==-owner&&typeid(*pPieces[c1][c2])==typeid(King)) { return true; } } return false; }*/
true
f129ef3b78227f4322ff5fc3c5c9fbcd4ba9f934
C++
md143rbh7f/competitions
/topcoder/srm/433/MagicWords.cpp
UTF-8
643
2.796875
3
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; char tmp[200]; int p[8]; struct MagicWords { int count( vector<string> s, int k ) { for( int i = 0; i < s.size(); i++ ) p[i] = i; int ans = 0; do { int index = 0, i = 0, j = 0; for( i = 0; i < s.size(); i++ ) for( j = 0; j < s[p[i]].size(); j++ ) tmp[index++] = s[p[i]][j]; for( i = 1; i <= index; i++ ) if( index % i == 0 ) { for( j = 0; j < index && tmp[j] == tmp[(i+j)%index]; j++ ); if( j == index ) break; } if( i * k == index ) ans++; } while(next_permutation(p,p+s.size())); return ans; } };
true
e533002ce61f08dff91b2a1658810dbc936fa959
C++
egorlw26/UniversityLabs
/5th_Course/Semester1/Cryptography/Lab3/SHA-256/SHA-256/SHA_256.h
UTF-8
2,221
2.5625
3
[]
no_license
#pragma once #include <string> #include <vector> class SHA_256 { private: // round constants const unsigned int K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; std::vector<std::vector<unsigned int>> m_blocks; std::vector<unsigned int> m_hash; int m_numberOfBlocks; std::vector<unsigned char> m_bytes; unsigned long long m_message_length_in_bits; unsigned int ROTR(const unsigned int& n, const unsigned int& x); unsigned int SHR(const unsigned int& n, const unsigned int& x); unsigned int Ch(const unsigned int& x, const unsigned int& y, const unsigned int& z); unsigned int Maj(const unsigned int& x, const unsigned int& y, const unsigned int& z); unsigned int lSigma0(const unsigned int& x); unsigned int lSigma1(const unsigned int& x); unsigned int sSigma0(const unsigned int& x); unsigned int sSigma1(const unsigned int& x); void stringToBytes(const std::string& msg); void padding(); void parse(); int calcPadding(); void computeHash(); void createHash(const std::string& i_msg); void clearState(); public: void showResultHash(); std::string getResultString(); SHA_256(const std::string& msg); };
true
26a2a2ed0a0c0903267455e6f253111e92609aa8
C++
liuruoqian/CS225
/mp7/maze.h
UTF-8
461
2.921875
3
[]
no_license
/* Your code here! */ #include <vector> #include "png.h" using namespace std; #ifndef _MAZE_H #define _MAZE_H class SquareMaze{ public: SquareMaze(); void makeMaze(int width, int height); bool canTravel(int x, int y, int dir) const; void setWall(int x, int y, int dir, bool exists); vector<int> solveMaze(); PNG * drawMaze() const; PNG * drawMazeWithSolution(); private: int wid; int hgt; vector<bool> downWall; vector<bool> rightWall; }; #endif
true
4cf476855a2de93d47ab1e048de5c60fa46b2b4f
C++
xinlianyu/EventCollection
/weights.h
UTF-8
8,115
2.59375
3
[]
no_license
/* Edge Weight Classes Brian Dean 1997 Adapted by Song Gao for stochastic dependent link travel times April 29, 2004 Song Gao, Added NOI related variables, Feburary 2007 */ #pragma comment(lib,"ws2_32.lib") #ifndef EDGEWEIGHTS #define EDGEWEIGHTS #define INT_INFINITY (int)2147000000 #define FLOAT_INFINITY (float)1.0e38 #define DOUBLE_MAX 1.7e308 #include "network.h" //use a piece-wise linear function to describe dynamic link travel times typedef pair<long, float> bp; //breaking point typedef vector<bp> bps; //breaking points class EdgeWeights { private: long _levels; //number of time periods long _numreal; //number of joint realizations (R) long _agglength; //aggregation length of link travel times (i.e. length of a time interval) in seconds long _numdefaults; //number of default breaking point long _numtimeslices; //number of time slices for dynamic link travel time step functions public: float **realization; //joint realizations of link travel times float *prob; //probabilities of each joint realization //float **expectedtt; //expected travel time for each time and each link //float ***marginaltt; //marginal travel time realizations for each time and link //float ***marginalprob; //marginal probabilities //int **nummarginalprob; //number of marginal support points for each time and link long *defaults; //the default breaking points entry time bps **BP; //breaking point pairs for each link and each support point (both deterministic and stochastic links) bps *ExpectedBP; //breaking point pairs for expected travel times of each link //short **det_flag; //flag for each link whether it is determinstic short *det_flag; long *slicestart; //entry time of each time slice (the same over all links): start with 12am and end with 11:59pm long **numsupportpoints; //number of support points for each link and each time slice long ***supportpoints; //support points for each link and each time slice float ***probability; //probability of each support point for each link at each time slice (#links x #time slices x #support points) float *avgtime; //average travel times int ***blocked; void write_weights(char *filename, Network *N); void calexpected(Network *N, long EV_start, long EV_end, long **event, long start_time); void calexpectedBP(Network *N); //void calexpected(Network *N); //void calmarginal(Network *N); float *pathtimes(long origIndex, long destIndex, long pathIndex, long t, Network *N, long EV_start, long EV_end, long flag, long **event=NULL); float pathtime(long origIndex, long destIndex, long pathIndex, long t, Network *N, long r); EdgeWeights(Network *N, long __levels = 1, long __agglength = 1, long __numreal = 1) { long i, numlinks = N->NumLinks(); assert( __levels > 0 ); _levels = __levels; assert( __agglength > 0); _agglength = __agglength; assert(__numreal > 0); _numreal = __numreal; //_numdefaults = -1; BP = new bps*[numlinks]; ExpectedBP = new bps[numlinks]; blocked = new int**[numlinks]; } ~EdgeWeights() { delete[] realization; delete prob; delete ExpectedBP; delete[] det_flag; delete slicestart; delete[] numsupportpoints; delete[] probability; delete[] BP; delete[] blocked; } /* inline int Blocked(long linkIndex, int t, int r) { return blocked[linkIndex][t][r]; } inline void SetBlocked(long linkIndex, int t, int r, int state) { blocked[linkIndex][t][r] = state; } */ inline long find_interval(long startslice, float time) { long i; for (i = startslice; i < _numtimeslices - 1; i++) if (time >= slicestart[i] && time < slicestart[i + 1]) //left inclusive, right exclusive break; return i; } inline bp find_interval(bps *x, float time, int *i) //*i is the index of the right breaking point; prev is the left breaking point { bp prev; for (*i = 0; *i < (*x).size() && (*x)[*i].first < time; (*i)++); if (*i == 0) prev.first = -2; //ray to the left else if (*i == (*x).size()) { prev.first = -1; //ray to the right *i = *i - 1; } else prev = (*x)[*i - 1]; return prev; } inline float weight_link(long link, int time, Network *_N, bps *x) { float ratio, starttime, endtime; int i, start, end; bp start_bp, end_bp; assert(link >= 0 && link < _N->NumLinks()); start_bp = find_interval(x, time, &i); start = start_bp.first; starttime = start_bp.second; end_bp = (*x)[i]; end = end_bp.first; endtime = end_bp.second; if (start < 0) //static part return endtime; assert(time >= start && time <= end); ratio = (float)(time - start) / (end - start); return starttime * (1 - ratio) + endtime * ratio; } inline float weight(long source, long dest, long time, Network *_N, bps *x) { long link = _N->LinkIndex(source, dest); assert(link != -1 ); return weight_link(link, time, _N, x); } inline float weight_link(long link, int time, int r, Network *_N) { int links = _N->NumLinks(); assert(link >= 0 && links); return (realization[time * links + link][r]); } inline float weight(long source, long dest, long time, int r, Network *_N) { long link = _N->LinkIndex(source, dest); assert(link != -1); return weight_link(link, time, r, _N); } inline float weight_in(long dest, long i, long time, Network *_N, bps *x) { assert( i>=0 && i<_N->InDegree(dest) ); return weight_link( _N->LinkInIndex( dest, i ), time, _N, x); } inline float weight_out( long source, long i, long time, Network *_N, bps *x) { assert( i>=0 && i<_N->OutDegree(source) ); return weight_link( _N->LinkOutIndex( source, i ), time, _N, x); } inline long timehorizon( void ) { return _levels-1; } inline long levels( void ) { return _levels; } inline long numreal(void) { return _numreal; } inline long agglength(void) { return _agglength; } inline long numdefaults(void) { return _numdefaults; } inline long numtimeslices(void) { return _numtimeslices; } inline void setweight(long source, long dest, long level, long real, float weight, Network *_N ) { assert( level>=0 && level<_levels ); assert( _N->LinkIndex( source, dest ) != -1 ); assert(real >=0 && real<_numreal); //_minweight = (weight < _minweight) ? weight : _minweight; //_maxweight = (weight > _maxweight) ? weight : _maxweight; realization[level * _N->NumLinks() + _N->LinkIndex( source, dest )][real] = weight; } inline void setweight_link( long linkIndex, long level, long real, float weight , Network *_N) { assert( level>=0 && level<_levels ); assert( linkIndex>=0 && linkIndex<_N->NumLinks() ); assert(real >=0 && real<_numreal); //_minweight = (weight < _minweight) ? weight : _minweight; //_maxweight = (weight > _maxweight) ? weight : _maxweight; realization[level * _N->NumLinks() + linkIndex][real] = weight; } inline void setprob( long real, float probability) { assert(real >=0 && real<_numreal); assert( probability >0 && probability <= 1); prob[real] = probability; } inline void setlevels(long levels) { assert(levels > 0); _levels = levels; } inline void setagglength(long agglength) { assert(agglength > 0); _agglength = agglength; } inline void setnumreal(long numreal) { assert(numreal > 0); _numreal = numreal; } inline void setnumdefaults(long numdefaults) { assert(numdefaults > 0); _numdefaults = numdefaults; } inline void setnumslices(long numtimeslices) { assert(numtimeslices > 0); _numtimeslices = numtimeslices; } }; #endif
true
1a60928f1aa25602b1ef8bbd05293bf681d86d1a
C++
SeanWuLearner/leetcode_vsstudio
/LeetCode/LeetCode/Q0326_PowerOfThree.h
UTF-8
1,109
3.421875
3
[]
no_license
#pragma once #include "DebugUtils.h" #pragma region odinary solution //class Solution { //public: // bool isPowerOfThree(int n) { // if (n == 0) // return false; // // while (n != 1) // { // if (n % 3 != 0) // return false; // n /= 3; // } // return true; // } //}; #pragma endregion #pragma region genius modular method //class Solution { //public: // bool isPowerOfThree(int n) { // if (n <= 0) return false; // return 1162261467 % n == 0; //maxPowerOfThree = 1162261467 // } //}; #pragma endregion #pragma region cheating method #include <set> class Solution { public: bool isPowerOfThree(int n) { set<int> power{ 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441, 1594323, 4782969, 14348907, 43046721, 129140163, 387420489, 1162261467 }; return power.find(n) != power.end(); } }; #pragma endregion void Q0326_tester() { Solution s; cout << s.isPowerOfThree(27) << endl; // output: true cout << s.isPowerOfThree(0) << endl; // output: false cout << s.isPowerOfThree(9) << endl; // output: true cout << s.isPowerOfThree(45) << endl; // output: false }
true
d9a57a17669cb9bbcf6595427bef4b5a7220b4af
C++
nhayesroth/cs106b_4
/PriorityQueue/PriorityQueue/src/pqueue-heap.cpp
UTF-8
2,459
3.53125
4
[]
no_license
/************************************************************* * File: pqueue-heap.cpp * * Implementation file for the HeapPriorityQueue * class. */ #include "pqueue-heap.h" #include "error.h" #include <iostream> int DEFAULT_SIZE = 1; HeapPriorityQueue::HeapPriorityQueue() { logicalLength = 0; list = new string[DEFAULT_SIZE]; allocatedLength = DEFAULT_SIZE; } HeapPriorityQueue::~HeapPriorityQueue() { delete[] list; } int HeapPriorityQueue::size() { return logicalLength; } bool HeapPriorityQueue::isEmpty() { return (logicalLength==0); } void HeapPriorityQueue::grow() { /* Growing by a factor of two gives amortized O(1) push. */ allocatedLength *= 2; string* newList = new string[allocatedLength]; /* Copy over the old elements into the new array. */ for (int i = 0; i < logicalLength; i++) { newList[i] = list[i]; } /* Free memory for the old array. */ delete[] list; /* Change which array of elements we are now using. */ list = newList; } void HeapPriorityQueue::enqueue(string value) { /* double the list size when you're out of space */ if (logicalLength == allocatedLength) grow(); /* write to first open space */ list[size()] = value; logicalLength ++; /*bubble-up*/ //shift indexes to 1-indexed array int cIndex = size()-1; int pIndex = size()/2-1; //loop until parent/child are in lexicographical(sp?) order while (list[cIndex] < list[pIndex]){ string newChild = list[pIndex]; list[pIndex]=list[cIndex]; list[cIndex]=newChild; //move indexes up for next pair cIndex=pIndex; pIndex=(cIndex+1)/2-1; } } string HeapPriorityQueue::peek() { if (isEmpty()) error("Peeked at an empty queue"); else { return list[0]; } } string HeapPriorityQueue::dequeueMin() { //cache the string to return string toReturn = list[0]; //swap the first and last elements list[0] = list[size()-1]; logicalLength--; /*bubble down*/ //select indexes for parent and two children int parent=0; int fChild=parent*2+1; int sChild=fChild+1; //loop until both children come after the parent while (list[parent] < list[fChild] && list[parent] < list[sChild]){ //move down the lower side int smaller = fChild; if (list[sChild]<list[fChild]) smaller=sChild; //swap parent and child string newChild = list[parent]; list[parent]=list[smaller]; list[smaller]=newChild; //select new indexes parent=smaller; int fChild=parent*2+1; int sChild=fChild+1; } return toReturn; }
true
5b47bd89487941cc0ac5fbded52190c9fd9ff1ea
C++
KasperHdL/Auris-Game-Engine
/Auris/src/Auris/Systems/Input.cpp
UTF-8
5,166
2.859375
3
[]
no_license
#include "Auris/Systems/Input.hpp" #include <iostream> #include "Auris/Game.hpp" using namespace Auris; std::map<SDL_Scancode, bool> Input::heldKeys; //all held keys std::map<SDL_Scancode, bool> Input::downKeys; //all down keys std::map<SDL_Scancode, bool> Input::upKeys; //all up keys std::map<SDL_JoystickID,SDL_GameController*> Input::ctrl; //all controllers connected int Input::quit = 0; Game* Input::game; //quit event or not void Input::init(Game* game){ Input::game = game; } //This method clears all the keys that are currently stored, and then updates them to what ever keys are being manipulated this frame void Input::update() { downKeys.clear();//clear down keys upKeys.clear();//clear up keys SDL_Event e; //An SDL event to figure out which keys are being manipulated while (SDL_PollEvent(&e)) { //If there is an event ImGui_SRE_ProcessEvent(&e); switch (e.type){ case SDL_KEYDOWN: if (e.key.repeat == 0) { //if this key is not being held down keyDownEvent(e); //register the event } break; case SDL_KEYUP: keyUpEvent(e); //register the event break; case SDL_CONTROLLERDEVICEADDED: controllerAdded(e); break; case SDL_CONTROLLERBUTTONDOWN: initController(e); break; case SDL_CONTROLLERDEVICEREMOVED: controllerRemoved(e); break; case SDL_QUIT: quit = 1; break; default: break; } } } void Input::shutdown(){ heldKeys.clear(); downKeys.clear(); upKeys.clear(); // for(auto &c : ctrl){ // SDL_GameControllerClose(c); // } } //This method registers a keydown event, and therefore takes an SDL event as input, to figure out which key has been pressed void Input::keyDownEvent(const SDL_Event& event) { downKeys[event.key.keysym.scancode] = true; //Save the key in down keys heldKeys[event.key.keysym.scancode] = true; //Save the key in held keys } //This method registers a keyup event, and therefore takes and SDL event as input, to figure out which key has been released void Input::keyUpEvent(const SDL_Event& event) { heldKeys[event.key.keysym.scancode] = false; //Remove the key from held keys upKeys[event.key.keysym.scancode] = true; //Save the key in up keys } //This method returns true if the key being checked is currently being pressed down, otherwise false bool Input::keyDown(SDL_Scancode key) { return downKeys[key]; } //This method return true if the key being checked is currently being lifted up, otherwise false bool Input::keyUp(SDL_Scancode key) { return upKeys[key]; } //This method returns true if the key being checked is currently being held down, otherwise false bool Input::keyHeld(SDL_Scancode key) { return heldKeys[key]; } void Input::controllerAdded(const SDL_Event &event){ if (SDL_IsGameController(event.cdevice.which)) { //char *mapping; //SDL_Log("Index \'%i\' is a compatible controller, named \'%s\'", event.cdevice.which, SDL_GameControllerNameForIndex(event.cdevice.which)); SDL_GameController* temp = SDL_GameControllerOpen(event.cdevice.which); //mapping = SDL_GameControllerMapping(temp); //SDL_Log("Controller %i is mapped as \"%s\".", event.cdevice.which, mapping); //SDL_free(mapping); game->controllerConnected(); } } void Input::initController(const SDL_Event& event){ if (SDL_IsGameController(event.cbutton.which)) { if(!ctrl.count(event.cbutton.which)){ ctrl[event.cbutton.which]= SDL_GameControllerOpen(event.cdevice.which); //find the controller game->controllerActivated(event.cbutton.which); //send the id to the game } } } void Input::controllerRemoved(const SDL_Event& event){ if (SDL_IsGameController(event.cdevice.which)) { SDL_GameControllerClose(ctrl[event.cdevice.which]); std::map<SDL_JoystickID,SDL_GameController*>::iterator it; it=ctrl.find(event.cdevice.which); //find the controller ctrl.erase (it); //remove it game->controllerDisconnected(event.cdevice.which); //send the id of the removed controller to game } } glm::vec2 Input::getControllerLeftStickState(int controllerID){ return glm::vec2(SDL_GameControllerGetAxis(ctrl[controllerID],SDL_CONTROLLER_AXIS_LEFTX),SDL_GameControllerGetAxis(ctrl[controllerID],SDL_CONTROLLER_AXIS_LEFTY)); } glm::vec2 Input::getControllerRightStickState(int controllerID){ return glm::vec2(SDL_GameControllerGetAxis(ctrl[controllerID],SDL_CONTROLLER_AXIS_RIGHTX),SDL_GameControllerGetAxis(ctrl[controllerID],SDL_CONTROLLER_AXIS_RIGHTY)); } bool Input::getControllerButtonState(int controllerID, SDL_GameControllerButton button){ return (SDL_GameControllerGetButton(ctrl[controllerID],button) == 1); } int Input::getControllerAxisState(int controllerID, SDL_GameControllerAxis axis){ return SDL_GameControllerGetAxis(ctrl[controllerID],axis); }
true
70c8b3c09f722054867bdf7d823e2c1f302ca179
C++
JashDave/ReferenceCodes
/ModularArathimatic.cpp
UTF-8
1,656
3.40625
3
[]
no_license
#include<iostream> #include<vector> using namespace std; typedef unsigned long long ull; typedef long long ll; class ModularFactorial{ private: vector<ull> facttable; ull mod; public: ModularFactorial(ull size,ull m){ facttable.resize(size,0); facttable[0]=1; mod = m; } ull fact(int x){ if(facttable[x]!=0) return facttable[x]; facttable[x] = (fact(x-1)*x) % mod; return facttable[x]; } }; ull modularPower(ull n,ull p, ull m){ ull ret = 1; n = n % m; while (p > 0) { if (p & 1) { ret = (ret*n) % m; } p = p>>1; n = (n*n) % m; } return ret; } // Lucas' Theorem. // Eulars law for modular division class ModularCombination{ private: ModularFactorial *f; ull mod; ull n; bool del; public: ModularCombination(int n_,ull m, ModularFactorial *f_=NULL){ n = n_; mod = m; if(f_ == NULL){ f = new ModularFactorial(n,mod); del = true; } else { f = f_; del = false; } } ~ModularCombination(){ if(del){ delete(f); } } ull ncr(int r){ //Eulars law for modular division ull denom = (f->fact(n-r) * f->fact(r)) % mod; ull mdenom = modularPower(denom,mod-2,mod); // ull mdenom = modularPower(f->fact(r)*modularPower(f->fact(n-r),mod-2,mod)%mod,mod-2,mod)%mod; ull ret = (mdenom * f->fact(n)) % mod; // ull ret = f->fact(n) / denom; return ret; } }; int main(){ int n=5; ull mod = (ull)1e9+7; ModularFactorial mf(n,mod); for(int i=0;i<n;i++){ cout<<mf.fact(i)<<endl; } ModularCombination mc(n,mod); int x=1; while(x%(n+1)){ cout<<mc.ncr(x)<<endl; x++; } }
true
c4039b012c3c8a3ed53f2c8a6e9a71018a252a23
C++
GrzegorzNieuzyla/Advent-of-Code-2018
/day05/solution.cpp
UTF-8
1,156
3.484375
3
[]
no_license
#include <iostream> #include <list> #include <cstdlib> #include <climits> // Calculates size after reaction // can also specify letter (uppercase) to exclude from reaction int reaction(std::list<char> string, char c = 0){ if(c != 0){ string.remove(c); string.remove(c + 32); } for(auto it = string.begin(); it != string.end();){ auto next = it; ++next; if(next == string.end()) break; if(abs(*next - *it) == 32){ string.erase(it); auto after = string.erase(next); if(after != string.begin()) --after; it = after; }else{ ++it; } } return string.size(); } int main() { std::list<char> string; char c; while(std::cin >> c){ string.push_back(c); } std::cout << "Size: " << reaction(string) << std::endl; // part 2 auto min = INT64_MAX; for(char c = 'A'; c <= 'Z'; c++){ int current = reaction(string, c); if(current < min) min = current; } std::cout << "Best: " << min << std::endl; return 0; }
true