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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
11dcc70af78e61d1ac8944c1fbc63e6e0bdb8acb | C++ | csorbakristof/alkalmazasfejlesztes | /QtCpp/SignalsAndSlots/Simulator.h | UTF-8 | 499 | 2.53125 | 3 | [] | no_license | #pragma once
#ifndef SIMULATOR_H
#define SIMULATOR_H
#include <QObject>
/** Egy járművet szimulál, ami halad adott sebességgel. */
class Simulator : public QObject
{
Q_OBJECT
public:
Simulator(int velocity);
~Simulator() = default;
signals:
/** Jelzi, hogy megérkeztünk egy szép helyre. */
void arrived(int where);
public slots:
/** Telik az idő... */
void tick();
private:
int x; /** pozíció */
int v; /** sebesség */
};
#endif // SIMULATOR_H
| true |
92821c7ae8c6af40ae86ff01e9728d9fa7c7d2f6 | C++ | alexgeorge50/Smart-Park | /parking_practice_original.ino | UTF-8 | 2,998 | 2.59375 | 3 | [] | no_license | #include <Ethernet.h>
#include <SPI.h>
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
//Arduino IP
IPAddress ip(192, 168, 1, 10);
const int bufferLen = 200;
//Digital Pin 3
int sensorPin = 3;
int currentValue = 0;
int triggerMode = 1 ;
byte waitingMode = 0;
byte debugMode = 0;
char server[] = "77.104.168.74"; //server address is here
EthernetClient client;
void setup() {
// put your setup code here, to run once:
// Serial.begin starts the serial connection between computer and Arduino
Serial.begin(9600);
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
} else if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// no point in carrying on, so do nothing forevermore:
while (true) {
delay(1);
}
}
// start the Ethernet connection and the server:
//Ethernet.begin(mac); //unocmment this line for DHCP
Serial.println("Starting...");
Serial.println(Ethernet.localIP());
pinMode(sensorPin, INPUT);
}
void loop() {
if (waitingMode) {
receiveData();
} else {
sendData();
}
}
void receiveData() {
int len = client.available();
if (len > 0) {
byte buffer[bufferLen];
if (len > bufferLen) len = bufferLen;
client.read(buffer, len);
if (debugMode) {
Serial.println();
Serial.println();
Serial.write(buffer, len); // show in the serial monitor (slows some boards)
Serial.println();
Serial.println();
}
waitingMode = 0;
client.stop(); // Closing connection to server
//delay(10000);
Serial.println("Sensor is Ready for next trigger!");
}
}
void sendData() {
int sensorValue = digitalRead(sensorPin);
if (currentValue == sensorValue) {
return;
}
currentValue = sensorValue;
if (sensorValue == 0) {
return;
}
if (triggerMode == 1 )
{
triggerMode = 0;
} else {
triggerMode = 1;
}
if (client.connect(server, 80)) {
client.print("GET /admin_dashboard/write_data.php?value="); // This
client.print(triggerMode);
client.println(" HTTP/1.1"); // Part of the GET request
client.println("Host: www.smartp.ictatjcub.com"); // webserver Host
client.println("Connection: close");
client.println(); // Empty line
client.println(); // Empty line
Serial.print("Sensor value has been sent to server :" );
Serial.println(triggerMode); // Part of the GET request
waitingMode = 1 ; // waiting for webserver
}
else {
// If Arduino can't connect to the server (your computer or web page)
Serial.println("--> connection failed\n");
}
}
| true |
a446f6260a7ac54705ed1b8455b93f243a3078c2 | C++ | A-M-GR/Book_Class | /Book.h | UTF-8 | 1,246 | 3.03125 | 3 | [] | no_license |
//test
#include <string>
#include <vector>
#include <iostream>
using std::string;
using std::vector;
using std::cin;
using std::cout;
using namespace std;
class Book
{
public:
Book();
enum Genre{
fiction = 1,nonficion,periodical,biography,children
};
void set_ISBN(string ISBN);
void set_title(string title);
void set_author(string author);
void set_copyright_date(string copyright_date);
void set_checked_out(int checked_out);
bool operator == (Book b1);
bool operator !=(Book b1);
string get_ISBN()
{
return ISBN;
}
string get_title()
{
return title;
}
string get_author()
{
return author;
}
string get_copyright_date()
{
return copyright_date;
}
int get_checked_out()
{
return checked_out;
}
void set_Genre(int number);
Genre get_Genre(void)
{
return g1;
}
protected:
private:
string ISBN;
string title;
string author;
string copyright_date;
int checked_out = 0;
Genre g1 = fiction;
};
| true |
2e9b0a51af9dd12b1a22a203d5db472a80cb6e05 | C++ | simsa-st/contest24 | /c24/communication/status.cpp | UTF-8 | 1,872 | 3.09375 | 3 | [
"Zlib",
"MIT"
] | permissive | #include "c24/communication/status.h"
namespace c24 {
namespace communication {
Status::Status()
: socket_status(sf::Socket::Done), error_code(0), error_mask(0) {}
Status::Status(sf::Socket::Status _socket_status) : Status() {
SetSocketError(_socket_status);
}
Status::Status(int _error_code, const std::string& _error_message) : Status() {
SetServerError(_error_code, _error_message);
}
bool Status::Ok() const { return error_mask == 0; }
bool Status::ErrorOccurred(ErrorType error_type) const {
if (error_type == ErrorType::NONE) return error_mask == 0;
return error_mask & (1 << error_type);
}
void Status::SetSocketError(sf::Socket::Status _socket_status) {
if (_socket_status != sf::Socket::Done) {
error_mask |= 1 << ErrorType::SOCKET;
socket_status = _socket_status;
}
}
void Status::SetServerError(int _error_code, const std::string& _error_message) {
if (_error_code != 0) {
error_mask |= 1 << ErrorType::SERVER;
error_code = _error_code;
error_message = _error_message;
}
}
void Status::SetNoDataReceivedError() {
error_mask |= 1 << ErrorType::NO_DATA_RECEIVED;
}
std::string Status::Print() const {
std::string str = "Status<";
if (ErrorOccurred(ErrorType::NONE)) {
str += "OK";
} else {
str += "ERROR:";
if (ErrorOccurred(ErrorType::SOCKET)) {
str += " [in socket: " + std::to_string(socket_status) + "]";
}
if (ErrorOccurred(ErrorType::SERVER)) {
str += " [server error code: " + std::to_string(error_code) +
", message: " + error_message + "]";
}
if (ErrorOccurred(ErrorType::NO_DATA_RECEIVED)) {
str += " [no data received in blocking mode]";
}
}
str.push_back('>');
return str;
}
std::ostream& operator<<(std::ostream& out, const Status& status) {
return out << status.Print();
}
} // namespace communication
} // namespace c24
| true |
d278652d966566f888125caf9e304b9f53759c84 | C++ | gjkennedy/tacs | /src/bpmat/KSM.h | UTF-8 | 16,121 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | /*
This file is part of TACS: The Toolkit for the Analysis of Composite
Structures, a parallel finite-element code for structural and
multidisciplinary design optimization.
Copyright (C) 2010 University of Toronto
Copyright (C) 2012 University of Michigan
Copyright (C) 2014 Georgia Tech Research Corporation
Additional copyright (C) 2010 Graeme J. Kennedy and Joaquim
R.R.A. Martins All rights reserved.
TACS is licensed under the Apache License, Version 2.0 (the
"License"); you may not use this software except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef TACS_KSM_H
#define TACS_KSM_H
/*
Solve linear systems using Krylov-subspace methods
*/
#include <math.h>
#include "TACSObject.h"
/*
The following enumeration defines whether the matrix is either the
normal or the transpose orientation.
*/
enum MatrixOrientation { TACS_MAT_NORMAL, TACS_MAT_TRANSPOSE };
/*
Define boundary conditions that are applied after all the
matrix/vector values have been set.
BCMap should only be instantiated once for a given analysis. All
other classes in this file should point that instance.
*/
class TACSBcMap : public TACSObject {
public:
TACSBcMap(int bsize, int num_bcs);
~TACSBcMap();
// Add/get the boundary conditions stored in this object
// -----------------------------------------------------
void addBC(int node, int nvals, const int *bc_nums = NULL,
const TacsScalar *bc_vals = NULL);
int getBCs(const int **_nodes, const int **_vars, TacsScalar **_values);
// Get the node numbers associated with the BCs for reordering
// -----------------------------------------------------------
int getBCNodeNums(int **_nodes);
// Add the boundary condition using the binary flags directly
// ----------------------------------------------------------
void addBinaryFlagBC(int node, int _vars);
private:
// Set the block size
int bsize;
// Information used to apply boundary conditions
int *nodes;
// The total number of boundary conditions
int nbcs;
// The local index of the unknowns and the values
int *vars;
TacsScalar *values;
// Set the boundary condition sizes
int max_size;
int bc_increment;
};
/*!
The abstract vector class.
All TACS KSM objects use this interface for matrix-vector products
and preconditioning operations. In practice, within TACS itself,
most of the matricies require the BVec base class. However, when
coupling to other disciplines it is frequently convenient to define
a hybrid vector consisting of multiple components. In these cases,
it is handy to have a base vector class.
*/
class TACSVec : public TACSObject {
public:
virtual ~TACSVec() {}
// Functions required for Krylov methods
// -------------------------------------
virtual TacsScalar norm() = 0; // Compute the Cartesian 2 norm
virtual void scale(TacsScalar alpha) = 0; // Scale the vector by a value
virtual TacsScalar dot(TACSVec *x) = 0; // Compute x^{T} * y
virtual void mdot(TACSVec **x, TacsScalar *ans,
int m); // Multiple dot product
virtual void axpy(TacsScalar alpha, TACSVec *x) = 0; // y <- y + alpha * x
virtual void copyValues(TACSVec *x) = 0; // Copy values from x to this
virtual void axpby(TacsScalar alpha, TacsScalar beta,
TACSVec *x) = 0; // Compute y <- alpha * x + beta * y
virtual void zeroEntries() = 0; // Zero all the entries
// Additional useful member functions
// ----------------------------------
virtual void setRand(double lower = -1.0, double upper = 1.0) {}
virtual void applyBCs(TACSBcMap *map, TACSVec *vec = NULL) {}
virtual void setBCs(TACSBcMap *map) {}
};
/*!
The abstract matrix base class for all TACS matrices. All of
these operations must be defined to be utilized by TACSAssembler.
zeroEntries(): Zeros the values of all entries in the matrix.
addValues(): Adds a small, dense matrix to the rows set in row[] and
the columns set in col[].
applyBCs(): Applies the Dirichlet boundary conditions to the matrix
by settin the associated diagonal elements to 1.
beginAssembly()/endAssembly(): Begin/end the parallel assembly of
the matrix.
getSize(): Return the number of rows and number of columns in the
matrix.
createVec(): Return a vector for output from the matrix - typically
only used when the matrix is square.
mult(x, y): Perform the matrix multiplication y = A*x
copyValues(): Copy the values from the matrix mat to this matrix.
scale(alpha): Scale all entries in the matrix by alpha.
axpy(alpha, mat): Compute this = this + alpha*mat - only works on
the same matrix types.
*/
class TACSMat : public TACSObject {
public:
virtual ~TACSMat() {}
// Operations for assembly/setting values
// --------------------------------------
virtual void zeroEntries() {}
virtual void addValues(int nrow, const int *row, int ncol, const int *col,
int nv, int mv, const TacsScalar *values) {}
virtual void addWeightValues(int nvars, const int *varp, const int *vars,
const TacsScalar *weights, int nv, int mv,
const TacsScalar *values,
MatrixOrientation matOr = TACS_MAT_NORMAL) {}
virtual void applyBCs(TACSBcMap *bcmap) {}
virtual void applyTransposeBCs(TACSBcMap *bcmap) {}
virtual void beginAssembly() {}
virtual void endAssembly() {}
// Create a duplicate with the same non-zero pattern. Values are not copied
// ------------------------------------------------------------------------
virtual TACSMat *createDuplicate() { return NULL; }
// Create vectors/retrieve sizes
// -----------------------------
virtual void getSize(int *_nr, int *_nc) {}
virtual TACSVec *createVec() = 0;
// Operations required for solving problems
// ----------------------------------------
virtual void mult(TACSVec *x, TACSVec *y) = 0;
virtual void multTranspose(TACSVec *x, TACSVec *y) {}
virtual void copyValues(TACSMat *mat) {}
virtual void scale(TacsScalar alpha) {}
virtual void axpy(TacsScalar alpha, TACSMat *mat) {}
virtual void addDiag(TacsScalar alpha) {}
// Return the name of the object
// -----------------------------
const char *getObjectName();
private:
static const char *matName;
};
/*!
The abstract pre-conditioner class
applyFactor(): Compute y = M^{-1}x, where M^{-1} is the
preconditioner.
factor(): Factor the preconditioner based on values in the matrix
associated with the preconditioner
*/
class TACSPc : public TACSObject {
public:
virtual ~TACSPc() {}
// Apply the preconditioner to x, to produce y
// -------------------------------------------
virtual void applyFactor(TACSVec *x, TACSVec *y) = 0;
// Factor (or set up) the preconditioner
// -------------------------------------
virtual void factor() = 0;
// Get the matrix associated with the preconditioner itself
virtual void getMat(TACSMat **_mat) { *_mat = NULL; }
// Retrieve the object name
// ------------------------
const char *getObjectName();
private:
static const char *pcName;
};
/*!
The abstract residual history class
Monitor the residual or other interesting quantity and print out the
result to the screen or file.
*/
class KSMPrint : public TACSObject {
public:
virtual ~KSMPrint() {}
virtual void printResidual(int iter, TacsScalar res) = 0;
virtual void print(const char *cstr) = 0;
const char *getObjectName();
private:
static const char *printName;
};
/*!
The abstract Krylov-subspace method class
Solve the linear system A*x = b with a Krylov subspace method,
possibly using some preconditioner.
createVec(): Create a vector for the matrix
setOperations(): Set the matrix (required) and the preconditioner
(optional)
getOperators(): Get the matrix and the preconditioner
solve(): Solve the linear system to the specified tolerance using
the Krylov subspace method.
setTolerances(rtol, atol): Set the relative and absolute stopping
tolerances for the method
setMonitor(): Set the monitor - possibly NULL - that will be used
getIterCount(): Return the number of iterations taken during the last solve
getResidualNorm(): Return the residual norm from the end of the last solve
*/
class TACSKsm : public TACSObject {
public:
TACSKsm() : iterCount(0), resNorm(0.0) {}
virtual ~TACSKsm() {}
virtual TACSVec *createVec() = 0;
virtual void setOperators(TACSMat *_mat, TACSPc *_pc) = 0;
virtual void getOperators(TACSMat **_mat, TACSPc **_pc) = 0;
virtual int solve(TACSVec *b, TACSVec *x, int zero_guess = 1) = 0;
virtual void setTolerances(double _rtol, double _atol) = 0;
virtual void setMonitor(KSMPrint *_monitor) = 0;
virtual int getIterCount() { return iterCount; }
virtual TacsScalar getResidualNorm() { return resNorm; }
const char *getObjectName();
private:
static const char *ksmName;
protected:
int iterCount; ///< Number of iterations taken during the last solve
TacsScalar resNorm; ///< The residual norm at the end of the last solve
};
/*
The following classes define a consistent way to write
residual histories to a file/to stdout
*/
class KSMPrintStdout : public KSMPrint {
public:
KSMPrintStdout(const char *_descript, int _rank, int _freq);
~KSMPrintStdout();
void printResidual(int iter, TacsScalar res);
void print(const char *cstr);
private:
char *descript;
int rank;
int freq;
};
/*
Write out the print statements to a file
*/
class KSMPrintFile : public KSMPrint {
public:
KSMPrintFile(const char *filename, const char *_descript, int _rank,
int _freq);
~KSMPrintFile();
void printResidual(int iter, TacsScalar res);
void print(const char *cstr);
private:
FILE *fp;
char *descript;
int rank;
int freq;
};
/*!
Pre-conditioned conjugate gradient method
*/
class PCG : public TACSKsm {
public:
PCG(TACSMat *_mat, TACSPc *_pc, int reset, int _nouter);
~PCG();
TACSVec *createVec() { return mat->createVec(); }
int solve(TACSVec *b, TACSVec *x, int zero_guess = 1);
void setOperators(TACSMat *_mat, TACSPc *_pc);
void getOperators(TACSMat **_mat, TACSPc **_pc);
void setTolerances(double _rtol, double _atol);
void setMonitor(KSMPrint *_print);
private:
// Operators in the KSM method
TACSMat *mat;
TACSPc *pc;
// The relative/absolute tolerances
double rtol, atol;
// Reset parameters
int nouter, reset;
// Vectors required for the solution method
TACSVec *work;
TACSVec *R;
TACSVec *P;
TACSVec *Z;
KSMPrint *monitor;
};
/*!
Right-preconditioned GMRES
This class handles both right-preconditioned GMRES and the flexible
variant of GMRES. Either the classical or modified Gram Schmidt
orthogonalization algorithm may be used. Modified Gram Schmidt has
better numerical stability properties, but requires more
communication overhead. Modified Gram Schmidt is the default.
The input parameters are:
-------------------------
mat: the matrix handle
pc: (optional - but highly recommended!) the preconditioner
m: the size of the Krylov-subspace to use before restarting
nrestart: the number of restarts to use nrestart = 0 results in
isflexible: flag to indicate whether to use a flexible variant of
GMRES or not
Notes:
------
- The preconditioner is used as is without any additional
calls. Ensure that it is properly factored by calling pc->factor().
- When calling solve, set zero_guess = 0 (False) to use the values
in 'x' as the initial guess.
- You can change the matrix and preconditioner operators by making
calls to setOperators - this is useful if you want to re-use the
vectors in the Krylov subspace, but have two different problems.
*/
class GMRES : public TACSKsm {
public:
enum OrthoType { CLASSICAL_GRAM_SCHMIDT, MODIFIED_GRAM_SCHMIDT };
GMRES(TACSMat *_mat, TACSPc *_pc, int _m, int _nrestart, int _isFlexible);
GMRES(TACSMat *_mat, int _m, int _nrestart);
~GMRES();
TACSVec *createVec() { return mat->createVec(); }
int solve(TACSVec *b, TACSVec *x, int zero_guess = 1);
void setOperators(TACSMat *_mat, TACSPc *_pc);
void getOperators(TACSMat **_mat, TACSPc **_pc);
void setTolerances(double _rtol, double _atol);
void setMonitor(KSMPrint *_monitor);
void setOrthoType(enum OrthoType otype);
void setTimeMonitor();
const char *getObjectName();
private:
// Initialize the class
void init(TACSMat *_mat, TACSPc *_pc, int _m, int _nrestart, int _isFlexible);
// Orthogonalize a vector against a set of vectors
void (*orthogonalize)(TacsScalar *, TACSVec *, TACSVec **, int);
TACSMat *mat;
TACSPc *pc;
int msub;
int nrestart;
int isFlexible;
TACSVec **W; // The Arnoldi vectors that span the Krylov subspace
TACSVec **Z; // An additional flexible subspace of vectors
TACSVec *work; // A work vector
int *Hptr; // Array to make accessing the elements of the matrix easier!
TacsScalar *H; // The Hessenberg matrix
double rtol;
double atol;
TacsScalar *Qsin;
TacsScalar *Qcos;
TacsScalar *res;
int monitor_time;
KSMPrint *monitor;
static const char *gmresName;
};
/*!
A simplified and flexible variant of GCROT - from Hicken and Zingg
This is a simplified and flexible variant of the GCROT algorithm
suggested by Hicken and Zingg. This Krylov subspace method - GCR
with outer truncation - has better restart properties than F/GMRES.
The input parameters are:
mat: The matrix operator
pc: The preconditioner (optional but recommended)
outer: The number of outer subspace vectors to use
max_outer >= outer: The maximum number of outer iterations
msub: The size of the GMRES subspace to use
isflexible: Parameter to indicate whether to use a flexible variant
*/
class GCROT : public TACSKsm {
public:
GCROT(TACSMat *_mat, TACSPc *_pc, int _outer, int _max_outer, int _msub,
int _isFlexible);
GCROT(TACSMat *_mat, int _outer, int _max_outer, int _msub);
~GCROT();
TACSVec *createVec() { return mat->createVec(); }
int solve(TACSVec *b, TACSVec *x, int zero_guess = 1);
void setOperators(TACSMat *_mat, TACSPc *_pc);
void getOperators(TACSMat **_mat, TACSPc **_pc);
void setTolerances(double _rtol, double _atol);
void setMonitor(KSMPrint *_monitor);
const char *getObjectName();
private:
void init(TACSMat *_mat, TACSPc *_pc, int _outer, int _max_outer, int _msub,
int _isFlexible);
TACSMat *mat;
TACSPc *pc;
int msub; // Size of the GMRES subspace
int outer, max_outer; // Number of outer vectors
int isFlexible;
TACSVec **W; // The Arnoldi vectors that span the Krylov subspace
TACSVec **Z; // Additional subspace of vectors - for the flexible variant
TACSVec **U, **C; // The subspaces for the outer GCR iterations
TACSVec *u_hat, *c_hat, *R;
int *Hptr; // Array to make accessing the elements of the matrix easier!
TacsScalar *H; // The Hessenberg matrix
TacsScalar *B; // The matrix that stores C^{T}*A*W
double rtol;
double atol;
TacsScalar *Qsin;
TacsScalar *Qcos;
TacsScalar *res;
KSMPrint *monitor;
static const char *gcrotName;
};
/*
Create a Krylov-subspace class that is just a preconditioner.
This is used in cases where a preconditioner may consist of an
internal subspace method. In these cases, it is sometimes useful to
have a KSM class that just applies the preconditioner itself. This
class fills this role.
*/
class KsmPreconditioner : public TACSKsm {
public:
KsmPreconditioner(TACSMat *_mat, TACSPc *_pc);
~KsmPreconditioner();
TACSVec *createVec();
void setOperators(TACSMat *_mat, TACSPc *_pc);
void getOperators(TACSMat **_mat, TACSPc **_pc);
int solve(TACSVec *b, TACSVec *x, int zero_guess = 1);
void setTolerances(double _rtol, double _atol);
void setMonitor(KSMPrint *_monitor);
private:
TACSMat *mat;
TACSPc *pc;
};
#endif // TACS_KSM_H
| true |
b68e2e4825611de5ed0e4cb4bc088f478ae3339e | C++ | skywhat/leetcode | /Cpp/113.cpp | UTF-8 | 763 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include "Tree.h"
using namespace std;
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> res;
vector<int> temp;
path(root,res,temp,sum);
return res;
}
void path(TreeNode* root,vector<vector<int>>& res,vector<int>& temp,int sum){
if(root){
temp.push_back(root->val);
sum-=root->val;
if(!root->left&&!root->right){
if(sum==0)
res.push_back(temp);
}
else{
path(root->left,res,temp,sum);
path(root->right,res,temp,sum);
}
temp.pop_back();
}
}
};
int main(){
}
| true |
1bf20ac2ff54cdc6e0537351b8c0939fa5251eaa | C++ | tiwason/practice | /strings/subsequence/longestPlainSubseq.cpp | UTF-8 | 720 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
int longestPalindrome(string s)
{
int len = s.size();
int dp[len][len] = {0};
for (int i = 0; i < len; i++)
dp[i][i] = 1;
for (int cl = 2; cl <= len; cl++)
{
for (int i = 0; i < len - cl + 1; i++)
{
int j = i + cl - 1;
if (s[i] == s[j] && cl == 2)
dp[i][j] = 2;
else if (s[i] == s[j])
dp[i][j] = 2 + dp[i + 1][j - 1];
else
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
return dp[0][len - 1];
}
int main()
{
string s = "geeksforgeeks";
cout << longestPalindrome(s) << endl;
return 0;
} | true |
a4c481c3d8d424f4dd7766da00dd489ec6459651 | C++ | martinengstrom/MapMaker | /test/linux.cpp | UTF-8 | 1,771 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | /*
Test the linux library
*/
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <iostream>
#include <cstring>
using namespace std;
void *handle;
typedef int (*RVExtension_fnc_ptr)(char*, int, const char*);
int (*RVExtension)(char *, int, const char*);
/*
-----------------------------------------------------------------------------------------------------
*/
string execute(string command) {
char *output = new char[4096];
char *function = new char[2048];
snprintf(function, 2048, command.c_str());
RVExtension(output, 4096, function);
string result(output);
delete[] output;
delete[] function;
return result;
}
int load(string filename) {
char *error;
handle = dlopen (filename.c_str(), RTLD_LAZY);
if (!handle) {
//fputs (dlerror(), stderr);
return 1;
}
RVExtension = (RVExtension_fnc_ptr)dlsym(handle, "RVExtension");
if ((error = dlerror()) != NULL) {
//fputs(error, stderr);
return 1;
}
return 0;
}
/*
-----------------------------------------------------------------------------------------------------
*/
int main( int argc, const char* argv[] ) {
if (load("./mapmaker.so") > 0)
if (load("../mapmaker.so") > 0) {
cout << "Unable to properly load mapmaker.so" << endl;
exit(1);
}
cout << "Library invoked on " << execute("datetime") << endl << endl;
if (argc > 1) {
char command[1024] = "";
strcat(command, "openRead;");
strcat(command, argv[1]);
execute(command);
string result = execute("read");
while (result != "[]") {
cout << result << endl;
result = execute("read");
}
} else {
string command;
cout << "> ";
getline(cin, command);
while (!command.empty()) {
cout << execute(command) << endl;
cout << "> ";
getline(cin, command);
}
}
return 0;
} | true |
0379935c9ad7dce895cd281672029975d42937e9 | C++ | jijiji-onaka/42Cpp | /cpp04/ex03/Ice.cpp | UTF-8 | 1,569 | 2.640625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Ice.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tjinichi <tjinichi@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/06/29 07:26:41 by tjinichi #+# #+# */
/* Updated: 2021/06/29 09:13:53 by tjinichi ### ########.fr */
/* */
/* ************************************************************************** */
#include "Ice.hpp"
Ice::Ice(void) : AMateria("ice")
{
}
Ice::~Ice(void)
{
}
Ice::Ice(Ice const &other) : AMateria("ice")
{
*this = other;
}
Ice &Ice::operator=(Ice const &other)
{
if (this != &other)
{
this->_xp = other._xp;
}
return (*this);
}
AMateria *Ice::clone(void) const
{
AMateria *res;
try
{
res = new Ice(*this);
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
std::exit(EXIT_FAILURE);
}
return (res);
}
// "* shoots an ice bolt at NAME *"
void Ice::use(ICharacter& target)
{
this->AMateria::use(target);
std::cerr << ORANGE""BOLD;
std::cout << "* shoots an ice bolt at " << target.getName() << " *" << std::endl;
std::cerr << RESET;
}
| true |
0eb81d207666dc6e05bed90ad49f22b63edcb89f | C++ | ExcaliburEX/My-oj | /摆动序列3.27.cpp | UTF-8 | 610 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
using namespace std;
int a[25],ans,n;
int visit[25];
int Iscan(int num,int k){
if(k==1||k==2)return 1;
if(a[k-1]<a[k-2]&&num>a[k-2])return 1;
if(a[k-1]>a[k-2]&&num<a[k-2])return 1;
return 0;
}
void dfs(int cur){
if(cur>n)return ;
for(int i=1;i<=n;i++){
if(!visit[i]&&Iscan(i,cur)){
visit[i]=1;
a[cur]=i;
if(cur>=2){
ans++;
for(int i=1;i<=cur;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
dfs(cur+1);
visit[i]=0;
}
}
}
int main(){
cin>>n;
dfs(1);
cout<<ans<<endl;
return 0;
}
| true |
15c8f8ed6fab8c1226920c70a51daaafd3215197 | C++ | De-Fau-Lt/Solutions | /yet_another_bookshelf.cpp | UTF-8 | 408 | 2.5625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
bool in = false;
int c=0;
int arr[n];
for(auto &x:arr)
scanf("%d",&x);
int j=n-1;
while(arr[j]!=1)
j--;
for(int i=0;i<j;i++)
{
if(in)
{
if(arr[i]==0)
c++;
}
if(arr[i]==1)
in = true;
}
printf("%d\n",c);
}
return 0;
}
| true |
5583585c964620d68bd3d06b69d6ddf9ec123498 | C++ | halla-online/analyzer | /src/THaCluster.h | UTF-8 | 1,313 | 2.546875 | 3 | [] | no_license | #ifndef ROOT_THaCluster
#define ROOT_THaCluster
///////////////////////////////////////////////////////////////////////////////
// //
// THaCluster //
// //
///////////////////////////////////////////////////////////////////////////////
#include "TObject.h"
#include "TVector3.h"
class THaCluster : public TObject {
public:
THaCluster() {}
THaCluster( const THaCluster& rhs ) : TObject(rhs), fCenter(rhs.fCenter) {}
THaCluster& operator=( const THaCluster& );
virtual ~THaCluster() {}
TVector3& GetCenter() { return fCenter; }
virtual void SetCenter( Double_t x, Double_t y, Double_t z )
{ fCenter.SetXYZ(x,y,z); }
virtual void SetCenter( const TVector3& vec3 )
{ fCenter = vec3; }
// TObject functions redefined
virtual void Clear( Option_t* opt="" );
virtual void Print( Option_t* opt="" ) const;
protected:
TVector3 fCenter; // Center coordinates of cluster
ClassDef(THaCluster,0) // Generic wire chamber cluster
};
//////////////////////////////////////////////////////////////////////////////
#endif
| true |
85efe7ea0e441a1c7bcfbca821dfa96beefc13ac | C++ | zinsmatt/Programming | /LeetCode/easy/Shortest_Distance_to_a_Character.cxx | UTF-8 | 498 | 2.84375 | 3 | [] | no_license | class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> pos;
for (int i = 0; i < S.size(); ++i)
{
if (S[i] == C)
pos.push_back(i);
}
vector<int> res;
for (int i = 0; i < S.size(); ++i)
{
int v = S.size();
for (auto p : pos)
{
v = min(v, abs(p-i));
}
res.push_back(v);
}
return res;
}
}; | true |
a3246920cfcf77a2ac22172e7a04228b39a75893 | C++ | amanjaingc/PLACEMENT | /heap.cpp | UTF-8 | 1,702 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int size = 0,a[10001];
void insert(int a[],int val)
{
size++;
a[size] = val;
int parent = size/2;
int self = size;
while(parent)
{
if(a[self]<a[parent])
{
int t = a[parent];
a[parent] = a[self];
a[self] = t;
self = parent;
parent/=2;
}
else
break;
}
return;
}
int extract_min(int a[])
{
if(size==0) return -1;
int ret = a[1];
a[1] = a[size];
size--;
int i=1;
while(i<size)
{
if((2*i + 1)<=size)
{
if(a[i]<min(a[2*i],a[2*i + 1]))
break;
else
{
if(a[2*i]==min(a[2*i],a[2*i + 1]))
{
int t = a[i];
a[i] = a[2*i];
a[2*i] = t;
i = 2*i;
}
else if(a[2*i + 1]==min(a[2*i],a[2*i + 1]))
{
int t = a[i];
a[i] = a[2*i + 1];
a[2*i + 1] = t;
i = 2*i + 1;
}
}
}
else if((2*i)==size)
{
if(a[i]>a[2*i])
{
int t = a[i];
a[i] = a[2*i];
a[2*i] = t;
}
break;
}
else if(2*i > size)
{
break;
}
}
return (ret);
}
int main()
{
insert(a,4);insert(a,7);insert(a,1);insert(a,12);insert(a,5);insert(a,9);
while(size)
cout<<extract_min(a)<<endl;
return 0;
}
| true |
24b43f933b6c9e550cf7768698cea87d84a38acb | C++ | arthurpd/icpc-notebook | /misc/mos/applications/86D.cpp | UTF-8 | 729 | 2.609375 | 3 | [] | no_license | // https://codeforces.com/contest/86/problem/D
#include "../mos.cpp"
#define MAXN 212345
int a[MAXN];
ll ans[MAXN];
ll val = 0;
int freq[1123456];
ll calc(int x)
{
return freq[x] * 1ll * freq[x] * 1ll * x;
}
void add(int i)
{
val += (long long)(2 * freq[a[i]] + 1) * a[i];
freq[a[i]]++;
}
void remove(int i)
{
val -= (long long)(2 * freq[a[i]] - 1) * a[i];
freq[a[i]]--;
}
void output(int i)
{
ans[i] = val;
}
int main(void)
{
int n, m;
scanf("%d %d", &n, &m);
vector<query> q(m);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 0; i < m; i++)
{
scanf("%d %d", &q[i].l, &q[i].r);
q[i].id = i;
}
mos(n, q, add, remove, output);
for (int i = 0; i < m; i++)
printf("%lld\n", ans[i]);
}
| true |
8c05953493dbdf3803ad629341c6d92938f9577d | C++ | imclab/tensorheaven | /tensorhell/taylor_polynomial.cpp | UTF-8 | 67,676 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>
#include "tenh/implementation/identity.hpp"
#include "tenh/implementation/innerproduct.hpp"
#include "tenh/implementation/vector.hpp"
#include "tenh/implementation/vee.hpp"
#include "tenh/interop/eigen.hpp"
#include "tenh/expressiontemplate_eval.hpp"
#include "tenh/utility/optimization.hpp"
using namespace Tenh;
#if 0
// ///////////////////////////////////////////////////////////////////////////
// norm and squared norm functions, which require an inner product to use
// ///////////////////////////////////////////////////////////////////////////
// this is sort of hacky -- it would probably be better to make an
// InnerProductSpace_c conceptual type and make ImplementationOf_t aware
// of it.
// NOTE: this won't work for complex types
template <typename InnerProductId_,
typename Derived_,
typename Scalar_,
typename BasedVectorSpace_,
ComponentQualifier COMPONENT_QUALIFIER_>
Scalar_ squared_norm (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &v)
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
typename InnerProduct_f<BasedVectorSpace_,InnerProductId_,Scalar_>::T inner_product;
return inner_product(v, v);//inner_product.split(i*j)*v(i)*v(j); // doesn't take advantage of symmetry
}
// NOTE: this won't work for complex types
template <typename InnerProductId_,
typename Derived_,
typename Scalar_,
typename BasedVectorSpace_,
ComponentQualifier COMPONENT_QUALIFIER_>
typename AssociatedFloatingPointType_t<Scalar_>::T
norm (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &v)
{
return std::sqrt(squared_norm<InnerProductId_>(v));
}
// ///////////////////////////////////////////////////////////////////////////
/*
design goals
------------
- given a function and a gradient, verify that the gradient is the gradient for the function
via numerical estimation -- using asymptotic bounds
- given a function and a gradient and a hessian, verify that the gradient and hessian are
actually the ones for that function, analogous to previous method.
- implement Newton's method
- implement conjugate gradient method
- implement gradient descent
- implement adaptive thingy (Newton's method, congjugate gradient method, gradient descent)
*/
// uniform distribution in [0,1]
void randomize (float &x)
{
x = float(rand()) / RAND_MAX;
}
// uniform distribution in [0,1]
void randomize (double &x)
{
x = double(rand()) / RAND_MAX;
}
// uniform distribution in [0,1]
void randomize (long double &x)
{
x = static_cast<long double>(rand()) / RAND_MAX;
}
// open annulus of given inner and outer radii in the vector space -- false
// is the parameter value for ComponentQualifier::PROCEDURAL
template <typename InnerProductId_, typename Derived_, typename Scalar_, typename BasedVectorSpace_>
void randomize (Vector_i<Derived_,Scalar_,BasedVectorSpace_,false> &x,
Scalar_ const &inner_radius,
Scalar_ const &outer_radius)
{
Scalar_ squared_inner_radius = sqr(inner_radius);
Scalar_ squared_outer_radius = sqr(outer_radius);
Scalar_ sqn;
do
{
// generate a random vector in the cube [-1,1]^n, where n is the dimension of the space
for (typename Vector_i<Derived_,Scalar_,BasedVectorSpace_,false>::ComponentIndex i; i.is_not_at_end(); ++i)
{
randomize(x[i]); // puts x[i] within [0,1]
x[i] *= Scalar_(2)*outer_radius;
x[i] -= outer_radius;
}
sqn = squared_norm<InnerProductId_>(x);
} // if the randomly generated point is outside of the annulus, try again
while (sqn <= squared_inner_radius || squared_outer_radius <= sqn);
}
#endif
// for arbitrary codomain
template <typename ParameterSpace_, typename CodomainSpace_, typename Scalar_>
struct FunctionObjectType_m
{
typedef typename DualOf_f<ParameterSpace_>::T DualOfBasedVectorSpace;
typedef SymmetricPowerOfBasedVectorSpace_c<2,DualOfBasedVectorSpace> Sym2Dual;
typedef CodomainSpace_ CodomainSpace;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<CodomainSpace_,DualOfBasedVectorSpace>> Differential1;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<CodomainSpace_,Sym2Dual>> Differential2;
typedef ImplementationOf_t<ParameterSpace_,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> V;
typedef ImplementationOf_t<DualOfBasedVectorSpace,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> DualOfV;
typedef ImplementationOf_t<Sym2Dual,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> Sym2_DualOfV;
typedef ImplementationOf_t<CodomainSpace_,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> Out;
typedef ImplementationOf_t<Differential1,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> D1;
typedef ImplementationOf_t<Differential2,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> D2;
};
// template specialization for when CodomainSpace_ is Scalar_
template <typename ParameterSpace_, typename Scalar_>
struct FunctionObjectType_m<ParameterSpace_,Scalar_,Scalar_>
{
typedef typename DualOf_f<ParameterSpace_>::T DualOfBasedVectorSpace;
typedef SymmetricPowerOfBasedVectorSpace_c<2,DualOfBasedVectorSpace> Sym2Dual;
typedef Scalar_ CodomainSpace;
typedef DualOfBasedVectorSpace Differential1;
typedef Sym2Dual Differential2;
typedef ImplementationOf_t<ParameterSpace_,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> V;
typedef ImplementationOf_t<DualOfBasedVectorSpace,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> DualOfV;
typedef ImplementationOf_t<Sym2Dual,Scalar_,UseMemberArray_t<ComponentsAreConst::FALSE>> Sym2_DualOfV;
typedef Scalar_ Out;
typedef DualOfV D1;
typedef Sym2_DualOfV D2;
};
// for arbitrary codomain
template <typename ParameterSpace_, typename CodomainSpace_, typename CodomainInnerProductId_, typename Scalar_, typename FunctionObject_>
struct TaylorPolynomialVerifier_t
{
typedef FunctionObjectType_m<ParameterSpace_,CodomainSpace_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_0th_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
return o.function(based_at_point);
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_1st_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
AbstractIndex_c<'i'> i;
// V delta(Static<WithoutInitialization>::SINGLETON);
// delta(i).no_alias() = evaluation_point(i) - based_at_point(i);
// return evaluate_1st_order_via_delta(o, based_at_point, delta);
return evaluate_1st_order_via_delta(o, based_at_point, (evaluation_point(i) - based_at_point(i)).eval());
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_2nd_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
AbstractIndex_c<'i'> i;
// V delta(Static<WithoutInitialization>::SINGLETON);
// delta(i).no_alias() = evaluation_point(i) - based_at_point(i);
// return evaluate_2nd_order_via_delta(o, based_at_point, delta);
return evaluate_2nd_order_via_delta(o, based_at_point, (evaluation_point(i) - based_at_point(i)).eval());
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_0th_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
return o.function(based_at_point);
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_1st_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
Out retval(Static<WithoutInitialization>::SINGLETON);
retval(i).no_alias() = o.function(based_at_point)(i)
+ o.D_function(based_at_point)(i*j)*delta(j);
return retval;
// return ( o.function(based_at_point)(i)
// + o.D_function(based_at_point)(i*j)*delta(j)).eval();
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Out evaluate_2nd_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'p'> p;
Out retval(Static<WithoutInitialization>::SINGLETON);
retval(i).no_alias() = o.function(based_at_point)(i)
+ o.D_function(based_at_point)(i*j)*delta(j)
+ o.D2_function(based_at_point)(i*p).split(p,j*k)*delta(j)*delta(k)/2;
return retval;
// return ( o.function(based_at_point)(i)
// + o.D_function(based_at_point)(i*j)*delta(j)
// + o.D2_function(based_at_point)(i*p).split(p,j*k)*delta(j)*delta(k)/2).eval();
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER_>
Scalar_ verify_gradient (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER_> const &at_point) const
{
Scalar_ big_o_bound(0);
static Uint32 const SAMPLES = 100;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V delta(Static<WithoutInitialization>::SINGLETON);
V evaluation_point(Static<WithoutInitialization>::SINGLETON);
AbstractIndex_c<'j'> j;
randomize<StandardInnerProduct>(delta, Scalar_(1)/1000, Scalar_(2)/1000);
evaluation_point(j).no_alias() = at_point(j) + delta(j);
// Scalar_ actual_function_value(function(at_point + delta)); // TODO: make this work?
Out actual_function_value(o.function(evaluation_point));
// Scalar_ estimated_function_value(evaluate_1st_order(at_point, evaluation_point));
Out estimated_function_value(evaluate_1st_order_via_delta(o, at_point, delta));
// std::cerr << FORMAT_VALUE(actual_function_value) << ", " << FORMAT_VALUE(estimated_function_value) << '\n';
Out error(Static<WithoutInitialization>::SINGLETON);
error(j).no_alias() = actual_function_value(j) - estimated_function_value(j);
Scalar_ asymptotic_ratio = norm<CodomainInnerProductId_>(error)
/
squared_norm<StandardInnerProduct>(delta);
// norm<StandardInnerProduct>(delta);
big_o_bound = std::max(big_o_bound, asymptotic_ratio);
}
//std::cerr << "verify_gradient(" << FORMAT_VALUE(at_point) << "): " << FORMAT_VALUE(big_o_bound) << '\n';
return big_o_bound;
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER_>
Scalar_ verify_hessian (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER_> const &at_point) const
{
Scalar_ big_o_bound(0);
static Uint32 const SAMPLES = 100;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V delta(Static<WithoutInitialization>::SINGLETON);
V evaluation_point(Static<WithoutInitialization>::SINGLETON);
AbstractIndex_c<'j'> j;
// use a solid annulus of radius [1/100, 2/200] around at_point
randomize<StandardInnerProduct>(delta, Scalar_(1)/1000, Scalar_(2)/1000);
evaluation_point(j).no_alias() = at_point(j) + delta(j);
// Scalar_ actual_function_value(function(at_point + delta)); // TODO: make this work?
Out actual_function_value(o.function(evaluation_point));
// Scalar_ estimated_function_value(evaluate_2nd_order(at_point, evaluation_point));
Out estimated_function_value(evaluate_2nd_order_via_delta(o, at_point, delta));
Out error(Static<WithoutInitialization>::SINGLETON);
error(j).no_alias() = actual_function_value(j) - estimated_function_value(j);
// std::cerr << FORMAT_VALUE(actual_function_value) << ", " << FORMAT_VALUE(estimated_function_value) << '\n';
Scalar_ asymptotic_ratio = norm<CodomainInnerProductId_>(error)
/
cube(norm<StandardInnerProduct>(delta));
// squared_norm<StandardInnerProduct>(delta);
big_o_bound = std::max(big_o_bound, asymptotic_ratio);
// std::cerr << FORMAT_VALUE(at_point) << ", " << FORMAT_VALUE(norm<StandardInnerProduct>(delta)) << ", " << FORMAT_VALUE(big_o_bound) << '\n';
}
//std::cerr << "verify_hessian(" << FORMAT_VALUE(at_point) << "): " << FORMAT_VALUE(big_o_bound) << '\n';
return big_o_bound;
}
};
// for when CodomainSpace_ is Scalar_
template <typename ParameterSpace_, typename Scalar_, typename FunctionObject_>
struct TaylorPolynomialVerifier_t<ParameterSpace_,Scalar_,StandardInnerProduct,Scalar_,FunctionObject_>
{
typedef FunctionObjectType_m<ParameterSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_0th_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
return o.function(based_at_point);
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_1st_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
AbstractIndex_c<'i'> i;
// V delta(Static<WithoutInitialization>::SINGLETON);
// delta(i).no_alias() = evaluation_point(i) - based_at_point(i);
// return evaluate_1st_order_via_delta(o, based_at_point, delta);
return evaluate_1st_order_via_delta(o, based_at_point, (evaluation_point(i) - based_at_point(i)).eval());
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_2nd_order (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &evaluation_point) const
{
AbstractIndex_c<'i'> i;
// AbstractIndex_c<'j'> j;
// AbstractIndex_c<'p'> p;
// V delta(Static<WithoutInitialization>::SINGLETON);
// delta(i).no_alias() = evaluation_point(i) - based_at_point(i);
// return evaluate_2nd_order_via_delta(o, based_at_point, delta);
return evaluate_2nd_order_via_delta(o, based_at_point, (evaluation_point(i) - based_at_point(i)).eval());
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_0th_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
return o.function(based_at_point);
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_1st_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
AbstractIndex_c<'i'> i;
return o.function(based_at_point)
+ o.D_function(based_at_point)(i)*delta(i);
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER0_,
typename Derived1_, ComponentQualifier COMPONENT_QUALIFIER1_>
Scalar_ evaluate_2nd_order_via_delta (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER0_> const &based_at_point,
Vector_i<Derived1_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER1_> const &delta) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
return o.function(based_at_point)
+ o.D_function(based_at_point)(i)*delta(i)
+ o.D2_function(based_at_point).split(i*j)*delta(i)*delta(j)/2;
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER_>
Scalar_ verify_gradient (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER_> const &at_point) const
{
Scalar_ big_o_bound(0);
static Uint32 const SAMPLES = 10;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V delta(Static<WithoutInitialization>::SINGLETON);
V evaluation_point(Static<WithoutInitialization>::SINGLETON);
AbstractIndex_c<'j'> j;
randomize<StandardInnerProduct>(delta, Scalar_(1)/1000, Scalar_(2)/1000);
evaluation_point(j).no_alias() = at_point(j) + delta(j);
// Scalar_ actual_function_value(function(at_point + delta)); // TODO: make this work?
Scalar_ actual_function_value(o.function(evaluation_point));
// Scalar_ actual_function_value(o.function((at_point(j) + delta(j)).eval().value()));
// Scalar_ estimated_function_value(evaluate_1st_order(at_point, evaluation_point));
Scalar_ estimated_function_value(evaluate_1st_order_via_delta(o, at_point, delta));
Scalar_ error(actual_function_value - estimated_function_value);
// std::cerr << FORMAT_VALUE(actual_function_value) << ", " << FORMAT_VALUE(estimated_function_value) << '\n';
Scalar_ asymptotic_ratio = fabs(error)
/
squared_norm<StandardInnerProduct>(delta);
// norm<StandardInnerProduct>(delta);
big_o_bound = std::max(big_o_bound, asymptotic_ratio);
}
//std::cerr << "verify_gradient(" << FORMAT_VALUE(at_point) << "): " << FORMAT_VALUE(big_o_bound) << '\n';
return big_o_bound;
}
template <typename Derived0_, ComponentQualifier COMPONENT_QUALIFIER_>
Scalar_ verify_hessian (FunctionObject_ const &o,
Vector_i<Derived0_,Scalar_,ParameterSpace_,COMPONENT_QUALIFIER_> const &at_point) const
{
Scalar_ big_o_bound(0);
static Uint32 const SAMPLES = 100;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V delta(Static<WithoutInitialization>::SINGLETON);
V evaluation_point(Static<WithoutInitialization>::SINGLETON);
AbstractIndex_c<'j'> j;
// use a solid annulus of radius [1/100, 2/200] around at_point
randomize<StandardInnerProduct>(delta, Scalar_(1)/1000, Scalar_(2)/1000);
evaluation_point(j) = at_point(j) + delta(j);
// Scalar_ actual_function_value(function(at_point + delta)); // TODO: make this work?
Scalar_ actual_function_value(o.function(evaluation_point));
// Scalar_ estimated_function_value(evaluate_2nd_order(at_point, evaluation_point));
Scalar_ estimated_function_value(evaluate_2nd_order_via_delta(o, at_point, delta));
Scalar_ error(actual_function_value - estimated_function_value);
// std::cerr << FORMAT_VALUE(actual_function_value) << ", " << FORMAT_VALUE(estimated_function_value) << '\n';
Scalar_ asymptotic_ratio = fabs(error)
/
cube(norm<StandardInnerProduct>(delta));
// squared_norm<StandardInnerProduct>(delta);
big_o_bound = std::max(big_o_bound, asymptotic_ratio);
// std::cerr << FORMAT_VALUE(at_point) << ", " << FORMAT_VALUE(norm<StandardInnerProduct>(delta)) << ", " << FORMAT_VALUE(big_o_bound) << '\n';
}
//std::cerr << "verify_hessian(" << FORMAT_VALUE(at_point) << "): " << FORMAT_VALUE(big_o_bound) << '\n';
return big_o_bound;
}
};
// ///////////////////////////////////////////////////////////////////////////
// "hat" Lie algebra morphism from (V, \times) to (so(3), [.,.]), where
// so(3) \subset V \otimes V*, where V = R^3. This has the property that
// hat(x)*y = x \times y (cross product).
// ///////////////////////////////////////////////////////////////////////////
namespace ComponentGeneratorEvaluator {
template <typename BasedVectorSpace_, typename HatMorphism_, typename Scalar_>
Scalar_ hat (ComponentIndex_t<DimensionOf_f<HatMorphism_>::V> const &i)
{
typedef typename DualOf_f<BasedVectorSpace_>::T DualOfBasedVectorSpace;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,DualOfBasedVectorSpace>> EndomorphismOfBasedVectorSpace;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<EndomorphismOfBasedVectorSpace,DualOfBasedVectorSpace>> HatMorphism;
static_assert(TypesAreEqual_f<HatMorphism,HatMorphism_>::V, "types must match");
// hat(x,y,z) has the form
// [ [ 0 -z y ]
// [ z 0 -x ]
// [ -y x 0 ] ].
// with EndomorphismOfBasedVectorSpaces indexed as
// [ [ 0 1 2 ]
// [ 3 4 5 ]
// [ 6 7 8 ] ]
// it follows that the hat morphism is indexed as
// [ [ 0 1 2 3 4 5 6 7 8 ]
// [ 9 10 11 12 13 14 15 16 17 ]
// [ 18 19 20 21 22 23 24 25 26 ] ]
// and the hat morphism's matrix looks like
// [ [ 0 0 0 0 0 -1 0 1 0 ]
// [ 0 0 1 0 0 0 -1 0 0 ]
// [ 0 -1 0 1 0 0 0 0 0 ] ]
// so the 1 constants go in slots 7, 11, 21, while the -1 constants go in slots 5, 15, 19.
switch (i.value())
{
case 7:
case 11:
case 21:
return Scalar_(1);
case 5:
case 15:
case 19:
return Scalar_(-1);
default:
return Scalar_(0);
}
}
} // end of namespace ComponentGeneratorEvaluator
struct HatId { static std::string type_as_string (bool verbose) { return "Hat"; } };
template <typename BasedVectorSpace_, typename Scalar_>
struct HatTensor_f
{
static_assert(DimensionOf_f<BasedVectorSpace_>::V == 3, "dimension of BasedVectorSpace_ must be exactly 3");
private:
typedef typename DualOf_f<BasedVectorSpace_>::T DualOfBasedVectorSpace;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,DualOfBasedVectorSpace>> Endomorphism;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<Endomorphism,DualOfBasedVectorSpace>> HatMorphism;
typedef ComponentGenerator_t<Scalar_,
DimensionOf_f<HatMorphism>::V,
::ComponentGeneratorEvaluator::hat<BasedVectorSpace_,HatMorphism,Scalar_>,
HatId> ComponentGenerator;
HatTensor_f();
public:
typedef ImplementationOf_t<HatMorphism,Scalar_,UseProceduralArray_t<ComponentGenerator>> T;
};
// Lie algebra morphism from (R^3, \times) to (so(3), [.,.]) - as a 2-tensor
// TODO: figure out if this make sense to have for arbitrary 3-dimensional based vector spaces
template <typename Derived_, typename Scalar_, typename BasedVectorSpace_, ComponentQualifier COMPONENT_QUALIFIER_>
ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,typename DualOf_f<BasedVectorSpace_>::T>>,
Scalar_,
UseMemberArray_t<ComponentsAreConst::FALSE>>
hat (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x)
{
static_assert(DimensionOf_f<BasedVectorSpace_>::V == 3, "dimension of BasedVectorSpace_ must be exactly 3");
// for brevity
typedef ImplementationOf_t<TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,typename DualOf_f<BasedVectorSpace_>::T>>,
Scalar_,
UseMemberArray_t<ComponentsAreConst::FALSE>> T;
typedef typename Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_>::ComponentIndex c;
typedef typename T::ComponentIndex C;
T retval(Static<WithoutInitialization>::SINGLETON);
retval[C(0)] = Scalar_(0);
retval[C(1)] = -x[c(2)];
retval[C(2)] = x[c(1)];
retval[C(3)] = x[c(2)];
retval[C(4)] = Scalar_(0);
retval[C(5)] = -x[c(0)];
retval[C(6)] = -x[c(1)];
retval[C(7)] = x[c(0)];
retval[C(8)] = Scalar_(0);
return retval;
}
// ///////////////////////////////////////////////////////////////////////////
// end of "hat" stuff
// ///////////////////////////////////////////////////////////////////////////
template <typename BasedVectorSpace_, typename Scalar_>
struct J_t
{
private:
enum { _ = Assert<DimensionOf_f<BasedVectorSpace_>::V == 3>::V };
public:
typedef FunctionObjectType_m<BasedVectorSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
J_t ()
:
m_D2(Static<WithoutInitialization>::SINGLETON)
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'p'> p;
// this really should use the natural embedding of the diagonal (inner product) into Sym2Dual
m_D2(p) = Scalar_(-2)*m_inner_product.split(i*j).bundle(i*j,typename D2::Concept(),p);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
return Scalar_(1) - x(i)*m_inner_product.split(i*j)*x(j);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(j).no_alias() = x(i)*m_D2.split(i*j); //Scalar_(-2)*x(i)*m_inner_product.split(i*j);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
// AbstractIndex_c<'i'> i;
// AbstractIndex_c<'j'> j;
// AbstractIndex_c<'p'> p;
// D2 retval(Static<WithoutInitialization>::SINGLETON);
// retval(p).no_alias() = Scalar_(-2)*m_inner_product(p);
// return retval;
return m_D2;
}
private:
typename InnerProduct_f<BasedVectorSpace_,StandardInnerProduct,Scalar_>::T m_inner_product;
D2 m_D2;
};
template <typename BasedVectorSpace_, typename Scalar_>
struct K_t
{
private:
enum { _ = Assert<DimensionOf_f<BasedVectorSpace_>::V == 3>::V };
public:
typedef FunctionObjectType_m<BasedVectorSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
K_t ()
:
m_form(Static<WithoutInitialization>::SINGLETON)
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'p'> p;
// this really should use the natural embedding of the diagonal (inner product) into Sym2Dual
m_form(p) = Scalar_(2)*m_inner_product.split(i*j).bundle(i*j,typename D2::Concept(),p);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
// AbstractIndex_c<'i'> i;
// AbstractIndex_c<'j'> j;
// return Scalar_(1) / (Scalar_(1) + x(i)*m_inner_product.split(i*j)*x(j));
return Scalar_(1) / (Scalar_(1) + m_inner_product(x, x));
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(j).no_alias() = -sqr(function(x))*x(i)*m_form.split(i*j);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
Scalar_ f_of_x(function(x));
AbstractIndex_c<'a'> a;
AbstractIndex_c<'b'> b;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'p'> p;
D2 retval(Static<WithoutInitialization>::SINGLETON);
retval(p).no_alias() = sqr(f_of_x)
* ( Scalar_(2)*f_of_x*(m_form.split(j*a)*x(a)*x(b)*m_form.split(b*k)).bundle(j*k,typename D2::Concept(),p)
- m_form(p));
return retval;
}
private:
typename InnerProduct_f<BasedVectorSpace_,StandardInnerProduct,Scalar_>::T m_inner_product;
D2 m_form;
};
template <typename BasedVectorSpace_, typename Scalar_>
struct N_t
{
private:
enum { _ = Assert<DimensionOf_f<BasedVectorSpace_>::V == 3>::V };
public:
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,typename DualOf_f<BasedVectorSpace_>::T>> CodomainSpace;
typedef FunctionObjectType_m<BasedVectorSpace_,CodomainSpace,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
// typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Sym2_DualOfV Sym2_DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'p'> p;
Out retval(Static<WithoutInitialization>::SINGLETON);
retval(i*j).no_alias() = m_J.function(x)*m_identity.split(i*j)
+ Scalar_(2) * (x(i)*m_inner_product.split(j*p)*x(p) + hat(x)(i*j));
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'p'> p;
AbstractIndex_c<'A'> A;
AbstractIndex_c<'B'> B;
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(B*k).no_alias() = ( m_J.D_function(x)(k)*m_identity.split(i*j)
+ Scalar_(2) * ( m_identity.split(i*k)*m_inner_product.split(j*p)*x(p)
+ x(i)*m_inner_product.split(j*k)
+ m_hat_tensor(A*k).split(A,i*j)))
.bundle(i*j,typename Out::Concept(),B);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'l'> l;
AbstractIndex_c<'p'> p;
AbstractIndex_c<'B'> B;
AbstractIndex_c<'C'> C;
D2 retval(Static<WithoutInitialization>::SINGLETON);
retval(C*p).no_alias() = m_identity(B).split(B,C)*m_J.D2_function(x)(p)
+ Scalar_(2)
* ( (m_identity.split(i*k)*m_inner_product.split(j*l))
.bundle(i*j,typename Out::Concept(),C)
.bundle(k*l,typename Sym2_DualOfV::Concept(),p)
+ (m_identity.split(i*l)*m_inner_product.split(j*k))
.bundle(i*j,typename Out::Concept(),C)
.bundle(k*l,typename Sym2_DualOfV::Concept(),p));
return retval;
}
private:
J_t<BasedVectorSpace_,Scalar_> m_J;
typename Identity_f<BasedVectorSpace_,Scalar_>::T m_identity;
typename InnerProduct_f<BasedVectorSpace_,StandardInnerProduct,Scalar_>::T m_inner_product;
typename InnerProduct_f<DualOfBasedVectorSpace,StandardInnerProduct,Scalar_>::T m_inner_product_inverse;
typename HatTensor_f<BasedVectorSpace_,Scalar_>::T m_hat_tensor;
};
template <typename BasedVectorSpace_, typename Scalar_>
struct CayleyTransform_t
{
private:
enum { _ = Assert<DimensionOf_f<BasedVectorSpace_>::V == 3>::V };
public:
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace_,typename DualOf_f<BasedVectorSpace_>::T>> CodomainSpace;
typedef FunctionObjectType_m<BasedVectorSpace_,CodomainSpace,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
// typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Sym2_DualOfV Sym2_DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
Out retval(Static<WithoutInitialization>::SINGLETON);
retval(i).no_alias() = m_K.function(x) * m_N.function(x)(i);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
D1 retval(Static<WithoutInitialization>::SINGLETON);
// retval(i*j).no_alias() = D_K(x)(j)*N(x)(i) + K(x)*D_N(x)(i*j); // this should work but Tenh complains about the ordering
retval(i*j).no_alias() = m_N.function(x)(i)*m_K.D_function(x)(j) + m_K.function(x)*m_N.D_function(x)(i*j);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
// AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'p'> p;
AbstractIndex_c<'C'> C;
D2 retval(Static<WithoutInitialization>::SINGLETON);
retval(C*p).no_alias() = m_N.function(x)(C)*m_K.D2_function(x)(p)
+ (m_N.D_function(x)(C*k)*m_K.D_function(x)(j)).bundle(j*k,typename Sym2_DualOfV::Concept(),p)
+ (m_K.D_function(x)(k)*m_N.D_function(x)(C*j)).bundle(j*k,typename Sym2_DualOfV::Concept(),p)
+ m_K.function(x)*m_N.D2_function(x)(C*p);
return retval;
}
private:
K_t<BasedVectorSpace_,Scalar_> m_K;
N_t<BasedVectorSpace_,Scalar_> m_N;
typename Identity_f<BasedVectorSpace_,Scalar_>::T m_identity;
typename InnerProduct_f<BasedVectorSpace_,StandardInnerProduct,Scalar_>::T m_inner_product;
typename InnerProduct_f<DualOfBasedVectorSpace,StandardInnerProduct,Scalar_>::T m_inner_product_inverse;
typename HatTensor_f<BasedVectorSpace_,Scalar_>::T m_hat_tensor;
};
// quadratic function on BasedVectorSpace_
template <typename BasedVectorSpace_, typename Scalar_, typename InnerProductId_>
struct QuadraticFunction_t
{
typedef FunctionObjectType_m<BasedVectorSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
// QuadraticFunction_t ()
// :
// m1(Static<WithoutInitialization>::SINGLETON),
// m2(fill_with(0)),
// m_D2(Static<WithoutInitialization>::SINGLETON)
// {
// AbstractIndex_c<'i'> i;
// AbstractIndex_c<'j'> j;
// AbstractIndex_c<'p'> p;
// // this really should use the natural embedding of the diagonal (inner product) into Sym2Dual
// //m_D2(p) = Scalar_(-2)*m_inner_product.split(i*j).bundle(i*j,typename D2::Concept(),p);
// // random constant term
// randomize(m0);
// // random linear term
// randomize<InnerProductId_>(m1, Scalar_(0), Scalar_(10));
// // create a random, positive-definite symmetric bilinear form for the quadratic term.
// for (Uint32 it = 0; it < DimensionOf_f<BasedVectorSpace_>::V; ++it)
// {
// DualOfV a(Static<WithoutInitialization>::SINGLETON);
// randomize<InnerProductId_>(a, Scalar_(1), Scalar_(2));
// m2(p) += (a(i)*a(j)).bundle(i*j,typename D2::Concept(),p);
// }
// m_D2(p) = Scalar_(2)*m2(p);
// }
QuadraticFunction_t ()
:
m1(Static<WithoutInitialization>::SINGLETON),
m2(fill_with(0)),
m_D2(Static<WithoutInitialization>::SINGLETON)
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'p'> p;
// this really should use the natural embedding of the diagonal (inner product) into Sym2Dual
//m_D2(p) = Scalar_(-2)*m_inner_product.split(i*j).bundle(i*j,typename D2::Concept(),p);
// random constant term
randomize(m0);
// random linear term
randomize<InnerProductId_>(m1, Scalar_(0), Scalar_(10));
// // create a random, positive-definite symmetric bilinear form for the quadratic term.
// for (Uint32 it = 0; it < DimensionOf_f<BasedVectorSpace_>::V; ++it)
// {
// DualOfV a(Static<WithoutInitialization>::SINGLETON);
// randomize<InnerProductId_>(a, Scalar_(1), Scalar_(2));
// m2(p) += (a(i)*a(j)).bundle(i*j,typename D2::Concept(),p);
// }
// create a non-positive-definite symmetric bilinear form
m2(p) += ((DualOfV::template BasisVector_f<0>::V(i))*(DualOfV::template BasisVector_f<0>::V(j))).bundle(i*j,typename D2::Concept(),p);
m2(p) += ((DualOfV::template BasisVector_f<1>::V(i))*(DualOfV::template BasisVector_f<1>::V(j))).bundle(i*j,typename D2::Concept(),p);
m2(p) -= ((DualOfV::template BasisVector_f<2>::V(i))*(DualOfV::template BasisVector_f<2>::V(j))).bundle(i*j,typename D2::Concept(),p);
m_D2(p) = Scalar_(2)*m2(p);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
// AbstractIndex_c<'i'> i;
// AbstractIndex_c<'j'> j;
// return Scalar_(1) - x(i)*m_inner_product.split(i*j)*x(j);
// return m0 + m1(i)*x(i) + m2.split(i*j)*x(i)*x(j);
return m0 + m1(x) + m2(x, x);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
// D1 retval(Static<WithoutInitialization>::SINGLETON);
// retval(j).no_alias() = x(i)*m_D2.split(i*j); //Scalar_(-2)*x(i)*m_inner_product.split(i*j);
// return retval;
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(j) = m1(j) + Scalar_(2)*(x(i)*m2.split(i*j));
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
return m_D2;
}
private:
//typename InnerProduct_f<BasedVectorSpace_,StandardInnerProduct,Scalar_>::T m_inner_product;
Scalar_ m0;
DualOfV m1;
D2 m2;
D2 m_D2;
};
// quadratic function on BasedVectorSpace_
template <typename BasedVectorSpace_, typename Scalar_>
struct BigFunction_t
{
typedef FunctionObjectType_m<BasedVectorSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
return m_q.function(m_cayley_transform.function(x));
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
// AbstractIndex_c<'p'> p;
// chain rule
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(j) = m_q.D_function(m_cayley_transform.function(x))(i)
* m_cayley_transform.D_function(x).split(i*j);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'l'> l;
AbstractIndex_c<'q'> q;
typename CayleyTransform::Out cayley_transform(m_cayley_transform.function(x));
typename CayleyTransform::D1 D_cayley_transform(m_cayley_transform.D_function(x));
// double chain rule
D2 retval(Static<WithoutInitialization>::SINGLETON);
retval(q) = ( m_q.D2_function(cayley_transform).split(i*j)
* D_cayley_transform.split(i*k)
* D_cayley_transform.split(j*l)).bundle(k*l,typename D2::Concept(),q)
+
m_q.D_function(cayley_transform)(i)
* m_cayley_transform.D2_function(x).split(i*q);
return retval;
}
private:
typedef CayleyTransform_t<BasedVectorSpace_,Scalar_> CayleyTransform;
typedef TensorProduct_c<Typle_t<StandardInnerProduct,StandardInnerProduct>> InnerProductId;
QuadraticFunction_t<typename CayleyTransform::CodomainSpace,Scalar_,InnerProductId> m_q;
CayleyTransform m_cayley_transform;
};
template <typename Scalar_>
struct WaveyFunction_t
{
typedef BasedVectorSpace_c<VectorSpace_c<RealField,2,Generic>,OrthonormalBasis_c<Generic>> BasedVectorSpace;
typedef FunctionObjectType_m<BasedVectorSpace,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> const &x) const
{
typedef Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> P;
Scalar_ const &u = x[typename P::ComponentIndex(0, CheckRange::FALSE)];
Scalar_ const &v = x[typename P::ComponentIndex(1, CheckRange::FALSE)];
return sin(u)*sin(v);
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> const &x) const
{
typedef Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> P;
Scalar_ const &u = x[typename P::ComponentIndex(0, CheckRange::FALSE)];
Scalar_ const &v = x[typename P::ComponentIndex(1, CheckRange::FALSE)];
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval[typename D1::ComponentIndex(0, CheckRange::FALSE)] = cos(u)*sin(v);
retval[typename D1::ComponentIndex(1, CheckRange::FALSE)] = sin(u)*cos(v);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> const &x) const
{
typedef Vector_i<Derived_,Scalar_,BasedVectorSpace,COMPONENT_QUALIFIER_> P;
Scalar_ const &u = x[typename P::ComponentIndex(0, CheckRange::FALSE)];
Scalar_ const &v = x[typename P::ComponentIndex(1, CheckRange::FALSE)];
D2 retval(Static<WithoutInitialization>::SINGLETON);
retval[typename D2::ComponentIndex(0, CheckRange::FALSE)] = -sin(u)*sin(v);
retval[typename D2::ComponentIndex(1, CheckRange::FALSE)] = cos(u)*cos(v);
retval[typename D2::ComponentIndex(2, CheckRange::FALSE)] = -sin(u)*sin(v);
return retval;
}
};
template <typename BasedVectorSpace_, typename Scalar_, typename InnerProductId_>
struct WaveyFunction2_t
{
typedef FunctionObjectType_m<BasedVectorSpace_,Scalar_,Scalar_> FunctionObjectType;
typedef typename FunctionObjectType::DualOfBasedVectorSpace DualOfBasedVectorSpace;
typedef typename FunctionObjectType::Sym2Dual Sym2Dual;
typedef typename FunctionObjectType::CodomainSpace CodomainSpace;
typedef typename FunctionObjectType::Differential1 Differential1;
typedef typename FunctionObjectType::Differential2 Differential2;
typedef typename FunctionObjectType::V V;
typedef typename FunctionObjectType::DualOfV DualOfV;
typedef typename FunctionObjectType::Out Out;
typedef typename FunctionObjectType::D1 D1;
typedef typename FunctionObjectType::D2 D2;
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
Out function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
return sin(squared_norm<InnerProductId_>(x));
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D1 D_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
typename InnerProduct_f<BasedVectorSpace_,InnerProductId_,Scalar_>::T inner_product;
D1 retval(Static<WithoutInitialization>::SINGLETON);
retval(j) = Scalar_(2) * cos(squared_norm<InnerProductId_>(x)) * x(i)*inner_product.split(i*j);
return retval;
}
template <typename Derived_, ComponentQualifier COMPONENT_QUALIFIER_>
D2 D2_function (Vector_i<Derived_,Scalar_,BasedVectorSpace_,COMPONENT_QUALIFIER_> const &x) const
{
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'l'> l;
AbstractIndex_c<'p'> p;
typename InnerProduct_f<BasedVectorSpace_,InnerProductId_,Scalar_>::T inner_product;
D2 retval(Static<WithoutInitialization>::SINGLETON);
Scalar_ squared_norm_x = squared_norm<InnerProductId_>(x);
retval(p) = ( Scalar_(2)
* cos(squared_norm_x)
* inner_product.split(j*l)
-
Scalar_(4)
* sin(squared_norm_x)
* x(i)*inner_product.split(i*j)
* x(k)*inner_product.split(k*l)).bundle(j*l,typename D2::Concept(),p);
return retval;
}
};
int main (int argc, char **argv)
{
static Uint32 const SAMPLES = 50;
typedef double Scalar;
static Uint32 const DIM = 3;
typedef BasedVectorSpace_c<VectorSpace_c<RealField,DIM,Generic>,OrthonormalBasis_c<Generic>> BasedVectorSpace;
typedef ImplementationOf_t<BasedVectorSpace,Scalar> V;
typedef CayleyTransform_t<BasedVectorSpace,Scalar> C;
C c;
V x(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(x, Scalar(0), Scalar(10));
// std::cerr << FORMAT_VALUE(c.N(x)) << "\n\n";
// std::cerr << FORMAT_VALUE(c.D_N(x)) << "\n\n";
std::cerr << FORMAT_VALUE(c.function(x)) << "\n\n";
std::cerr << FORMAT_VALUE(c.D_function(x)) << "\n\n";
// std::cerr << FORMAT_VALUE(c.D2_function(x)) << "\n\n";
{
std::cerr << "optimizing a quadratic function\n";
QuadraticFunction_t<BasedVectorSpace,Scalar,StandardInnerProduct> qf;
V x(uniform_tuple<Scalar>(100, 100, 100));
V y(minimize<StandardInnerProduct>(qf, x, 1e-05));
std::cerr << "approximate optimizer = " << y << '\n';
std::cerr << "differential of function at approximate optimizer = " << qf.D_function(y) << '\n';
std::cerr << '\n';
}
{
std::cerr << "optimizing a wavey function 2\n";
typedef WaveyFunction2_t<BasedVectorSpace,Scalar,StandardInnerProduct> WaveyFunction2;
WaveyFunction2 wf;
WaveyFunction2::V x(fill_with(0.25));
WaveyFunction2::V y(minimize<StandardInnerProduct>(wf, x, 1e-05));
std::cerr << "approximate optimizer = " << y << '\n';
std::cerr << "differential of function at approximate optimizer = " << wf.D_function(y) << '\n';
std::cerr << '\n';
}
std::cerr << "WaveyFunction2_t\n";
{
Scalar big_o_bound(0);
typedef WaveyFunction2_t<BasedVectorSpace,Scalar,StandardInnerProduct> WaveyFunction2;
WaveyFunction2 w;
TaylorPolynomialVerifier_t<BasedVectorSpace,Scalar,StandardInnerProduct,Scalar,WaveyFunction2> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(1));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(w, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(1));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(w, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
return 0;
InnerProduct_f<BasedVectorSpace,StandardInnerProduct,Scalar>::T inner_product;
InnerProduct_f<DualOf_f<BasedVectorSpace>::T,StandardInnerProduct,Scalar>::T inner_product_inverse;
for (Uint32 it = 0; it < 10; ++it)
{
randomize<StandardInnerProduct>(x, Scalar(0), Scalar(10));
C::Out cayley_transform(c.function(x));
// std::cerr << FORMAT_VALUE(cayley_transform) << "\n\n";
AbstractIndex_c<'i'> i;
AbstractIndex_c<'j'> j;
AbstractIndex_c<'k'> k;
AbstractIndex_c<'l'> l;
// std::cerr << FORMAT_VALUE(cayley_transform(i*j)*inner_product.split(i*k)*cayley_transform(k*l)) << "\n\n";
// std::cerr << FORMAT_VALUE((cayley_transform(i*j)*inner_product.split(i*k)*cayley_transform(k*l)).eval().tensor_value()) << "\n\n";
// std::cerr << FORMAT_VALUE(cayley_transform(i*j)*inner_product.split(i*k)*cayley_transform(k*l) - inner_product_inverse.split(j*l)) << "\n\n";
// std::cerr << FORMAT_VALUE((cayley_transform(i*j)*inner_product.split(i*k)*cayley_transform(k*l) - inner_product_inverse.split(j*l)).eval().tensor_value()) << "\n\n";
typedef Typle_t<StandardInnerProduct,StandardInnerProduct> InnerProductFactorTyple;
std::cerr << "this value should be about equal to 0: "
<< FORMAT_VALUE(squared_norm<TensorProduct_c<InnerProductFactorTyple>>((cayley_transform(i*j)*inner_product.split(i*k)*cayley_transform(k*l) - inner_product.split(j*l)).eval().value())) << "\n\n";
}
// std::cerr << "QuadraticFunction_t\n";
// for (Uint32 j = 0; j < 10; ++j)
// {
// Scalar big_o_bound(0);
// QuadraticFunction_t<BasedVectorSpace,Scalar> helpy;
// for (Uint32 i = 0; i < SAMPLES; ++i)
// {
// V at_point(Static<WithoutInitialization>::SINGLETON);
// randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(10));
// big_o_bound = std::max(big_o_bound, helpy.verify_gradient(at_point));
// }
// std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
// big_o_bound = Scalar(0);
// for (Uint32 i = 0; i < SAMPLES; ++i)
// {
// V at_point(Static<WithoutInitialization>::SINGLETON);
// randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(10));
// big_o_bound = std::max(big_o_bound, helpy.verify_hessian(at_point));
// }
// std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
// }
// std::cerr << '\n';
// std::cerr << "SombreroFunction_t\n";
// for (Uint32 j = 0; j < 10; ++j)
// {
// Scalar big_o_bound(0);
// SombreroFunction_t<BasedVectorSpace,Scalar> helpy;
// for (Uint32 i = 0; i < SAMPLES; ++i)
// {
// V at_point(Static<WithoutInitialization>::SINGLETON);
// randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(10));
// big_o_bound = std::max(big_o_bound, helpy.verify_gradient(at_point));
// }
// std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
// big_o_bound = Scalar(0);
// for (Uint32 i = 0; i < SAMPLES; ++i)
// {
// V at_point(Static<WithoutInitialization>::SINGLETON);
// randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(10));
// big_o_bound = std::max(big_o_bound, helpy.verify_hessian(at_point));
// }
// std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
// }
std::cerr << "J_t\n";
{
Scalar big_o_bound(0);
typedef J_t<BasedVectorSpace,Scalar> J;
J j;
TaylorPolynomialVerifier_t<BasedVectorSpace,Scalar,StandardInnerProduct,Scalar,J> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(j, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(0), Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(j, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
std::cerr << "K_t\n";
{
Scalar big_o_bound(0);
typedef K_t<BasedVectorSpace,Scalar> K;
K k;
TaylorPolynomialVerifier_t<BasedVectorSpace,Scalar,StandardInnerProduct,Scalar,K> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(k, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(k, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
std::cerr << "N_t\n";
{
Scalar big_o_bound(0);
// N_t<BasedVectorSpace,Scalar> helpy;
typedef N_t<BasedVectorSpace,Scalar> N;
N n;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace,DualOf_f<BasedVectorSpace>::T>> CodomainSpace;
typedef TensorProduct_c<Typle_t<StandardInnerProduct,StandardInnerProduct>> CodomainInnerProductId;
TaylorPolynomialVerifier_t<BasedVectorSpace,CodomainSpace,CodomainInnerProductId,Scalar,N> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(n, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(n, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
std::cerr << "CayleyTransform_t\n";
{
Scalar big_o_bound(0);
// CayleyTransform_t<BasedVectorSpace,Scalar> helpy;
typedef CayleyTransform_t<BasedVectorSpace,Scalar> CayleyTransform;
CayleyTransform cayley_transform;
typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace,DualOf_f<BasedVectorSpace>::T>> CodomainSpace;
typedef TensorProduct_c<Typle_t<StandardInnerProduct,StandardInnerProduct>> CodomainInnerProductId;
TaylorPolynomialVerifier_t<BasedVectorSpace,CodomainSpace,CodomainInnerProductId,Scalar,CayleyTransform> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(cayley_transform, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(cayley_transform, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
std::cerr << "BigFunction_t\n";
{
Scalar big_o_bound(0);
typedef BigFunction_t<BasedVectorSpace,Scalar> BigFunction;
BigFunction big_function;
// typedef TensorProductOfBasedVectorSpaces_c<Typle_t<BasedVectorSpace,DualOf_f<BasedVectorSpace>::T>> CodomainSpace;
// typedef TensorProduct_c<Typle_t<StandardInnerProduct,StandardInnerProduct>> CodomainInnerProductId;
TaylorPolynomialVerifier_t<BasedVectorSpace,Scalar,StandardInnerProduct,Scalar,BigFunction> verifier;
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_gradient(big_function, at_point));
}
std::cerr << "max big-o-bound for gradient verification = " << big_o_bound << '\n';
big_o_bound = Scalar(0);
for (Uint32 i = 0; i < SAMPLES; ++i)
{
V at_point(Static<WithoutInitialization>::SINGLETON);
randomize<StandardInnerProduct>(at_point, Scalar(1)/2, Scalar(100));
big_o_bound = std::max(big_o_bound, verifier.verify_hessian(big_function, at_point));
}
std::cerr << "max big-o-bound for hessian verification = " << big_o_bound << '\n';
}
std::cerr << '\n';
return 0;
}
| true |
006560fd856bccb3eaccb3f206620e7330a05c05 | C++ | rcosnita/voicemynews | /src/core/analytics/Analytics.h | UTF-8 | 2,364 | 3.015625 | 3 | [] | no_license | #ifndef VOICEMYNEWSCORE_ANALYTICS_ANALYTICS_H_
#define VOICEMYNEWSCORE_ANALYTICS_ANALYTICS_H_
#include "WebBrowser.h"
#include "io/fs/FileUtils.h"
#include <string>
namespace voicemynews {
namespace core {
namespace analytics {
/**
* \brief Provides all types of analytics events we currently support in voicemynews.
*/
enum class AnalyticsEventTypeEnum : int
{
ScreenEvent = 1,
CustomEvent = 2
};
/**
* \brief Provides the model for an analytics event. It is compliant with the analytics-layer spec.
*/
class AnalyticsEvent
{
public:
AnalyticsEvent(std::string eventCategory, std::string eventAction, std::string eventLabel,
int eventValue);
std::string EventCategory() const;
std::string EventAction() const;
std::string EventLabel() const;
int EventValue() const;
AnalyticsEventTypeEnum EventType() const;
/**
* \brief Builds a json string out of the current event.
*/
std::string ToJson() const;
protected:
AnalyticsEventTypeEnum eventType_;
private:
std::string eventCategory_;
std::string eventAction_;
std::string eventLabel_;
int eventValue_;
};
/**
* \brief Provides the screen event which is going to be used for tracking screen transitions.
*/
class AnalyticsScreenEvent : public AnalyticsEvent
{
public:
AnalyticsScreenEvent(std::string screenName);
};
/**
* \brief Provides the contract for analytics layer.
*
* Analytics layer allows voice my news to publish events to a backend analytics solution. The backend analytics
* solution allows us to understand the behavior of our customers and to take accurate decisions.
*/
class Analytics
{
public:
Analytics(std::shared_ptr<WebBrowser> webBrowser);
/**
* \brief Provides the logic for logging the current analytics event.
*
* It simply builds a string from the analytics event and sends it to the web browser.
*/
void LogEvent(const AnalyticsEvent& evt);
/**
* \brief Provides the logic for retrieving the analytics html application.
*
* On each platform, this application must be embedded into a web browser or headless dom.
*/
static std::string LoadAnalyticsHtmlApp(voicemynews::core::io::fs::FileUtils& fileUtils);
private:
std::shared_ptr<WebBrowser> webBrowser_;
};
}
}
}
#endif // VOICEMYNEWSCORE_ANALYTICS_ANALYTICS_H_ | true |
af0fe17578f6a634c4f58cecd654ead27c6cc3b3 | C++ | AllenCompSci/FLOPPYGLORY | /IRAQIS_REVENGE/Old Files/PROB#39.CPP | UTF-8 | 3,761 | 2.59375 | 3 | [
"MIT"
] | permissive | //Chris Chapman
//prob#39
//7th Period
//Mr. Baker
//Library Section
#include<conio.h>
#include<iostream.h>
#include<iomanip.h>
#include<apstring.h>
#include<apvector.h>
#include<apmatrix.h>
#include<fstream.h>
//Constant Section
//Structure Section
//Prototype Section
void planet_data (ofstream&);
void choice (int&);
void screen (apstring);
//Global Variable Section
char Answer;
int N;
ofstream out_file;
apstring PLanet;
void main ()
{
do{
clrscr();
planet_data (out_file);
choice(N);
clrscr();
screen (PLanet);
cout<<"Run again? (Y/N)"<<endl;
cin>>Answer;
}while (Answer=='Y'||Answer=='y');
}
void planet_data (ofstream& out_file)
{
out_file.open("a:\\Planets.Dat");
out_file<<"Mercury"<<endl;
out_file<<"57900000 km"<<endl;
out_file<<"4880 km"<<endl;
out_file<<"88 days"<<endl;
out_file<<"59 days"<<endl;
out_file<<"0"<<endl;
out_file<<"0"<<endl;
out_file<<"Venus"<<endl;
out_file<<"108200000 km"<<endl;
out_file<<"12100 km"<<endl;
out_file<<"224.7 days"<<endl;
out_file<<"243 days (retrograde)"<<endl;
out_file<<"0"<<endl;
out_file<<"0"<<endl;
out_file<<"Earth"<<endl;
out_file<<"149600000 km"<<endl;
out_file<<"12756 km"<<endl;
out_file<<"365.2 days"<<endl;
out_file<<"23 hr 56 min 4 sec"<<endl;
out_file<<"1"<<endl;
out_file<<"0"<<endl;
out_file<<"Mars"<<endl;
out_file<<"227900000 km"<<endl;
out_file<<"6794 km"<<endl;
out_file<<"687 days"<<endl;
out_file<<"24 hr 37 min"<<endl;
out_file<<"2"<<endl;
out_file<<"0"<<endl;
out_file<<"Jupiter"<<endl;
out_file<<"778300000 km"<<endl;
out_file<<"142800 km"<<endl;
out_file<<"11.86 yrs"<<endl;
out_file<<"9 hr 55 min 30 sec"<<endl;
out_file<<"16"<<endl;
out_file<<"1"<<endl;
out_file<<"Saturn"<<endl;
out_file<<"1427000000 km"<<endl;
out_file<<"120660 km"<<endl;
out_file<<"29.46 yrs"<<endl;
out_file<<"10 hr 40 min 24 sec"<<endl;
out_file<<"18"<<endl;
out_file<<"1000"<<endl;
out_file<<"Uranus"<<endl;
out_file<<"2870000000 km"<<endl;
out_file<<"51810 km"<<endl;
out_file<<"84 yrs"<<endl;
out_file<<"16.8 hr (retrograde)"<<endl;
out_file<<"15"<<endl;
out_file<<"11"<<endl;
out_file<<"Neptune"<<endl;
out_file<<"4497000000 km"<<endl;
out_file<<"49528 km"<<endl;
out_file<<"165 yrs"<<endl;
out_file<<"16 hr 11 min"<<endl;
out_file<<"8"<<endl;
out_file<<"4"<<endl;
out_file<<"Pluto"<<endl;
out_file<<"5900000000 km"<<endl;
out_file<<"2290 km"<<endl;
out_file<<"248 y"<<endl;
out_file<<"6 days 9 hr 18 min (retrograde)"<<endl;
out_file<<"1"<<endl;
out_file<<"?"<<endl;
};
void choice (int& N)
{
cout<<"1 Mercury"<<endl<<"2 Venus"<<endl<<"3 Earth"<<endl;
cout<<"4 Mars"<<endl<<"5 Jupiter"<<endl<<"6 Saturn"<<endl;
cout<<"7 Uranus"<<endl<<"8 Neptune"<<endl<<"9 Pluto"<<endl;
do{
cout<<"Pick One: ";
cin>>N;
}while (N<1||N>9);
};
void screen (apstring PLanet)
{
struct Planets
{
apstring Revolution,Rotation,Distance,Diameter,Satellite,Ring,Name;
};
ifstream in_file;
Planets Planet;
in_file.open("a:\\Planets.Dat");
in_file>>Planet.Name;
getline(in_file,Planet.Name);
getline(in_file,Planet.Distance);
getline(in_file,Planet.Diameter);
getline(in_file,Planet.Revolution);
getline(in_file,Planet.Rotation);
getline(in_file,Planet.Satellite);
getline(in_file,Planet.Ring);
in_file.close();
cout<<Planet.Name<<endl<<endl;
cout<<"Distance from Sun: "<<Planet.Distance<<endl;
cout<<"Diameter: "<<Planet.Diameter<<endl;
cout<<"Revolution: "<<Planet.Revolution<<endl;
cout<<"Rotation: "<<Planet.Rotation<<endl;
cout<<"Satellites: "<<Planet.Satellite<<endl;
cout<<"Rings: "<<Planet.Ring<<endl;
}; | true |
09435fd28409c7edafb78291f9f71d9f229034ef | C++ | ljshou/workspace | /algorithm/daiziguizhong/inorder-successor.cc | UTF-8 | 1,812 | 3.8125 | 4 | [] | no_license | /**
* @file inorder-successor.cc
* @brief inorder successor node of a node
* in a binary tree
* @author L.J.SHOU, shoulinjun@126.com
* @version 0.1.00
* @date 2015-01-14
*/
#include <iostream>
#include <cassert>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right, *parent;
TreeNode(int x=0):
val(x), left(nullptr), right(nullptr),
parent(nullptr) {}
};
TreeNode* LeftMostNode(TreeNode *node)
{
if(node == nullptr) return nullptr;
while(node->left)
node = node->left;
return node;
}
TreeNode* Destroy(TreeNode *root)
{
if(root == nullptr) return nullptr;
root->left = Destroy(root->left);
root->right = Destroy(root->right);
delete root;
return nullptr;
}
TreeNode* InorderSuccessor(TreeNode *node)
{
if(node == nullptr) return nullptr;
TreeNode *p = node->parent;
if(node->right) {
return LeftMostNode(node->right);
}
else {
while(p && p->left != node) {
node = p;
p = node->parent;
}
return p;
}
}
void AddChild(TreeNode *root, int child, int val)
{
if(root == nullptr) return;
TreeNode *node = new TreeNode(val);
node->parent = root;
if(child == 0) {
//left child
root->left = node;
}
else {
//right child
root->right = node;
}
}
void Test()
{
TreeNode *root = new TreeNode(30);
AddChild(root, 0, 10);
AddChild(root, 1, 20);
AddChild(root->left, 0, 50);
AddChild(root->left->left, 1, 60);
AddChild(root->right, 0, 45);
AddChild(root->right, 1, 35);
TreeNode * p = LeftMostNode(root);
while(p) {
cout << p->val << " ";
p = InorderSuccessor(p);
}
root = Destroy(root);
}
int main(void)
{
Test();
return 0;
}
| true |
2068009305554db13f070588ad2fc1bf1a97f788 | C++ | frbgd/al2 | /al2-t12/al2-t12/al2-t12.cpp | UTF-8 | 705 | 3.40625 | 3 | [] | no_license | #include<math.h>
#include<iostream>
using namespace std;
class vector {
protected:
double x, y;
public:
vector(double a, double b) { x = a; y = b; }
virtual double Len_v() { return sqrt(x * x + y * y); }
virtual void Print_v() { cout << endl << "len=" << Len_v() << " x=" << x << " y=" << y; }
};
class vector_3d : public vector {
double z;
public:
vector_3d(double a, double b, double c) : vector(a, b) { z = c; }
double Len_v() { return sqrt(x * x + y * y + z * z); }
void Print_v() { vector::Print_v(); cout << " z=" << z; }
};
int main()
{
vector A(1, 2);
vector_3d B(3, 4, 5);
vector *pv;
pv = &A;
pv->Print_v();
pv = &B;
pv->Print_v();
cout << endl;
system("pause");
return 0;
} | true |
7219913332a56682114a5d5e82ad5953f9182e9a | C++ | JainStuti25/Hacktoberfest | /stepsToSortNumber.cpp | UTF-8 | 601 | 2.59375 | 3 | [] | permissive | #include <iostream>
#include <cstring>
using namespace std;
int main(){
int n=0;
int height[101];
int a=0, b=0, l=0, s=0;
cin >> n;
for (int i=0;i<n;i++){
cin >> height[i];
}
a=height[0];
for(int i=0;i<n;i++){
if (a<height[i]){
a=height[i];
l=i;
}
}
b=height[0];
for(int i=0;i<n;i++){
if (height[i]<=b){
b=height[i];
s=i;
}
}
int t= l+(n-1)-s; //total
if (l>s){
cout << t-1;
}
else cout << t;
return 0;}
| true |
8f90e415496b82d408325d9dffd53bbb6ed41441 | C++ | manujgrover71/cp_codes | /codeforces/977/E.cpp | UTF-8 | 1,696 | 2.59375 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <climits>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <set>
#include <map>
using namespace std;
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define ll long long
#define mod 1000000007
#define vi vector<int>
#define vll vector<ll>
#define pb push_back
ll power(int x, unsigned int y){
ll res = 1;
while(y > 0){
if(y & 1) res = res * x;
y >>= 1;
x *= x;
}
return res;
}
const int mx = 2 * (int)1e5 + 1;
vll adj[mx];
vector<bool> vis(mx, false);
bool findEdges(int x) {
queue<int> q;
q.push(x);
bool check = true;
while(!q.empty()) {
int front = q.front();
q.pop();
if(vis[front]) continue;
vis[front] = true;
if(adj[front].size() != 2) check = false;
for(auto child : adj[front]) {
if(!vis[child]) {
q.push(child);
}
}
}
return check;
}
// Check for number of Cases!!
void solve() {
int n, m;
cin >> n >> m;
while(m--) {
ll a, b;
cin >> a >> b;
adj[a].pb(b);
adj[b].pb(a);
}
ll ans = 0;
for(int i = 1; i <= n; i++) {
if(!vis[i]) {
if(findEdges(i))
ans++;
}
}
cout << ans;
}
int main(){
#ifndef ONLINE_JUDGE
freopen("/ATOMCODES/input.txt", "r", stdin);
freopen("/ATOMCODES/output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t = 1;
// cin >> t;
while(t--) {
solve();
}
} | true |
f381498ac2490621c8515ebc959dbe9fb4dd1793 | C++ | jrl-umi3218/tvm | /include/tvm/solver/internal/Option.h | UTF-8 | 2,665 | 2.9375 | 3 | [
"BSD-3-Clause"
] | permissive | /** Copyright 2017-2020 CNRS-AIST JRL and CNRS-UM LIRMM */
#pragma once
#include <optional>
#include <type_traits>
/** Adding getter and setter for the option \a optionName of type \a type. */
#define TVM_ADD_OPTION_GET_SET(optionName, type) \
public: \
const std::optional<type> & optionName() const { return optionName##_; } \
auto & optionName(const type & v) \
{ \
optionName##_ = v; \
return *this; \
}
/** Adding an option \a optionName of type \a type with no default value.
* The default value of the underlying solver will be used.
*/
#define TVM_ADD_DEFAULT_OPTION(optionName, type) \
private: \
using optionName##_t = type; \
std::optional<type> optionName##_; \
TVM_ADD_OPTION_GET_SET(optionName, type)
/** Adding an option \a optionName with new default value \a defaultValue, that
* will replace the value of the underlying solver.
*/
#define TVM_ADD_NON_DEFAULT_OPTION(optionName, defaultValue) \
private: \
using optionName##_t = std::remove_const_t<decltype(defaultValue)>; \
std::optional<optionName##_t> optionName##_ = defaultValue; \
TVM_ADD_OPTION_GET_SET(optionName, optionName##_t)
/** Process \a optionName: if \a optionName has a non-default value, use
* \a target.setterName to set that value for \a target.
*/
#define TVM_PROCESS_OPTION_2(optionName, target, setterName) \
if(options.optionName()) \
target.setterName(options.optionName().value());
/** Specialized version of TVM_PROCESS_OPTION_2 where \a setterName = \a optionName. */
#define TVM_PROCESS_OPTION(optionName, target) TVM_PROCESS_OPTION_2(optionName, target, optionName)
/** Process \a optionName: if \a optionName has a non-default value, set
* \a target.fieldName to set that value.
*/
#define TVM_PROCESS_OPTION_PUBLIC_ACCESS_2(optionName, target, fieldName) \
if(options.optionName()) \
target.fieldName = options.optionName().value();
/** Specialized version of TVM_PROCESS_OPTION_PUBLIC_ACCESS_2 where \a fieldName = \a optionName. */
#define TVM_PROCESS_OPTION_PUBLIC_ACCESS(optionName, target) \
TVM_PROCESS_OPTION_PUBLIC_ACCESS_2(optionName, target, optionName)
| true |
843569666a2cce7d86e55b275c906c924fb01904 | C++ | AlejandroGY/Algorithms-Templates | /factorizacion.cpp | UTF-8 | 796 | 2.859375 | 3 | [] | no_license | //Factoriza n <= 10^7 en log(n)
#include <bits/stdc++.h>
using ll = long long;
constexpr ll MAX = 10000000;
bool v[MAX];
ll len, sp[MAX];
void criba( ) {
for (ll i = 2; i < MAX; i += 2) sp[i] = 2;
for (ll i = 3; i < MAX; i += 2) {
if (!v[i]) {
sp[i] = i;
for (ll j = i; (i * j) < MAX; j += 2) {
if (!v[i * j]) {
v[i * j] = true, sp[i * j] = i;
}
}
}
}
}
std::vector <ll> factoriza(ll k) {
std::vector <ll> res;
while (k > 1) {
res.push_back(sp[k]);
k /= sp[k];
}
return res;
}
int main( ) {
std::ios_base::sync_with_stdio(0);
std::cin.tie(0);
std::cout.tie(0);
criba( );
std::vector<ll> factores = factoriza(1000);
for (auto f : factores) {
std::cout << f << " ";
}
}
| true |
832be178057a36a9e30f375ff5d391f25774d9d2 | C++ | albmarvil/The-Eternal-Sorrow | /Src/Logic/Entity/Components/AnimatedGraphics.h | ISO-8859-1 | 4,927 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | /**
@file AnimatedGraphics.h
Contiene la declaracin del componente que controla la representacin
grfica de una entidad esttica.
@see Logic::CAnimatedGraphics
@see Logic::CGraphics
@author David Llans
@date Agosto, 2010
*/
#ifndef __Logic_AnimatedGraphics_H
#define __Logic_AnimatedGraphics_H
#include "Graphics.h"
#include "Graphics/AnimatedEntity.h"
// Predeclaracin de clases para ahorrar tiempo de compilacin
namespace Graphics
{
class CAnimatedEntity;
}
//declaracin de la clase
namespace Logic
{
/**
Componente que se encarga de la representacin grfica animada de una
entidad. Especializa a la clase CGraphics para que la entidad grfica
creada sea animada.
<p>
Adems de los mensajes de cambio de posicin y de cambio de orientacin
que acepta CGraphics, acepta mensajes para poner o para una animacin
(SET_ANIMATION y STOP_ANIMATION).
@ingroup logicGroup
@author David Llans Garca
@date Agosto, 2010
*/
class CAnimatedGraphics : public CGraphics, public Graphics::CAnimatedEntityListener
{
DEC_FACTORY(CAnimatedGraphics);
public:
/**
Constructor por defecto; inicializa los atributos a su valor por
defecto.
*/
CAnimatedGraphics() : CGraphics(), _animatedGraphicsEntity(0),
_defaultAnimation("") , _animationConfig(""), _speed(1.0f), _multSpeed(1.f) {}
/**
Mtodo virtual que elige que mensajes son aceptados. Son vlidos
SET_ANIMATION y STOP_ANIMATION.
@param message Mensaje a chequear.
@return true si el mensaje es aceptado.
*/
virtual bool accept(const std::shared_ptr<Logic::IMessage> &message);
/**
Mtodo virtual que procesa un mensaje.
@param message Mensaje a procesar.
*/
virtual void process(const std::shared_ptr<Logic::IMessage> &message);
////////////////////////////////////////
// Mtodos de CAnimatedEntityListener //
////////////////////////////////////////
/**
Mtodo que ser invocado siempre que se termine una animacin.
Las animaciones en cclicas no invocarn nunca este mtodo.
@param animation Nombre de la animacin terminada.
*/
void animationFinished(const std::string &animation);
Graphics::CAnimatedEntity* getAnimatedEntity(){return _animatedGraphicsEntity;}
/**
Metodo que sirve para setear el entityInfo y el map en donde sera respawneada. No pongo solo la posicion, sino mas bien
el entityInfo entero, porque puede ocurrir que queramos setear por ejemplo, la vida que tenga un enemigo, dado
que los enemigos se haran mas fuertes.
@param map Mapa Logic en el que se registrara la entidad
@param entity Informacion de construccion de la entidad leida del fichero
@return Cierto si el respawn ha sido satisfatorio
**/
//virtual bool respawn(const Map::CEntity *entity);
/**
Mtodo que activa el componente; invocado cuando se activa
el mapa donde est la entidad a la que pertenece el componente.
<p>
La implementacin registrar al componente en algunos observers en
los que pueda necesitar estar registrado (como el cronmetro del
sistema, etc.).
@return true si todo ha ido correctamente.
*/
virtual bool activate();
/**
Mtodo que desactiva el componente; invocado cuando se
desactiva el mapa donde est la entidad a la que pertenece el
componente. Se invocar siempre, independientemente de si estamos
activados o no.
<p>
La implementacin eliminar al componente de algunos observers en los
que pueda estar registrado (como el cronmetro del sistema, etc.).m
*/
virtual void deactivate();
std::string getDefaultAnimation(){return _defaultAnimation;};
std::string getActualAnimation(){return _actualAnimation;};
void setAnimation(const std::string &animation, const std::string &animSet = "default", bool loop = false, bool restart = false, float duration = 0.0f, float speed = 1.0f, bool saveAnim = true);
void setMultiSpeed(float ms) {_multSpeed = ms;};
protected:
/**
Mtodo virtual que construye la entidad grfica animada de la entidad.
Sobreescribe el mtodo de la clase CGraphics.
@param entityInfo Informacin de construccin del objeto ledo del
fichero de disco.
@return Entidad grfica creada, NULL si hubo algn problema.
*/
virtual Graphics::CEntity* createGraphicsEntity(const Map::CEntity *entityInfo);
/**
Entidad grfica animada.
*/
Graphics::CAnimatedEntity *_animatedGraphicsEntity;
/**
Animacin por defecto de una entidad grfica animada.
*/
std::string _defaultAnimation;
/**
Animacin actual
*/
std::string _actualAnimation;
/*
Multiplicador de velocidad para la animacion
*/
float _multSpeed;
/**
Configuracin de la entidad animada
*/
std::string _animationConfig;
/**
Speed por defecto de la animacin default
*/
float _speed;
}; // class CAnimatedGraphics
REG_FACTORY(CAnimatedGraphics);
} // namespace Logic
#endif // __Logic_AnimatedGraphics_H
| true |
fd324f9d5669cc5fe275fba2a74c14700595148a | C++ | ning2510/Think-twice-Code-once | /LeetCode/LeetCode 1189.cpp | UTF-8 | 739 | 3 | 3 | [] | no_license | /*************************************************************************
> File Name: aaa.cpp
> Author:
> Mail:
> Created Time: 2020年03月22日 星期日 18时41分37秒
************************************************************************/
class Solution {
public:
int maxNumberOfBalloons(string text) {
int sa = 0, sb = 0, sl = 0, so = 0, sn = 0;
for(int i = 0; i < text.size(); i++) {
if(text[i] == 'a') sa++;
if(text[i] == 'b') sb++;
if(text[i] == 'l') sl++;
if(text[i] == 'o') so++;
if(text[i] == 'n') sn++;
}
sl /= 2;
so /= 2;
int ans = min(sa, min(sb, min(sl, min(so, sn))));
return ans;
}
};
| true |
daeba2f4d335dcf7a7e28cda50353727c3536e11 | C++ | Agrabski/C-equals-1 | /Compiler/CM1Compiler_CPP/DataStructures/execution/IntegerValue.cpp | UTF-8 | 2,513 | 2.84375 | 3 | [] | no_license | #include "IntegerValue.hpp"
#include <sstream>
#include <gsl/gsl>
using namespace cMCompiler::dataStructures::execution;
using namespace cMCompiler::dataStructures;
number_component elementAtOr0(std::vector<number_component>& n, size_t index)
{
if (index > n.size())
return number_component(0);
return n[index];
}
cMCompiler::dataStructures::execution::json cMCompiler::dataStructures::execution::IntegerValue::emmit(ir::INameGetter const& nameLookupFunction, ISerializationManager&) const
{
return {
{"signed", isSigned_},
{"value", number_}
};
}
IntegerValue cMCompiler::dataStructures::execution::IntegerValue::operator+(IntegerValue& rhs)
{
auto result = negotiateSize(*this, rhs);
auto overflow = number_component(0);
for (auto i = 0; i < result.number_.size(); i++)
{
auto l = elementAtOr0(number_, i);
auto r = elementAtOr0(rhs.number_, i);
result.setValue(i, l + r + overflow);
unsigned char result = l + r + overflow;
if (result < l + r + overflow)
overflow = 1;
overflow = 0;
}
return result;
}
cMCompiler::dataStructures::execution::IntegerValue cMCompiler::dataStructures::execution::IntegerValue::negotiateSize(IntegerValue& l, IntegerValue& r)
{
if (l.number_.size() > r.number_.size())
return IntegerValue(l.number_.size(), l.isSigned_, l.type());
return IntegerValue(r.number_.size(), r.isSigned_, l.type());
}
void cMCompiler::dataStructures::execution::IntegerValue::setValue(usize componentIndex, number_component value)
{
assert(number_.size() > componentIndex);
number_[componentIndex] = value;
}
void cMCompiler::dataStructures::execution::IntegerValue::fromString(std::string const& s)
{
// usize optimisation
if(number_.size() == 8)
if (!isSigned_)
{
usize result = 0;
std::stringstream stream(s);
stream >> result;
*(usize*)number_.data() = result;
}
else
{
}
}
void cMCompiler::dataStructures::execution::IntegerValue::setValue(number_component* value, size_t size)
{
number_.reserve(size);
for (auto i = 0; i < size; i++)
setValue(i, value[i]);
}
std::string cMCompiler::dataStructures::execution::IntegerValue::toString() const
{
if (number_.size() == 8)
if (!isSigned_)
{
usize result = *(usize*)number_.data();
return std::to_string(result);
}
std::terminate();
}
std::unique_ptr<IRuntimeValue> cMCompiler::dataStructures::execution::IntegerValue::copy() const
{
auto result = std::make_unique<IntegerValue>(number_.size(), isSigned_, type());
result->number_ = number_;
return result;
}
| true |
6cd9547dcc54fbf8e30052a802800da476a6aa35 | C++ | hamfirst/StormBrewerEngine | /StormTech/StormSockets/StormSemaphore.cpp | UTF-8 | 1,363 | 2.8125 | 3 | [] | no_license |
#include "StormSemaphore.h"
#if defined(_WINDOWS) && defined(USE_NATIVE_SEMAPHORE)
#include <Windows.h>
#endif
namespace StormSockets
{
void StormSemaphore::Init([[maybe_unused]] int max_count)
{
#if defined(_WINDOWS) && defined(USE_NATIVE_SEMAPHORE)
m_Semaphore = CreateSemaphore(NULL, 0, max_count, NULL);
#endif
}
bool StormSemaphore::WaitOne(int ms)
{
#if defined(_WINDOWS) && defined(USE_NATIVE_SEMAPHORE)
WaitForSingleObject(m_Semaphore, ms);
#else
std::unique_lock<std::mutex> lock{ m_Mutex };
auto finished = m_ConditionVariable.wait_for(lock, std::chrono::milliseconds(ms), [&] { return m_Count > 0; });
if (finished)
{
--m_Count;
}
return finished;
#endif
}
void StormSemaphore::WaitOne()
{
#if defined(_WINDOWS) && defined(USE_NATIVE_SEMAPHORE)
WaitForSingleObject(m_Semaphore, INFINITE);
#else
std::unique_lock<std::mutex> lock(m_Mutex);
while (m_Count == 0)
{
m_ConditionVariable.wait(lock);
}
m_Count--;
#endif
}
void StormSemaphore::Release([[maybe_unused]] int amount)
{
#if defined(_WINDOWS) && defined(USE_NATIVE_SEMAPHORE)
ReleaseSemaphore(m_Semaphore, amount, NULL);
#else
std::unique_lock<std::mutex> lock(m_Mutex);
m_Count += amount;
m_ConditionVariable.notify_one();
#endif
}
} | true |
6f44b8bd8fb0ff955510bbe738f7564bf63e74f6 | C++ | Lebonesco/cplusplus_notes | /lambda.cpp | UTF-8 | 556 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <vector>
void lambda()
{
// [] - capture clause
// () - parameters
// {} - body
// [&] - capture by reference
// [=] - capture by value
std::vector<int> v{1, 2, 3, 4};
std::for_each(v.begin(), v.end(),
[](int n)
{
std::cout << n << " ";
});
int x = 0;
int y = 0;
auto print = [&](){std::cout << x << y << std::endl; };
std::vector<int> doubleV(v.size());
transform(begin(v), end(v), begin(doubleV),
[](int e){return e*2;}
);
} | true |
05ff6c84abd8a3be5ac7cc2616bd9a82bd4b9829 | C++ | claudiorafael1/ListaAmanda | /fAZENDO/Q36.cpp | ISO-8859-1 | 2,030 | 3.578125 | 4 | [] | no_license | /*36 - Fazer um programa em C que solicita um nmero inteiro e soletra o mesmo na
tela. Ex: 124: um, dois, quatro.*/
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
#include <math.h>
main(){
char num[4];
char vetor[4];
setlocale(LC_ALL,"PORTUGUESE");
printf("Digite seu nmero: ");
gets(num);
vetor [4] = '\0';
fflush(stdin);
fflush(stdin);
switch(num[0]){
case '1':
vetor[0]='um';
break;
case '2':
vetor[0]='dois';
break;
case '3':
vetor[0]='tres';
break;
case '4':
vetor[0]= 'quatro';
break;
case '5':
vetor[0]='cinco';
break;
case '6':
vetor[0]='seis';
break;
case '7':
vetor[0]='sete';
break;
case '8':
vetor[0] ='oito';
break;
case '9':
vetor[0]= 'nove';
break;
default:
vetor[0]= 'zero';
}
fflush (stdin);
switch(num[1]){
case '1':
vetor[1]='um';
break;
case '2':
vetor[1]='dois';
break;
case '3':
vetor[1]='tres';
break;
case '4':
vetor[1]= 'quatro';
break;
case '5':
vetor[1]='cinco';
break;
case '6':
vetor[1]='seis';
break;
case '7':
vetor[1]='sete';
break;
case '8':
vetor[1] ='oito';
break;
case '9':
vetor[1]= 'nove';
break;
default:
vetor[1]= 'zero';
}
fflush(stdin);
switch(num[3]){
case '1':
vetor[2]='um';
break;
case '2':
vetor[2]='dois';
break;
case '3':
vetor[2]='tres';
break;
case '4':
vetor[2]= 'quatro';
break;
case '5':
vetor[2]='cinco';
break;
case '6':
vetor[2]='seis';
break;
case '7':
vetor[2]='sete';
break;
case '8':
vetor[2] ='oito';
break;
case '9':
vetor[2]= 'nove';
break;
default:
vetor[2]= 'zero';
}
fflush(stdin);
for(int i=0;i<3;i++){
fflush(stdin);
printf("%s",vetor[i]);
fflush(stdin);
}
}
| true |
a9883dcfd50588e4414ff2561bf7deef6fd1e502 | C++ | JimmyCarter5417/leetcode | /cpp/0242. Valid Anagram.cpp | UTF-8 | 1,035 | 3.5 | 4 | [] | no_license | // Given two strings s and t , write a function to determine if t is an anagram of s.
// Example 1:
// Input: s = "anagram", t = "nagaram"
// Output: true
// Example 2:
// Input: s = "rat", t = "car"
// Output: false
// Note:
// You may assume the string contains only lowercase alphabets.
// Follow up:
// What if the inputs contain unicode characters? How would you adapt your solution to such case?
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> mm; // 记录每个字符的绝对计数
for (auto ch: s)
{
++mm[ch];
}
for (auto ch: t)
{
if (mm.find(ch) == mm.end() || mm[ch] == 0) / 可提前结束
{
return false;
}
else
{
--mm[ch];
}
}
for (auto p: mm)
{
if (p.second != 0)
return false;
}
return true;
}
};
| true |
176d743c936c903dfd46a2590a75b034d308a590 | C++ | OggYiu/rag-engine | /src/Logger.cpp | UTF-8 | 614 | 2.671875 | 3 | [] | no_license | #include "Logger.h"
#include <sstream>
#include "Kernel.h"
static Logger s_instance;
Logger::Logger()
: drawToScreen_( true )
{
}
Logger::~Logger()
{
}
void Logger::trace( const std::string& tag, const std::string& msg, const int line, const std::string& filename, const Uint32 color )
{
std::stringstream ss;
ss << "<" << tag << "> : \"" << msg << "\", line: " << line << ", file: " << filename;
std::string str = ss.str();
if ( !drawToScreen_ ) {
std::cout << str << std::endl;
} else {
kernel.getInstance().addDebugMsg( str, color );
}
}
Logger& Logger::getInstance()
{
return s_instance;
}
| true |
2b397918c4a02c5f5eacacb8d17c0bf1ae5a4680 | C++ | beliefy/luogu | /String/zuichangqiznhui_kmp.cpp | UTF-8 | 1,614 | 2.5625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define mem(a, b) memset(a, b, sizeof(a))
#define fo1(a, b) for (int a = 0; a < b; ++a)
#define fo2(a, b) for (int a = 1; a <= b; ++a)
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 2e5 + 5;
int nxt[15];
vector<int> v[maxn]; //首尾位置
bool vis[maxn];
int ans = 0;
void getnxt(string s2, int l2)
{
int i = 0, j = 1;
while (j < l2)
{
if (s2[i] == s2[j])
nxt[j++] = ++i;
else if (!i)
nxt[j++] = 0;
else
i = nxt[i - 1];
}
}
void KMP(string s1, string s2, int l1, int l2)
{
int i = 0, j = 0;
while (i < l1)
{
if (s1[i] == s2[j])
i++, j++;
else if (!j)
i++;
else
j = nxt[j - 1];
if (j == l2)
{
v[i - j].push_back(i - j - 1 + l2); //记录首尾位置
j = nxt[j - 1];
}
}
}
void dfs(int x)
{
int len = v[x].size();
if (len == 0)
{
ans = max(ans, x);
}
fo1(i, len)
{
if (!vis[v[x][i] + 1])
{ //看看要去的点走没走过
vis[v[x][i] + 1] = 1;
dfs(v[x][i] + 1);
}
}
}
int main()
{
string s1, s2[205];
int l = 0;
while (cin >> s2[++l])
{
if (s2[l] == ".")
break;
}
string t;
while (cin >> t)
s1 += t;
int l1 = s1.size();
fo2(i, l - 1)
{
int l2 = s2[i].size();
mem(nxt, 0);
getnxt(s2[i], l2);
KMP(s1, s2[i], l1, l2);
}
mem(vis, 0);
dfs(0);
printf("%d\n", ans);
return 0;
} | true |
a1136c3ec45d7d0de56726a653426a42ed665ec2 | C++ | lachaka/IS-Introduction-to-Programming-2018 | /Week05/solutions/READMESolutions/task04.cpp | UTF-8 | 419 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int firstDigit = 0, secDigit = 0, thirdDigit = 0;
int num = 0, sum = 0;
cin >> num;
for (int i = 100; i < 1000; i++) {
firstDigit = i / 100;
secDigit = (i / 10) % 10;
thirdDigit = i % 10;
sum = firstDigit + secDigit + thirdDigit;
if (sum == num && sum >= 2 && sum <= 27) {
cout << i << endl;
}
}
return 0;
} | true |
0044542d0c7329c4eb6bb6f4a54ffccc74000332 | C++ | ewaugh13/2DGameEngine | /MonsterChase/Engine/RigidBody.h | UTF-8 | 1,693 | 2.625 | 3 | [] | no_license | #pragma once
#include "Actor.h"
#include "Vector3.h"
#include "WeakPtr.h"
namespace Engine
{
namespace Physics
{
class RigidBody : public IActorComponent
{
public:
RigidBody(const SmartPtr<Actor> & i_Actor, const Vector3 & i_MovementForces, const Vector3 & i_MaxVelocity, float i_Mass, float i_Kd) :
m_Actor(i_Actor), m_Forces(Vector3::Zero), m_MovementForces(i_MovementForces), m_Acceleration(Vector3::Zero),
m_Velocity(Vector3::Zero), m_MaxVelocity(i_MaxVelocity), m_Mass(i_Mass), m_Kd(i_Kd)
{
}
RigidBody(const RigidBody & i_OtherBody);
void BeginUpdate(float i_DeltaTime);
WeakPtr<Actor> GetActor() const { return m_Actor; }
Vector3 GetVelocity() const { return m_Velocity; }
void SetVelocity(Vector3 & i_Velocity) { m_Velocity = i_Velocity; }
void SetMaxVelocity(Vector3 & i_NewMaxVelocity) { m_MaxVelocity = i_NewMaxVelocity; }
Vector3 GetForces() const { return m_Forces; }
void SetXForce(float i_NewXForce) { m_Forces.SetX(i_NewXForce); }
void SetYForce(float i_NewYForce) { m_Forces.SetY(i_NewYForce); }
void SetForces(Vector3 & i_NewForce) { m_Forces = i_NewForce; }
private:
WeakPtr<Actor> m_Actor;
Vector3 m_Forces;
// the force applied when moving
Vector3 m_MovementForces;
Vector3 m_Acceleration;
Vector3 m_Velocity;
// the max velocity of the actor
Vector3 m_MaxVelocity;
float m_Mass;
float m_Kd;
};
class RigidBodyDestructor : public ComponentDestructor
{
public:
static void release(RigidBody * i_ptr)
{
SmartPtr<Actor> actor = i_ptr->GetActor().AcquireSmartPtr();
if (actor)
actor->RemoveComponent("rigidbody");
delete i_ptr;
}
};
}
} | true |
ebf6b50c3e1d42e1fc53f5f8f166f8d4f9068011 | C++ | HekpoMaH/Olimpiads | /maycamp/zapodozrqn.cpp | UTF-8 | 1,151 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
struct nom
{
int num;
string p;
};
nom cm[100005],maf[100005];
int n,m;
bool dn[100005];
bool cmp(nom f,nom s)
{
if(f.p<s.p)return true;
if(f.p>s.p)return false;
if(f.num<s.num)return true;
return false;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%s",&cm[i].p);
cm[i].num=i;
}
for(int i=1;i<=m;i++)
{
scanf("%s",&maf[i].p);
maf[i].num=i;
}
sort(cm+1,cm+n+1,cmp);
sort(maf+1,maf+m+1,cmp);
//for(int i=1;i<=n;i++)cout<<cm[i].p<<endl;
//cout<<endl;
//for(int i=1;i<=m;i++)cout<<maf[i].p<<endl;
int i=1,j=1;
while(i<=n&&j<=m)
{
//cout<<cm[i].p<<" "<<maf[j].p<<endl;
if(cm[i].p==maf[j].p)
{
dn[maf[j].num]=true;
j++;
}
else if(cm[i].p<maf[j].p){i++;}
else if(cm[i].p>maf[j].p){j++;}
}
for(int i=1;i<=m;i++)
{
if(dn[i]==true)printf("YES\n");
else printf("NO\n");
}
return 0;
} | true |
d136dce9a6e6fe2993b07f6e4159a385bb0d6382 | C++ | smallStonela/libbricks | /include/bricks/collections/deque_internal.h | UTF-8 | 3,048 | 2.859375 | 3 | [] | no_license | #pragma once
#include "bricks/config.h"
#if !BRICKS_CONFIG_STL
#error libbricks must be configured to use the STL
#endif
#include "bricks/core/object.h"
#include "bricks/core/autopointer.h"
#include "bricks/core/exception.h"
#include "bricks/collections/comparison.h"
#include "bricks/collections/collection.h"
#include <deque>
namespace Bricks { namespace Collections {
class QueueEmptyException : public Exception
{
public:
QueueEmptyException(const String& message = String::Empty) : Exception(message) { }
};
template<typename T> class DequeIterator;
template<typename T>
class Deque : public Object, public Collection<T>, public IterableFast<DequeIterator<T> >
{
protected:
AutoPointer<ValueComparison<T> > comparison;
typename std::deque<T> queue;
typedef typename std::deque<T>::iterator iterator;
typedef typename std::deque<T>::const_iterator const_iterator;
friend class DequeIterator<T>;
const_iterator IteratorOfItem(const T& value) const {
for (const_iterator iter = queue.begin(); iter != queue.end(); iter++) {
if (!comparison->Compare(*iter, value))
return iter;
}
return queue.end();
}
iterator IteratorOfItem(const T& value) {
for (iterator iter = queue.begin(); iter != queue.end(); iter++) {
if (!comparison->Compare(*iter, value))
return iter;
}
return queue.end();
}
public:
Deque(ValueComparison<T>* comparison = autonew OperatorValueComparison<T>()) : comparison(comparison) { }
Deque(const Deque<T>& queue, ValueComparison<T>* comparison = autonew OperatorValueComparison< T >()) : comparison(comparison ?: queue.comparison.GetValue()), queue(queue.queue) { }
Deque(Iterable<T>* iterable, ValueComparison<T>* comparison = autonew OperatorValueComparison<T>()) : comparison(comparison) { AddItems(iterable); }
virtual void Push(const T& value) = 0;
// Iterator
virtual ReturnPointer<Iterator<T> > GetIterator() const { return autonew DequeIterator<T>(const_cast<Deque<T>&>(*this)); }
DequeIterator<T> GetIteratorFast() const { return DequeIterator<T>(const_cast<Deque<T>&>(*this)); }
// Collection
virtual long GetCount() const { return queue.size(); };
virtual bool ContainsItem(const T& value) const { return IteratorOfItem(value) != queue.end(); }
virtual void AddItem(const T& value) { Push(value); }
virtual void AddItems(Iterable<T>* values) { BRICKS_FOR_EACH (const T& item, values) AddItem(item); }
virtual void Clear() { queue.clear(); }
virtual bool RemoveItem(const T& value) {
iterator iter = IteratorOfItem(value);
if (iter == queue.end())
return false;
queue.erase(iter);
return true;
}
};
template<typename T>
class DequeIterator : public Iterator<T>
{
private:
typename Deque<T>::iterator position;
typename Deque<T>::iterator end;
friend class Deque<T>;
public:
DequeIterator(Deque<T>& queue) : position(queue.queue.begin() - 1), end(queue.queue.end()) { }
T& GetCurrent() const { return *position; }
bool MoveNext() { return ++position < end; }
};
} }
| true |
5b27450ce10e6fa6831be3b301f2415008de33c4 | C++ | Draculavid/shared | /shared/main.cpp | UTF-8 | 3,500 | 3.625 | 4 | [] | no_license | /* Application producer: David Wigelius */
#include "CircularBuffer.h"
using namespace std;
#pragma region the random function
size_t random(size_t min, size_t max)
{
int range, result, cutoff;
if (min >= max)
return min;
range = max - min + 1;
cutoff = (RAND_MAX / range) * range;
do {
result = rand();
} while (result >= cutoff);
return result % range + min;
}
void gen_random(char *s, const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (auto i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
#pragma endregion
void Producer(LPCWSTR buffName, const size_t & delay, const size_t & buffSize, const size_t & numMessages, const size_t & chunkMsg)
{
CircularBuffer cBuffer(buffName, buffSize, true, 256);
/*the msgLeft variable will tell the producer how many
messages are left to send */
char* message = new char[buffSize * 1<<10];
size_t msgLeft = numMessages;
while (msgLeft > 0)
{
/*a bool variable to check if the message was sent */
bool msgSent = false;
/*calculating the size of the message*/
size_t msgSize;
if (chunkMsg == 0)
msgSize = random(1, ((buffSize * (1 << 10)) / 4));
else
msgSize = chunkMsg;
/*Creating the message*/
gen_random(message, msgSize);
/*A loop that tries to sent the message over and over until it's sent*/
while (!msgSent)
{
if (cBuffer.push(message, msgSize))
{
std::cout << msgLeft << " " << message << "\n";
msgSent = true;
msgLeft--;
Sleep(delay);
}
else
{
Sleep(delay);
}
}
}
/*deleting the message so that there will be no memory leaks*/
delete message;
}
void Consumer(LPCWSTR buffName, const size_t & delay, const size_t & buffSize, const size_t & numMessages)
{
CircularBuffer cBuffer(buffName, buffSize, false, 256);
size_t msgLeft = numMessages;
//Creating the variable that will hold the message
char* msg = new char[buffSize * 1 << 10];
while (msgLeft > 0)
{
size_t length;
bool msgRecieved = false;
while (!msgRecieved)
{
if (cBuffer.pop(msg, length))
{
msg[length] = '\0';
std::cout << msgLeft << " " << msg << "\n";
msgRecieved = true;
msgLeft--;
Sleep(delay);
}
else
{
Sleep(delay);
}
}
}
delete msg;
}
int main(int argc, char* args[])
{
if (argc >= 6)
{
/*
The first usable element (1) will determine if the program
will behave as a producer or a comsumer.
The second will be delay, it will be sent in milliseconds
The third argument will be memorySize (buffsize), which will be the size
of memory we will allocate for the shared memory
The fourth is numMessages, which will dictate how many messages
this executable will sent between the producer and consumers
The fifth is random|msgSize. It will tell the application if
we will send random sized messages of a fixed size. If it's a
fixed size, i guess we should send 1/4 of the reserved memory
in each message.
*/
size_t delay = atoi(args[2]);
size_t buffSize = atoi(args[3]);
size_t numMessages = atoi(args[4]);
size_t chunkSize;
if (strcmp(args[5], "random") == 0)
chunkSize = 0;
else
chunkSize = atoi(args[5]);
if (strcmp(args[1], "producer") == 0)
Producer((LPCWSTR)"theSuperMap", delay, buffSize, numMessages, chunkSize);
else if (strcmp(args[1], "consumer") == 0)
Consumer((LPCWSTR)"theSuperMap", delay, buffSize, numMessages);
}
return 0;
} | true |
7e477269ff28ae64c1842103e7c4cbbf3e12c481 | C++ | an2arch/Gallery | /ConsoleMenu/ItemMenu.cpp | UTF-8 | 832 | 3.3125 | 3 | [] | no_license | #include <ItemMenu.h>
#include <utility>
ItemMenu::ItemMenu(string item_name, Function task)
: m_name{std::move(item_name)}, m_task{std::move(task)} {}
ItemMenu::ItemMenu(const ItemMenu &other)
: ItemMenu(other.m_name, other.m_task) {};
string ItemMenu::getItemName() const {
return m_name;
}
void ItemMenu::print(std::ostream &out) const {
out << m_name;
}
ItemMenu &ItemMenu::operator=(const ItemMenu &other) {
if (this == &other) {
return *this;
}
m_name = other.m_name;
m_task = other.m_task;
return *this;
}
std::ostream &operator<<(std::ostream &out, const ItemMenu &item) {
item.print(out);
return out;
}
int ItemMenu::operator()() const {
return run();
}
int ItemMenu::run() const {
if (m_task) {
return m_task();
}
return -1;
}
| true |
1318792ab88d683e509bd533a9fadf606cfc5048 | C++ | AnminQ97/Titan-Souls | /D2D/Systems/SoundTool.cpp | UHC | 3,190 | 3 | 3 | [] | no_license | #include"stdafx.h"
#include"SoundTool.h"
SoundTool::SoundTool()
:buffer(15), volume(1.0f)
{
System_Create(&system);
system->init(buffer, FMOD_INIT_NORMAL, NULL);
sound = new Sound* [buffer];
channel = new Channel*[buffer];
memset(sound, NULL, sizeof(Sound*) * buffer); //ּҺ null ֱ
memset(channel, NULL, sizeof(Channel*) * buffer);
}
SoundTool::~SoundTool()
{
if (channel != NULL)
{
for (UINT i = 0; i < buffer; i++)
if (channel[i]) channel[i]->stop(); //鼭 ä
}
if (sound != NULL)
{
for (UINT i = 0; i < buffer; i++)
if (sound[i]) sound[i]->release(); //鼭 sound
}
SAFE_DELETE_ARRAY(channel);
SAFE_DELETE_ARRAY(sound);
if (system != NULL)
{
system->release();
system->close();
}
sounds.clear();
}
void SoundTool::AddSound(string name, string sounFile, bool bLoop)
{
if (bLoop == true) //ݺ ̸
{
system->createStream
(
sounFile.c_str(),
FMOD_LOOP_NORMAL,
NULL,
&sound[sounds.size()]
);
return;
}
system->createStream
(
sounFile.c_str(),
FMOD_DEFAULT,
NULL,
&sound[sounds.size()]
);
sounds[name] = &sound[sounds.size()]; // ̸ ֱ
}
void SoundTool::Play(string name, float volume)
{
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
system->playSound(FMOD_CHANNEL_FREE,*iter->second,false,&channel[count]); //ִ ä ؼ
channel[count]->setVolume(volume); // ä
}
}
}
void SoundTool::Stop(string name)
{
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->stop();
break;
}
}
}
void SoundTool::Pause(string name) //Ͻ
{
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->setPaused(true);
break;
}
}
}
void SoundTool::Resume(string name) //ٽ
{
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->setPaused(false);
break;
}
}
}
bool SoundTool::Playing(string name)
{
bool bPlay = false;
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->isPlaying(&bPlay);
break;
}
}
return bPlay;// ƴ
}
bool SoundTool::Paused(string name)
{
bool bPaused = false;
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->getPaused(&bPaused);
break;
}
}
return bPaused;//
}
void SoundTool::Update()
{
system->update();
}
void SoundTool::Volume(string name, float volume)
{
int count = 0;
iter = sounds.begin();
for (iter; iter != sounds.end(); ++iter, count++)
{
if (name == iter->first)
{
channel[count]->setVolume(volume);
break; //break Ҹ
}
}
}
| true |
87ecbc94f90d1a013f35a44d59b258cc7a5a5e01 | C++ | sirkp/DSA | /17. Graphs/problems/p2.cpp | UTF-8 | 628 | 3.359375 | 3 | [] | no_license | // BFS
// https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1/
// O(V+E), space: O(V)
// Time:E comes for traversing all adjacency list element, V comes for when all vertices are disconnected
// space: V for maintaing visited array
vector<int> bfs(vector<int> g[], int n){
vector<int> v;
queue<int> q;
bool visited[n] = {false};
q.push(0);
visited[0] = true;
while(!q.empty()){
v.push_back(q.front());
for(auto x: g[q.front()])
if(!visited[x]){
q.push(x);
visited[x] = true;
}
q.pop();
}
return v;
} | true |
f66e913ef29a801cebc3cdba6fecf30323fac970 | C++ | Trickster2038/BmstuLabs2 | /задания/2 часть/Учебное пособие. C++. 2 часть Объектно-ориентированное программирование/Примеры к части 2/Ex8_01/main.cpp | WINDOWS-1251 | 760 | 3.234375 | 3 | [] | no_license | #include <memory>
#include <iostream>
#include <conio.h>
using namespace std;
class A
{
public:
int x;
A(int X):x(X){}
A(){}
~A(){cout<<"destructor"<<endl;}
};
void main()
{
auto_ptr<A> temp1; // -
auto_ptr<A> temp(new A(1)); // -
A &a= *temp; //
cout<<"A.x="<<a.x<<endl;
A *ptr = temp.get();//
cout<<"ptr="<<ptr<<endl;
temp.reset(); //
A *ptr1 = temp.get();//
cout<<"ptr1="<<ptr1<<endl;
getch();
}
| true |
b5f59fb4541a22770de40c3d242021322b8517dc | C++ | kernelhunter92/CatrobatForWindows | /Source/Master/Catrobat/PlayerWindowsPhone8/PlayerWindowsPhone8Component/Project.h | UTF-8 | 647 | 2.625 | 3 | [] | no_license | #pragma once
#include "BaseObject.h"
#include "SpriteList.h"
class Project
{
public:
Project(int androidVersion, int catroidVersionCode, string CatroidVersionName, string projectName,
int screenWidth, int screenHeight);
~Project();
int getAndroidVersion();
int getCatroidVersionCode();
string getCatroidVersionName();
string getProjectName();
int getScreenWidth();
int getScreenHeight();
SpriteList *getSpriteList();
private:
int m_androidVersion;
int m_catroidVersionCode;
string m_catroidVersionName;
string m_projectName;
int m_screenWidth;
int m_screenHeight;
SpriteList *m_spriteList;
};
| true |
107378b28b0fe162512dfe6c99290341f72791c2 | C++ | ngkhanha2/backup | /fundamental_of_artificial_intelligence/homeworks/01/Source/BFS.cpp | UTF-8 | 1,054 | 2.671875 | 3 | [] | no_license | /*
* BFS.cpp
*
* Created on: Apr 1, 2014
* Author: khanh
*/
#include "BFS.h"
BFS::BFS(STATE *source_state) :
BLIND_SEARCH(source_state) {
}
double BFS::solve(double time_limit) {
for (unsigned int i = 0; i < this->destination_states->size(); ++i) {
if ((*this->destination_states)[i]->compare(source_state) == 0) {
return 0;
}
}
queue<STATE*> *bfs_queue = new queue<STATE*>();
bfs_queue->push(this->source_state);
double start_time = get_time();
double time = get_time();
while (!bfs_queue->empty()) {
STATE *state = bfs_queue->front();
bfs_queue->pop();
for (int i = 0; i < this->slide->directions(); ++i) {
STATE *new_state = new STATE(state);
new_state->set_previous_state(state);
int check = this->check(new_state, i);
switch (check) {
case -1:
delete new_state;
continue;
case 1:
goto end;
}
bfs_queue->push(new_state);
}
time = get_time() - start_time;
if (time_limit != NO_TIME_LIMIT && time > time_limit) {
break;
}
}
end: delete bfs_queue;
return time;
}
| true |
9d7d584ba1aa0233582453d0f8bd85396bd92e69 | C++ | Aura-zx/zhx-Leetcode | /LeetCode/21_Merge_Two_Sorted_Lists.h | UTF-8 | 769 | 3.546875 | 4 | [] | no_license | #ifndef MERGE_TWO_SORTED_LISTS_H
#define MERGE_TWO_SORTED_LISTS_H
#include <stdlib.h>
class Solution_21
{
public:
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL){}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode* helper = new ListNode(0);
ListNode* pre = helper;
helper->next = l1;
while (l1 && l2)
{
if (l1->val > l2->val)
{
ListNode* next = l2->next;
l2->next = pre->next;
pre->next = l2;
l2 = next;
}
else
l1 = l1->next;
pre = pre->next; // current pre->val is small than l1 and l2
}
if (l2 != NULL)
pre->next = l2; // l2 is not at end,but l1 is end,so link l2 is the rest part.
return helper->next;
}
};
#endif // !MERGE_TWO_SORTED_LISTS_H
| true |
19e97bfd1abae7b142dcbdc9f758db1baeb465b8 | C++ | brennengreen/OpenGL-Mandelbrot-Fractals | /Shaders/Geometry.h | UTF-8 | 774 | 2.609375 | 3 | [] | no_license | #ifndef GEOMETRY_H
#define GEOMETRY_H
#include <glad/glad.h>
#include <iostream>
#include <vector>
#include "Shader.h"
struct GVertex {
float x;
float y;
float z;
glm::vec3 normal;
};
struct GTriangle {
GVertex vertices[3];
glm::vec3 normal;
};
struct GMesh {
std::vector<GVertex> vertices;
std::vector<GTriangle> triangles;
};
class Geometry {
public:
std::vector<float> mesh;
std::vector<GLuint> indices;
std::vector<glm::vec3> normals;
GMesh testMesh;
GLuint VAO;
Shader shader;
Geometry(std::vector<float> vertices, std::vector<GLuint> indices);
void Draw();
void setShader(const char* vs, const char* fs);
private:
GLuint VBO, EBO;
void setup();
void getNormals();
};
#endif // !GEOMETRY_H
| true |
c0f94f23587dc0ae6cb4c265d4033653462ebdd7 | C++ | alelevinas/Inventario | /Common/common_Protocolo.cpp | UTF-8 | 3,194 | 3 | 3 | [] | no_license | #include "common_Protocolo.h"
#include <string>
using common::Protocolo;
using common::Socket;
using common::Imagen;
Protocolo::Protocolo(const std::string& finalizador)
: finalizadorDeMensaje(finalizador) {}
Protocolo::~Protocolo() {}
const std::string Protocolo::getFinalizadorDeMensaje() const {
return this->finalizadorDeMensaje;
}
void Protocolo::setFinalizadorMensaje(const std::string& finalizador) {
this->finalizadorDeMensaje = finalizador;
}
const std::string Protocolo::recibirMensaje(Socket& skt) const {
return this->protocolizarMensaje(
skt.recibirMensajeFinalizado(this->finalizadorDeMensaje));
}
void Protocolo::enviarMensaje(Socket& skt, std::string mensaje) const {
skt.enviarMensaje(this->protocolizarMensaje(mensaje));
}
const std::string Protocolo::protocolizarMensaje(std::string mensaje) const {
if (mensaje == "") return finalizadorDeMensaje;
// si el mensaje no termina con el finalizador correspondiente lo agrego.
if (mensaje[mensaje.length() - 1] != this->getFinalizadorDeMensaje()[0]) {
return mensaje.append(this->getFinalizadorDeMensaje());
}
return mensaje;
}
//Recibe la imagen enviada por red. Debe chequearse a su salida que el socket siga abierto ya que si no significa que fallo la transmision.
Imagen Protocolo::recibirImagen(Socket& socket,const unsigned int altoImagen,const unsigned int anchoImagen, const unsigned long int tamanioImagen) const{
const unsigned char* datosImagen=socket.recibirBytesDinamicos(tamanioImagen);
if (socket.estaConectado()){
Imagen imagenARetornar (altoImagen,anchoImagen,datosImagen);
delete[] datosImagen;
return imagenARetornar;
}
delete[] datosImagen;
return Imagen("");
}
void Protocolo::enviarImagen(Socket& socket,const Imagen& imagenAEnviar) const{
const unsigned int altoImagen=imagenAEnviar.getAlto();
const unsigned int anchoImagen=imagenAEnviar.getAncho();
const unsigned int tamanioImagen=imagenAEnviar.getTamanio();
std::stringstream parseadorMensaje;
parseadorMensaje << kIndicadorComandoAltaImagen << kMensajeDelimitadorCampos << altoImagen << kMensajeDelimitadorCampos << anchoImagen << kMensajeDelimitadorCampos << tamanioImagen<<kMensajeDelimitadorCampos<<finalizadorDeMensaje;
enviarMensaje(socket,parseadorMensaje.str());
std::string respuesta =recibirMensaje(socket);
if (respuesta==kMensajeOK+finalizadorDeMensaje){
const unsigned char* const datosImagen= imagenAEnviar.obtenerBytesDinamicos();
socket.enviarBytes(datosImagen,tamanioImagen);
delete[] datosImagen;
}
}
const std::string Protocolo::extraerArgumentoDeComando(
const std::string& comandoDeOperacion, const size_t numeroArgumento){
std::stringstream parseador(comandoDeOperacion);
std::string argumento;
for (size_t i =0;i<numeroArgumento;++i)
std::getline(parseador, argumento, '|');
return argumento;
}
const unsigned long int Protocolo::extraerArgumentoNumericoDeComando(
const std::string& comandoDeOperacion, const size_t numeroDeParametro) {
std::stringstream parseador(extraerArgumentoDeComando(comandoDeOperacion,numeroDeParametro));
unsigned long int argumentoNumerico=0;
parseador >> argumentoNumerico;
return argumentoNumerico;
}
| true |
183a5c6b3a4ff2448d5c2c8664f6bc58a71b3411 | C++ | izvolov/burst | /test/burst/range/difference.cpp | UTF-8 | 4,573 | 3.328125 | 3 | [
"BSL-1.0"
] | permissive | #include <burst/container/make_list.hpp>
#include <burst/container/make_set.hpp>
#include <burst/container/make_vector.hpp>
#include <burst/range/difference.hpp>
#include <doctest/doctest.h>
#include <boost/range/algorithm/for_each.hpp>
#include <boost/range/algorithm/set_algorithm.hpp>
#include <functional>
#include <vector>
TEST_SUITE("difference")
{
TEST_CASE("Разность двух диапазонов – это элементы первого диапазона, "
"которые отсутствуют во втором диапазоне")
{
const auto natural = burst::make_vector({1, 2, 3, 4, 5, 6});
const auto odd = burst::make_vector({1, 3, 5 });
// ^ ^ ^
const auto difference = burst::difference(natural, odd);
const auto even = burst::make_vector({2, 4, 6});
CHECK(difference == even);
}
TEST_CASE("Допускает мультимножества")
{
const auto minuend = burst::make_vector({1, 1, 1, 2, 2, 3});
const auto subtrahend = burst::make_vector({1, 1, 2 });
// ^ ^ ^
const auto difference = burst::difference(minuend, subtrahend);
const auto expected = burst::make_vector({1, 2, 3});
CHECK(difference == expected);
}
TEST_CASE("Разность диапазона с самим собой — пустой диапазон")
{
const auto set = burst::make_vector({'a', 'b', 'c'});
const auto difference = burst::difference(set, set);
CHECK(difference.empty());
}
TEST_CASE("Разность диапазона с пустым диапазоном – это тот же диапазон")
{
const auto set = burst::make_vector({3, 2, 1});
const auto empty_set = std::vector<int>{};
const auto difference = burst::difference(set, empty_set, std::greater<>{});
CHECK(difference == set);
}
TEST_CASE("Разность пустого диапазона с любым непустым диапазоном — пустой диапазон")
{
const auto empty_set = std::vector<int>{};
const auto set = burst::make_set({1, 2, 3});
const auto difference = burst::difference(empty_set, set);
CHECK(difference.empty());
}
TEST_CASE("Разность пилообразно дополняющих друг друга диапазонов равна уменьшаемому")
{
const auto minuend = burst::make_list({'h', 'f', 'd', 'b' });
const auto subtrahend = burst::make_list({ 'g', 'e', 'c', 'a'});
// ^ ^ ^ ^
const auto difference = burst::difference(minuend, subtrahend, std::greater<>{});
CHECK(difference == minuend);
}
TEST_CASE("Если вычитаемый диапазон окружает уменьшаемый, то их разность равна уменьшаемому")
{
const auto minuend = burst::make_list({ 4, 6, 8 });
const auto subtrahend = burst::make_vector({-1, 2, 10, 11});
// ^ ^ ^
const auto difference = burst::difference(minuend, subtrahend);
CHECK(difference == minuend);
}
TEST_CASE("Допускает диапазоны разных типов")
{
const auto minuend = burst::make_list({0, 4, 6, 7, 9, 10 });
const auto subtrahend = burst::make_vector({0, 2, 5, 6, 6, 10, 11});
// ^ ^ ^
const auto difference = burst::difference(minuend, subtrahend);
const auto expected = burst::make_vector({4, 7, 9});
CHECK(difference == expected);
}
TEST_CASE("Результирующий диапазон изменяем")
{
auto minuend = burst::make_vector({1, 3, 5, 7, 9});
auto subtrahend = burst::make_vector({ 2, 3, 4, 5 });
// ^ ^ ^
auto difference = burst::difference(minuend, subtrahend);
boost::for_each(difference, [] (auto & x) { x *= 2; });
const auto expected = burst::make_vector({2, 14, 18});
CHECK(difference == expected);
}
}
| true |
f8ad9556d7e4e4749ac6f814647a08dbc3ac97fb | C++ | Vivek095/DeckOfCards | /Vivek_Goswami_Card.cpp | UTF-8 | 444 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include "Vivek_Goswami_card.h"
using namespace std;
string Card::faceArr[] = {"Ace","Deuce","Three", "Four", "Five", "Six", "Seven","Eight",
"Nine", "Ten", "Jack", "Queen","King"};
string Card::suitArr[] ={"Hearts", "Diamonds", "Clubs","Spades"};
Card::Card(int f,int s)
{
face=f;
suit=s;
}
string Card::toString()
{
return faceArr[face]+ "of" +suitArr[suit];
}
| true |
8645273a2169b48dfff63bd8e791e3dd749a5bf9 | C++ | hellozts4120/DS-homework | /week1&2/work2.cpp | UTF-8 | 1,876 | 3.671875 | 4 | [] | no_license | #include<cstdio>
#include<cstring>
#include<malloc.h>
#include<iostream>
using namespace std;
struct Link{
int value;
Link *next;
};
Link *Merge(Link *head1,Link *head2){
Link *temp1,*temp2;
Link *newone,*temp3;
int i;
temp1 = head1->next;
temp2 = head2;
temp3 = head1;
newone = head1;
newone->next = NULL;
while(temp1 || temp2){
if(temp1 == NULL){
temp3 = temp2;
temp2 = temp2->next;
}
else if(temp2 == NULL){
temp3 = temp1;
temp1 = temp1->next;
}
else if(temp1->value <= temp2->value){
temp3 = temp1;
temp1 = temp1->next;
}
else{
temp3 = temp2;
temp2 = temp2->next;
}
temp3->next = newone->next;
newone->next = temp3;
}
i = newone->value;
Link *temp4 = newone;
while(temp4->next != NULL){
if(temp4->next->value >= i){
temp4->value = temp4->next->value;
temp4->next->value = i;
}
temp4 = temp4->next;
}
return newone;
}
Link *append(Link *head){
Link *temp = head,*p;
p = (Link *)malloc(sizeof(Link));
cin >> p->value;
p->next = NULL;
if(head == NULL) return p;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = p;
return head;
}
void PrintAll(Link *head){
Link *temp = head;
int n = 1;
if(head == NULL){
cout << "Void LinkList!" << endl;
}
cout << "All Information:" << endl;
while(temp != NULL){
cout << "Index" << n << ": " << temp->value << endl;
temp = temp->next;
n++;
}
}
int main(){
Link *head1 = NULL;
Link *head2 = NULL;
Link *newone = NULL;
int n1,n2;
cout << "Enter List1 Num:";
cin >> n1;
cout << "Enter List2 Num:";
cin >> n2;
cout << "Enter Value of List1:";
for(int i = 0;i < n1;i++){
head1 = append(head1);
}
PrintAll(head1);
cout << "Enter Value of List2:";
for(int i = 0;i < n2;i++){
head2 = append(head2);
}
PrintAll(head2);
cout << "Now Merge..." << endl;
newone = Merge(head1,head2);
PrintAll(newone);
return 0;
} | true |
25e0504619b89a899fae1cb2a7a42bbb089c5188 | C++ | seeman1978/c__20 | /locale/mbsrtowcs.cpp | UTF-8 | 1,545 | 3.578125 | 4 | [] | no_license | //
// Created by 王强 on 2021/1/20.
//
#include <iostream>
#include <vector>
#include <clocale>
#include <cwchar>
void print_as_wide(const char8_t* mbstr)
{
const char8_t* mbstr2 = mbstr;
std::mbstate_t state = std::mbstate_t();
// 转化为wchar后,z:占用2个byte;ß:占用2个byte;水:占用2个byte;🍌:占用4个byte;一个10个byte
std::size_t len = 1 + std::mbsrtowcs(nullptr, reinterpret_cast<const char **>(&mbstr), 0, &state);
std::vector<wchar_t> wstr(len);
std::mbsrtowcs(&wstr[0], reinterpret_cast<const char **>(&mbstr), wstr.size(), &state);
std::wcout << "Wide string: " << &wstr[0] << '\n'
<< "The length, including '\\0': " << wstr.size() << '\n';
//wstr的size是11
wchar_t wstr2[len];
std::mbsrtowcs(&wstr2[0], reinterpret_cast<const char **>(&mbstr2), 11, &state);
std::wstring wstr3{wstr2};
std::wcout << "Wide string: " << wstr3 << " The length, not including '\\0': " << wstr3.size() << std::endl;
}
int main()
{
std::setlocale(LC_ALL, "en_US.utf8");
const char8_t *mbstr = u8"z\u00df\u6c34\U0001f34c"; // or u8"zß水🍌",ß水🍌的编码是unicode编码。通过u8前缀,系统会自动把unicode编码字符转换为utf8编码字符
//zß水🍌的utf-8编码为 7a c39f e6b064 f09f8d8c.
//zß水🍌的string和wstring的长度相同,是个巧合。
int nLength = std::char_traits<char8_t>::length(mbstr);
std::cout << "The length of ansi char is " << nLength << '\n';
print_as_wide(mbstr);
} | true |
8dd069a2556b3eaab49af2c9746e86d402b658b6 | C++ | rytai/ArtNeater | /koodi002/output.ino | UTF-8 | 2,022 | 2.671875 | 3 | [] | no_license | /*
const int nleds;
static WS2812 ledstrip;
static Pixel_t pixels[nleds];
*/
void lcdFlush()
{
lcd.setCursor(0, 0);
lcd.print(" ");
}
void UpdateLCD()
{
//lcdFlush();
lcd.setCursor(0, 0);
lcd.print(menu_lcd_projection);
memcpy(menu_lcd_projection_row2, menu_lcd_projection+(sizeof(byte)*16), 16);
/*lcd.setCursor(0, 1);
lcd.print(menu_lcd_projection_row2);
*/
/*
if(debugging) {
Serial.print ("MENU LCD PROJ:-");
Serial.print(menu_lcd_projection);
Serial.println("-");
Serial.print ("Row2:-");
Serial.print(menu_lcd_projection_row2);
Serial.println("-");
Serial.print("Channel start:");
Serial.println(channel_start);
Serial.print("Encoder movement:");
Serial.println(encoder_movement);
}
*/
}
void colormix(){
}
void initializeLEDs(){
ledstrip.init(8);
}
/*
unsigned int channel_start = 0;
unsigned int channel_width = 1;
byte channel_buffer[128*3];
static Pixel_t pixels[nleds];
*/
void ArtnetToLeds(){
uint8_t i;
uint8_t buffer_i = 0;
for (i=0; i<nleds; i++){
//GRB järjestys
pixels[i].R = channel_buffer[channel_start+(buffer_i*3)+1];
pixels[i].G = channel_buffer[channel_start+(buffer_i*3)];
pixels[i].B = channel_buffer[channel_start+(buffer_i*3)+2];
buffer_i += 3;
//Jos paketteja on tullu vähemmän kuin ledejä, loopataan saatuja värejä ledeille
if (buffer_i = (channel_width*3)) buffer_i = 0;
}
ledstrip.show(pixels);
}
void RGBtoLeds(){
for (i=0; i<nleds; i++){
//GRB järjestys
pixels[i].R = simpleRGB_r;
pixels[i].G = simpleRGB_g;
pixels[i].B = simpleRGB_b;
}
ledstrip.show(pixels);
simpleRGB_change = false;
if(debugging) Serial.println("Led update");
}
/*
//0 Default Artnet in, leds out.
//1 simpleRGB Users sets all leds to same R,G,B values
//2 RainbowFade Colorful demo animation
byte operation_mode = 0;
*/
void UpdateLeds(){
if(operation_mode = 0){
}else if (operation_mode == 1){
RGBtoLeds();
}else if (operation_mode == 2){
}
}
| true |
066072afac024f8c0260531b5f76aacfda8efaac | C++ | RonNiles/nth-binary-permutation | /nth_bit_permutation.cpp | UTF-8 | 5,083 | 3.375 | 3 | [] | no_license | /* bit permutations:
What if you took all of the possible integers with a specific number of set bits and arranged them in
ascending order? These are "binary permutations" or "bit permutations".
These routines use Pascal's triangle to get the nth bit permutation and conversely to get the
position (or rank) of a specific binary permutation.
*/
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <climits>
#include <stdexcept>
#include <bitset>
/* the maximum number of bits to be used. Pascal's triangle will be expanded according to this value */
#define MAXBITS 32
/* pascal's triangle - needed for indexing bitmap permutations */
std::vector<std::vector<unsigned> > pascalt;
void make_pascal_triangle(void) {
pascalt.clear();
pascalt.resize(MAXBITS+1);
pascalt[0].push_back(1);
for (unsigned i=1; i<=MAXBITS; ++i) {
pascalt[i].push_back(pascalt[i-1][0]);
for (unsigned j=1; j<pascalt[i-1].size(); ++j) {
/* In Pascal's triangle, each entry is the sum of the two numbers above it in the previous row */
pascalt[i].push_back(pascalt[i-1][j-1] + pascalt[i-1][j]);
}
pascalt[i].push_back(pascalt[i-1].back());
}
}
/* given a bitmap where ntotbits are set out of nsetbits, return the rank */
unsigned rank_from_permutation(unsigned bitmap, unsigned ntotbits, unsigned nsetbits) {
unsigned total = 0;
unsigned row = ntotbits;
unsigned col = row - nsetbits;
unsigned thisbit = 1 << (ntotbits-1);
for(;;) {
if (pascalt[row][col] == 1) {
break;
}
row--;
if (bitmap & thisbit) {
total += pascalt[row][col-1];
} else {
col--;
}
thisbit >>= 1;
}
return total;
}
/* given a rank from zero through (ntotbits choose nsetbits) minus 1, return the nth binary permutation
as a bitmap */
unsigned permutation_from_rank(unsigned rank, unsigned ntotbits, unsigned nsetbits) {
unsigned res = 0;
unsigned row = ntotbits;
unsigned col = row - nsetbits;
unsigned thisbit = 1 << (ntotbits-1);
for(;;) {
if (row-- == 0) break;
if (col > 0 && rank < pascalt[row][col-1]) {
--col;
} else {
if (col) rank -= pascalt[row][col-1];
res |= thisbit;
}
thisbit >>= 1;
}
return res;
}
void bit_permutation_test(void) {
/* go through all possible input values. The inner loop generates the bit permutations in order
using Sean Eron Anderson's bit-twiddling hack. Then we check that the bit permutation generates
the expected rank, and that the rank generates the expected bit permutation */
std::cout << "Testing all possible inputs for values up to 32-bits" << std::endl;
for (unsigned ntotbits = 0; ntotbits <= MAXBITS; ++ntotbits) {
for (unsigned nsetbits = 0; nsetbits <= ntotbits; ++nsetbits) {
std::cout << ntotbits << ":" << nsetbits << " bits \r" << std::flush;
std::string nd;
nd.append(ntotbits - nsetbits, '0');
nd.append(nsetbits, '1');
unsigned bitperm = (1ULL << nsetbits) - 1;
unsigned count = 0;
do {
unsigned bits = 0;
unsigned val = 1;
for (unsigned i=0; i<ntotbits; ++i) {
if (nd[ntotbits-i-1] == '1') bits += val;
val <<= 1;
}
if (bitperm != bits) throw std::runtime_error("bitperm is not equal to bits");
/* The folowing code is the "next bit permutation" routine from the "Bit Twiddling Hacks"
By Sean Eron Anderson at Stanford University */
unsigned t = bitperm | (bitperm -1);
unsigned v = bitperm;
unsigned ctz = 0;
if (v) {
v = (v ^ (v - 1)) >> 1; // Set v's trailing 0s to 1s and zero rest
while (v) {
++ctz;
v >>= 1;
}
} else {
ctz = CHAR_BIT * sizeof(v);
}
bitperm = (t+1) | (((~t & -~t) -1) >> (ctz + 1));
unsigned rankval = rank_from_permutation(bits, ntotbits, nsetbits);
if (rankval != count) throw std::runtime_error("rankval is not equal to rank");
unsigned pfr = permutation_from_rank(count, ntotbits, nsetbits);
if (pfr != bits) {
throw std::runtime_error("permutation_from_rank is not equal to bits");
}
++count;
} while(next_permutation(nd.begin(), nd.end()));
}
}
std::cout << "Test complete." << std::endl;
return;
}
int main(int argc, char *argv[]) {
try {
make_pascal_triangle();
std::cout << "The first 20 binary permutations of 5 set bits out of 8 total bits are " << std::endl;
for (unsigned i=0; i<20; ++i) {
std::cout << std::setw(5) << i+1 << ": " << std::bitset<8>(permutation_from_rank(i, 8,5)) << std::endl;
}
bit_permutation_test();
} catch (std::exception &x) {
std::cout << std::endl << x.what() << std::endl;
return 1;
}
return 0;
}
| true |
471291e7bc98c0a900fd78272217f58d555338e7 | C++ | RomeoV/FastSLAM | /cpp/fastslam1/compute_weight.h | UTF-8 | 668 | 2.515625 | 3 | [] | no_license | #ifndef COMPUTE_WEIGHT_H
#define COMPTUE_WEIGHT_H
#include <Eigen/Dense>
#include <vector>
#include "core/particle.h"
using namespace Eigen;
using namespace std;
/*!
Compute particle weight for sampling.
Uses compute_jacobians.
@param[out] particle Particle whose weight is calculated
@param[in] z vector of map features, calculated by data_associate_known
@param[in] idf vector of map features, calculated by data_associate_known, used for jacobians
@param[in] R matrix of observation noises, metres and radians
*/
double compute_weight(Particle &particle, vector<Vector2d> z, vector<int> idf, Matrix2d R);
#endif
| true |
f5d62bf9573602bb878b059febad304487061983 | C++ | EkanshdeepGupta/CppDump | /Quicksort/main.cpp | UTF-8 | 2,217 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
int countFinal = 0;
void quickSort(int *arr, int finish, int start=0) {
finish--;
int pivot = arr[finish];
int biggerIndex;
int smallerIndex;
for (int i=0; /*i<=((finish-start)/2)*/; i++) {
for (int j=start; j<=finish; j++) {
if (arr[j] >= pivot) {
biggerIndex = j;
break;
}
};
for (int j=finish-1; j>=start; j--) {
if (arr[j] <= pivot) {
smallerIndex = j;
break;
}
};
if (biggerIndex < smallerIndex) {
int temp = arr[biggerIndex];
arr[biggerIndex] = arr[smallerIndex];
arr[smallerIndex] = temp;
countFinal++;
}
else if (smallerIndex <= biggerIndex) {
break;
};
};
{
int i = 0;
while ((arr[i] <= pivot) && (i<finish)) {
i++;
};
int temp = arr[finish];
arr[finish] = arr[i];
arr[i] = temp;
countFinal++;
bool ascendingComplete1 = true;
bool ascendingComplete2 = true;
for (int j=start; j<i-1; j++) {
if (arr[j] > arr[j+1]) {
ascendingComplete1 = false;
};
};
for (int j=i+1; j<finish; j++) {
if (arr[j] > arr[j+1]) {
ascendingComplete2 = false;
};
};
if (!(ascendingComplete1)) {
quickSort(arr, i, start);
};
if (!(ascendingComplete2)) {
quickSort(arr, finish+1, i+1);
};
};
};
int main() {
int arr[1000];
ifstream file("./Untitled 1.csv");
for (int i=0; i<1000; i++) {
file >> arr[i];
}
quickSort(arr, 1000);
cout << "FINAL: " << endl;
for (int i=0; i<1000; i++) {
cout << arr[i] << " \t";
};
cout << endl << countFinal << " swaps made.";
file.close();
/*
int arr[4] = {1, 3, 2, 4};
quickSort(arr, 4);
cout << "FINAL: " << endl;
for (int i=0; i<4; i++) {
cout << arr[i] << "\t";
};
cout << endl << countFinal;*/
};
| true |
bd22150ebdeb819400fa9a7d40b478d9473afd30 | C++ | asarria48/1repos | /22-10-2021-operators/logical_operators.cpp | UTF-8 | 564 | 3.078125 | 3 | [] | no_license | #include <iostream>
int main(void)
{
std::cout << ((5==5) && (3>6)) <<std::endl;
std::cout << ((5==5) || (3>6)) <<std::endl;
int flag = (5<4) ? -1 : 32;
std::cout << flag <<std::endl;
int m = 3, n = 17, k = 0;
k = m & n;
std::cout << k <<std::endl;
k = m | n;
std::cout << k <<std::endl;
k = m << 2;
std::cout << k <<std::endl;
k = m >> 2;
std::cout << k <<std::endl;
// 4 = 0100, 8 = 1000
// 4&8 = 0100&1000 = 0000 = 0
// 4|8 = 0100&1000 = 1100 = 12
// 00010 & 10001 = 00000 = 0
// 00010 | 10001 = 10011 = 19
return 0;
}
| true |
9482eaac84b02a714705b3c05b3474eed8019bef | C++ | Eslarian/CPP_Ass1 | /maze.h | UTF-8 | 1,812 | 2.890625 | 3 | [] | no_license | /******************************************************************************
* COSC1254 - Programming Using C++
* Semester 2 2016 - Assignment #1
* Full Name : Emile Antognetti
* Student Number : s3488934
* Course Code : COSC1254_1650
* Program Code : BP094
*****************************************************************************/
using namespace std;
#define MAGNIFY 100
#define DEFAULT_W 10
#define DEFAULT_H 10
#include "cell.h"
typedef std::chrono::high_resolution_clock myclock;
typedef struct Edge
{
Cell source;
Cell destination;
}Edge;
class Maze
{
friend class Cell;
public:
//Maze metainfo
int width;
int height;
int numEdges;
unsigned long seed;
/*The positions respectively are left, right, up and down
These are used to determined the coordinates of a cell's neighbour*/
int xDirs[NUM_DIRS] = {-1,1,0,0};
int yDirs[NUM_DIRS] = {0,0,-1,1};
/*These are used for determining the positions of an edge(wall)
relative to a cell*/
int xSourceDirs[NUM_DIRS] = {0,1,0,0};
int ySourceDirs[NUM_DIRS] = {0,0,0,1};
int xDestDirs[NUM_DIRS] = {0,1,1,1};
int yDestDirs[NUM_DIRS] = {1,1,0,1};
//Opposite directions
int oppoDirs[NUM_DIRS] = {1,0,3,2};
//Data structures
Cell entrance;
Cell exit;
vector<vector<Cell>> map;
vector<Edge> edges;
//Functions
bool load_binary(string filename);
bool save_svg(string filename);
bool save_binary(string filename);
bool is_in(Cell checkCell);
bool is_in(int x, int y);
bool on_border(Cell checkCell);
bool compare_edge(Edge firstEdge, Edge secondEdge);
bool validate_edge(Edge chkEdge);
void make_gateways(Cell gateway);
void remove_edge(Edge deadEdge);
void gen_maze();
Maze(int width, int height, int seed);
Maze();
friend class Cell;
};
| true |
09b1a7349cd15af75390f91ddf305f6147dfeb1c | C++ | jmpcosta/loc | /code/statistics/fileStatistics.hh | UTF-8 | 2,045 | 2.828125 | 3 | [
"MIT"
] | permissive | // *****************************************************************************************
//
// File description:
//
// Author: Joao Costa
// Purpose: Provide the definitions/declarations for file code statistics
//
// *****************************************************************************************
#ifndef LOC_FILE_STATISTICS_HH_
#define LOC_FILE_STATISTICS_HH_
// *****************************************************************************************
//
// Section: Import headers
//
// *****************************************************************************************
// Import C++ system headers
//#include <cstdint>
#include <string>
// Import application headers
#include "trace_macros.hh"
#include "statistics/statistics.hh"
// *****************************************************************************************
//
// Section: Function declaration
//
// *****************************************************************************************
/// @brief Class responsible for holding statistics for a file
class fileStatistics
{
public:
/// @brief Class constructor
fileStatistics ( const void * pf, statistics & s ) : iStats( s ) { p_iFile = pf; }
/// @brief Class constructor
fileStatistics ( const fileStatistics & fs ) : iStats( fs.iStats ) { p_iFile = fs.p_iFile; }
/// @brief Class destructor
~fileStatistics () {}
/// @brief Get a reference to a statistics
/// @return The language statistics object reference
statistics & getStatistics ( void ) { return iStats; }
/// @brief Add statistics to the current file
void addStatistics ( statistics & s ) { iStats.add( s ); }
/// @brief Compare the language type, i.e. the language ID
/// @return True if language IDs are equal. False otherwise
bool operator==( const void * key ) { return (key == p_iFile); }
private:
const void * p_iFile; ///< File object
statistics iStats; ///< File statistics
TRACE_CLASSNAME_DECLARATION
};
#endif // LOC_FILE_STATISTICS_HH_
| true |
d900796a4a07b77903ff40598949aa10bbf13a57 | C++ | KingTreeS/CodingInterview | /Algorithm17/Algorithm17.cpp | UTF-8 | 854 | 3.25 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
void PrintNum(const char* num)
{
while (*num == '0')
{
num++;
}
while (*num != '\0')
{
std::cout << *num++;
}
std::cout << "\n";
}
void PrintToMaxCore(char* num, int n, int index)
{
if (index == n)
{
PrintNum(num);
return;
}
for (int i = 0; i <= 9; i++)
{
num[index] = i + '0';
PrintToMaxCore(num, n, index + 1);
}
}
//全排列
void Print1ToMaxOfNDigits_1(int n)
{
if (n < 1)
{
return;
}
char* num = new char[n + 1];
num[n] = '\0';
PrintToMaxCore(num, n, 0);
}
// ====================测试代码====================
void Test(int n)
{
printf("Test for %d begins:\n", n);
Print1ToMaxOfNDigits_1(n);
//Print1ToMaxOfNDigits_2(n);
printf("\nTest for %d ends.\n", n);
}
int main(int argc, char* argv[])
{
Test(1);
Test(2);
Test(3);
Test(0);
Test(-1);
return 0;
} | true |
eab37f63355b96ecbfea4274e01d22b20ce638d5 | C++ | semenovf/pfs | /src/pfs/io/exception.cpp | UTF-8 | 916 | 2.640625 | 3 | [] | no_license | #include "pfs/io/exception.hpp"
namespace pfs {
namespace details {
char const * io_category::name () const noexcept
{
return "io_category";
}
std::string io_category::message (int ev) const
{
switch (ev) {
case static_cast<int>(io_errc::success):
return "no error";
case static_cast<int>(io_errc::operation_in_progress):
return "operation in progress";
case static_cast<int>(io_errc::connection_refused):
return "connection refused";
case static_cast<int>(io_errc::bad_file_descriptor):
return "bad file descriptor";
case static_cast<int>(io_errc::stream):
return "stream error";
case static_cast<int>(io_errc::timeout):
return "timed out";
default: return "unknown I/O error";
}
}
} // details
pfs::error_category const & io_category ()
{
static details::io_category instance;
return instance;
}
} // pfs
| true |
ec9b45fa7c9e2229aa99799d2a5bae8bd65d7dbd | C++ | leninhasda/competitive-programming | /acm.hdu/solved/LoestBit.cpp | UTF-8 | 397 | 2.609375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int a[100000],ab[10]={1,2,4,8,16,32,64,128,512};
int n,div,mod,m,i;
while(cin>>n)
{
if(!n)
break;
div=0;mod=0;m=0;
do
{
div=n/2;
mod=n%2;
a[m]=mod;
m++;
n=div;
}while(div!=0);
for(i=0;i<m;i++)
{
if(a[i]==1)
{
cout<<ab[i]<<endl;
break;
}
}
}
return 0;
} | true |
00bec1fbb6be648d58f7233d740caaa0c173fadf | C++ | nicowxd/Competitive-Programming | /UVA/10664.cpp | UTF-8 | 772 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
string s;
scanf("%d ", &n);
while(n--)
{
int k, v[25], i = 1, sum = 0;
bool memo[30][210];
getline(cin, s);
stringstream ss(s);
while(ss >> k)
{
v[i++] = k;
sum += k;
}
if (sum&1)
puts("NO");
else
{
int ans = sum / 2;
for (int j = 1; j <= sum; j++)
memo[0][j] = 0;
for (int j = 0; j < i; j++)
memo[j][0] = 1;
for (int j = 1; j < i; j++)
{
for (int k = 1; k <= sum; k++)
{
memo[j][k] = memo[j-1][k];
if (k >= v[j])
memo[j][k] |= memo[j-1][k-v[j]];
}
}
if (memo[i-1][ans])
puts("YES");
else
puts("NO");
}
}
cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n";
return 0;
}
| true |
91fe498bcde1f6713c403b97c23d8d5e769b9f7a | C++ | AlexDevyatov/ACM-Contests-Data | /NCPC/2014/ncpc2014/basincity/submissions/accepted/pa_simple.cc | UTF-8 | 1,620 | 2.625 | 3 | [] | no_license | // This solution is O*(n*3^k)
#include <cassert>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <set>
using namespace std;
typedef pair<int,int> pii;
typedef set<pii> pq;
typedef vector<int> vi;
vi adj[120];
int neigh[120][120];
void discard(int V, vi °) {
deg[V] = -1;
for (int W: adj[V]) if (deg[W] > 0) --deg[W];
}
void take(int U, vi °) {
deg[U] = -1;
for (int V: adj[U]) if (deg[V] > 0) discard(V, deg);
}
vi nodes;
int solve(int i, vi deg, int goal) {
if (goal == 0 || i < 0) return 0;
int U = nodes[i];
if (deg[U] == -1) return solve(i-1, deg, goal);
vi ndeg = deg;
take(U, ndeg);
int val = 1+solve(i-1, ndeg, goal-1), rem = deg[U]-1;
if (val >= goal) return val;
for (int V: adj[U]) {
if (deg[V] > 0 && rem > 0) {
--rem;
ndeg = deg;
take(V, ndeg);
val = max(val, 1+solve(i-1, ndeg, goal-1));
if (val >= goal) return val;
discard(V, deg);
}
}
return val;
}
int seen[120];
void dfs(int u, vi &vis) {
seen[u] = true;
for (int v: adj[u]) if (!seen[v]) dfs(v, vis);
vis.push_back(u);
}
int main(void) {
int k, n;
scanf("%d%d", &k, &n);
if (n >= 5*(k-1)+1) {
printf("possible\n");
return 0;
}
vi deg(n+1);
for (int i = 1; i <= n; ++i) {
int d;
scanf("%d", &d);
for (int j= 0; j < d; ++j) {
int a;
scanf("%d", &a);
adj[i].push_back(a);
}
deg[i] = d;
}
int ms = 0;
memset(seen, 0, sizeof(seen));
for (int i = 1; i <= n; ++i) {
if (!seen[i]) {
nodes.clear();
dfs(i, nodes);
ms += solve(nodes.size()-1, deg, k-ms);
}
}
printf("%spossible\n", ms >= k ? "" : "im");
return 0;
}
| true |
1339de3005f108e2ef3f62099329d3d12a390ced | C++ | Junjie-Feng/Previous-Projects | /C++Projects/Homework-9/Homework-9/Display_JunjieFeng.cpp | UTF-8 | 1,354 | 3.046875 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<vector>
#include<cstring>
#include"Package_JunjieFeng.h"
#include"TwoDayPackage_JunjieFeng.h"
#include"OvernightPackage_JunjieFeng.h"
using namespace std;
void Display(Package *BasePackage)
{
static int package_index = 1;//count the package number
cout << "Package " << package_index++<<endl<<endl;
cout << "Sender :" << endl//print sender
<< BasePackage->getsendername() << endl//print sender name
<< BasePackage->getsenderaddress() << endl//print sender address
<< BasePackage->getsendercity() << ", " << BasePackage->getsenderstate() << " " << BasePackage->getsenderzipcode() << endl << endl;//print sender address
cout<<"Recipient :"<<endl//print recipient
<< BasePackage->getrecipientname() << endl//print recipient name
<< BasePackage->getrecipientaddress() << endl//print recipient address
<< BasePackage->getrecipientcity() << ", " << BasePackage->getrecipientstate() << " " << BasePackage->getrecipientzipcode() << endl << endl;//print recipient address
cout << "Weight of package : " << BasePackage->getweight() << " ounces" << endl//print package weight
<< "Type of delivery : " << BasePackage->type_name() << endl//print the delivery type name
<< "Cost of package : $" << BasePackage->calculateCost() << endl << endl;//print the cost of the package
} | true |
726edfeeb68024cd5f105e7859c56a56fc52e605 | C++ | alisn1024/3d-cube | /src/data_types/MatrixTemplate.h | UTF-8 | 4,720 | 3.375 | 3 | [
"MIT"
] | permissive | #ifndef MatrixTemplate_class
#define MatrixTemplate_class
#include <assert.h>
#include <iostream>
#include <vector>
#include <memory>
template <typename T>
class _Matrix{
private:
int width;
int height;
std::vector<std::vector<T>> cells;
public:
template <typename A>
_Matrix(int width,int height,A cellDefaultValue)
:
width(width),
height(height)
{
int i,j;
for(i=0;i<width;i++){
cells.emplace_back(std::vector<T>());
for(j=0;j<height;j++){
cells.at(i).emplace_back(T(cellDefaultValue));
}
}
}
template <typename A>
_Matrix(int width,int height,std::vector<std::vector<A>> initialCellValue)
:
width(width),
height(height)
{
this->cells = initialCellValue;
}
template <typename A>
_Matrix<T>& operator=(_Matrix<A> rhs){
width = rhs.width;
height = rhs.height;
cells.erase(cells.begin(),cells.end());
for(int i=0;i<width;i++){
cells.emplace_back(std::vector<T>());
for(int j=0;j<height;j++){
cells.at(i).emplace_back(T(rhs.cells.at(i).at(j)));
}
}
return *this;
}
template <typename A>
_Matrix<T> operator+(_Matrix<A> rhs){
assert(rhs.width==width);
assert(rhs.height==height);
std::vector<std::vector<T>> resultsCell;
for(int i=0;i<width;i++){
resultsCell.emplace_back(std::vector<T>());
for(int j=0;j<height;j++){
resultsCell.at(i).emplace_back(T(rhs.cells.at(i).at(j)) + cells.at(i).at(j));
}
}
_Matrix<T> result(width,height,resultsCell);
return result;
}
template <typename A>
_Matrix<T>& operator+=(_Matrix<A> rhs){
this = this + rhs;
return *this;
}
template <typename A>
_Matrix<T> operator-(_Matrix<A> rhs){
assert(rhs.width==width);
assert(rhs.height==height);
std::vector<std::vector<T>> resultsCell;
for(int i=0;i<width;i++){
resultsCell.emplace_back(std::vector<T>());
for(int j=0;j<height;j++){
resultsCell.at(i).emplace_back(cells.at(i).at(j) - T(rhs.cells.at(i).at(j)));
}
}
_Matrix<T> result(width,height,resultsCell);
return result;
}
template <typename A>
_Matrix<T>& operator-=(_Matrix<A> rhs){
this = this - rhs;
return *this;
}
template <typename A>
_Matrix<T> operator*(_Matrix<A> rhs){
assert(rhs.height==width);
auto finalWidth = rhs.width;
auto finalHeight = height;
std::vector<std::vector<T>> resultCells;
int i,j,k,p;
for(i=0;i<finalWidth;i++){
resultCells.emplace_back(std::vector<T>());
for(j=0;j<finalHeight;j++){
resultCells.at(i).emplace_back(0);
for(k=0,p=0;k<width;k++,p++){
resultCells.at(i).at(j) += cells.at(k).at(j) * T(rhs.cells.at(i).at(p));
}
}
}
_Matrix<T> resultMatrix(finalWidth,finalHeight,resultCells);
return resultMatrix;
}
template <typename A>
_Matrix<T>& operator*=(_Matrix<A> rhs){
this = this * rhs;
return *this;
}
bool operator==(_Matrix<T> rhs){
if(rhs.width!=width || rhs.height!=height){
return false;
}
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
if(rhs.get(i,j)!=get(i,j)){
return false;
}
}
}
return true;
}
bool operator!=(_Matrix<T> rhs){
return !(this==rhs);
}
int getWidth(){
return width;
}
int getHeight(){
return height;
}
void print(){
std::cout<<"---Printing matrix----"<<std::endl;
std::cout<<"Width:"<<width<<std::endl;
std::cout<<"Height:"<<height<<std::endl;
for(int i=0;i<height;i++){
for(int j=0;j<width;j++){
std::cout<<" "<<cells.at(j).at(i)<<" ";
}
std::cout<<std::endl;
}
std::cout<<"-----------------------"<<std::endl;
}
T get(int x,int y){
assert(x<width);
assert(y<height);
return this->cells.at(x).at(y);
}
void set(int x,int y,T value){
assert(x<width);
assert(y<height);
this->cells.at(x).at(y) = value;
}
_Matrix<T> clone(){
std::vector<std::vector<T>> cellsCopy;
int i,j;
for(i=0;i<width;i++){
cellsCopy.emplace_back(std::vector<T>());
for(j=0;j<height;j++){
cellsCopy.at(i).emplace_back(cells.at(i).at(j));
}
}
return _Matrix<T>(width,height,cellsCopy);
}
};
using MatrixInt = _Matrix<int>;
using MatrixFloat = _Matrix<float>;
using MatrixDouble = _Matrix<double>;
#endif | true |
455c805eead3e6f2f924ff4fd724b80b92199e6e | C++ | mclumd/erewhon_systems | /godel/src/search/cg_cache.cc | UTF-8 | 4,308 | 2.796875 | 3 | [] | no_license | #include "cg_cache.h"
#include "causal_graph.h"
#include "globals.h"
#include "state.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
const int CGCache::NOT_COMPUTED;
CGCache::CGCache() {
cout << "Initializing heuristic cache... " << flush;
int var_count = g_variable_domain.size();
CausalGraph *cg = g_causal_graph;
// Compute inverted causal graph.
depends_on.resize(var_count);
for (int var = 0; var < var_count; var++) {
// This is to be on the safe side of overflows for the multiplications below.
assert(g_variable_domain[var] <= 1000);
const vector<int> &succ = cg->get_successors(var);
for (int i = 0; i < succ.size(); i++) {
// Ignore arcs that are not part of the reduced CG:
// These are ignored by the CG heuristic.
if (succ[i] > var)
depends_on[succ[i]].push_back(var);
}
}
// Compute transitive close of inverted causal graph.
// This is made easier because it is acyclic and the variables
// are in topological order.
for (int var = 0; var < var_count; var++) {
int direct_depend_count = depends_on[var].size();
for (int i = 0; i < direct_depend_count; i++) {
int affector = depends_on[var][i];
assert(affector < var);
depends_on[var].insert(depends_on[var].end(),
depends_on[affector].begin(),
depends_on[affector].end());
}
sort(depends_on[var].begin(), depends_on[var].end());
depends_on[var].erase(unique(depends_on[var].begin(), depends_on[var].end()),
depends_on[var].end());
}
/*
cout << "Dumping transitive closure of inverted causal graph..." << endl;
for(int var = 0; var < var_count; var++) {
cout << var << ":";
for(int i = 0; i < depends_on[var].size(); i++)
cout << " " << depends_on[var][i];
cout << endl;
}
*/
const int MAX_CACHE_SIZE = 1000000;
cache.resize(var_count);
helpful_transition_cache.resize(var_count);
for (int var = 0; var < var_count; var++) {
int required_cache_size = g_variable_domain[var] * (g_variable_domain[var] - 1);
bool can_cache = (required_cache_size <= MAX_CACHE_SIZE);
if (can_cache) {
for (int i = 0; i < depends_on[var].size(); i++) {
int relevant_var = depends_on[var][i];
if (cache[relevant_var].empty()) {
// It is possible that var depends on a variable var_i
// that is not cached: this is the case, if the
// required_cache_size of var_i exceeds MAX_CACHE_SIZE
// (note: the domain of var_i contributes quadratically to
// the required_cache_size of var_i while it contributes
// only linearly to the required_cache_size of var)
can_cache = false;
break;
}
required_cache_size *= g_variable_domain[relevant_var];
if (required_cache_size > MAX_CACHE_SIZE) {
can_cache = false;
break;
}
}
}
if (can_cache) {
// cout << "Cache for var " << var << ": "
// << required_cache_size << " entries" << endl;
cache[var].resize(required_cache_size, NOT_COMPUTED);
helpful_transition_cache[var].resize(required_cache_size, 0);
}
}
cout << "done!" << endl;
}
CGCache::~CGCache() {
}
int CGCache::get_index(int var, const State &state,
int from_val, int to_val) const {
assert(is_cached(var));
assert(from_val != to_val);
int index = from_val;
int multiplier = g_variable_domain[var];
for (int i = 0; i < depends_on[var].size(); ++i) {
int dep_var = depends_on[var][i];
index += state[dep_var] * multiplier;
multiplier *= g_variable_domain[dep_var];
}
if (to_val > from_val)
--to_val;
index += to_val * multiplier;
assert(index >= 0 && index < cache[var].size());
return index;
}
| true |
841c93ebda9595eb26cfd1623f476565c4845597 | C++ | Angus-Leung/A4 | /Queue.cc | UTF-8 | 5,703 | 3.609375 | 4 | [] | no_license | #include "Queue.h"
//Default constructor
Queue::Queue() : head(0){
}
//Copy constructor
Queue::Queue(Queue &origQueue) {
head = 0;
Node *origCurrNode;
origCurrNode = origQueue.head;
while (origCurrNode != 0) {
*this += origCurrNode->data;
origCurrNode = origCurrNode->next;
}
}
//Destructor
Queue::~Queue() {
Node *currNode, *nextNode;
currNode = head;
while (currNode != 0) {
nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
}
/* Function: overloaded addition assignment operator */
/* in: Pointer pirate to be added to the Queue */
/* out: Reference to the queue (cascading) */
/* Purpose: Adds the pirate pointer to the end of the Queue */
Queue& Queue::operator+=(Pirate* newPirate) {
Node *newNode;
Node *currNode, *prevNode;
newNode = new Node;
newNode->data = newPirate;
newNode->prev = 0;
newNode->next = 0;
prevNode = 0;
currNode = head;
while (currNode != 0) {
prevNode = currNode;
currNode = currNode->next;
}
if (prevNode == 0) {
head = newNode;
}
else {
prevNode->next = newNode;
newNode->prev = prevNode;
}
newNode->next = currNode;
if (currNode != 0) {
currNode->prev = newNode;
}
return *this;
}
/* Function: pop */
/* out: Int indicating success or failure */
/* Purpose: Removes the pirate at the front of the Queue */
void Queue::pop() {
if (head != 0)
*(this) -= head->data;
}
/* Function: front */
/* out: Pointer to the Pirate at the front of the Queue */
/* Purpose: Returns a pointer to the pirate at the front of */
/* the queue */
Pirate* Queue::front() {
return head->data;
}
/* Function: overloaded Negation operator */
/* out: Boolean indicating empty or non-empty */
/* Purpose: Indicates whether or not the Queue is empty */
bool Queue::operator!() {
if (head == 0)
return false;
else
return true;
}
/* Function: overloaded subtraction assignment operator */
/* in: A pirate pointer to be removed */
/* Purpose: Removes a pirate pointer from the Queue */
Queue& Queue::operator-=(Pirate* piratePtr) {
Node *currNode, *prevNode;
prevNode = 0;
currNode = head;
while (currNode != 0) {
if (currNode->data->getId() == piratePtr->getId())
break;
prevNode = currNode;
currNode = currNode->next;
}
if (currNode == 0)
return *this;
if (prevNode == 0) {
head = currNode->next;
if (head != 0)
head->prev = 0;
}
else {
prevNode->next = currNode->next;
if (currNode->next != 0)
currNode->next->prev = prevNode;
}
delete currNode;
return *this;
}
/* Function: getPirateSpace */
/* in: ID of a pirate */
/* out: The space of a pirate with matching ID */
/* Purpose: Returns the space of a pirate (this is used */
/* when removing a pirate, in order to increase */
/* the space that is left in a cell after a pirate */
/* is removed from it */
int Queue::getPirateSpace(int pirateId) {
Node *currNode;
currNode = head;
while (currNode != 0) {
if (currNode->data->getId() == pirateId)
return currNode->data->getSpace();
currNode = currNode->next;
}
return 0;
}
/* Function: find */
/* in: ID of a pirate */
/* out: A pointer to the pirate with a matching ID */
/* Purpose: Returns a pointer to the pirate that is being */
/* searched for */
/* (for deallocation purposes in the */
/* removePirate() function in the Brig) */
Pirate* Queue::find(int pirateId) {
Node *currNode;
currNode = head;
while (currNode != 0) {
if (currNode->data->getId() == pirateId)
return currNode->data;
currNode = currNode->next;
}
return 0;
}
/* Function: deleteData */
/* Purpose: Deletes the data contained in every Node in */
/* the Queue. This cannot be in the Queue's */
/* destructor because the temporary queue in */
/* the printBrig function calls the destructor */
/* and that queue should not be deleting the data */
void Queue::deleteData() {
Node *currNode, *nextNode;
currNode = head;
while (currNode != 0) {
nextNode = currNode->next;
delete currNode->data;
currNode = nextNode;
}
}
/* Function: overloaded subscript operator */
/* in: Index of the queue */
/* out: A pointer to the pirate at that index */
/* Purpose: Returns a pointer to a pirate at an index */
Pirate* Queue::operator[](int index) {
Node *currNode;
int currIndex = 0;
currNode = head;
while (currNode != 0) {
if (currIndex == index) {
return currNode->data;
}
currNode = currNode->next;
currIndex += 1;
}
return 0;
} | true |
47298ef7f4cb23d17cccd1f483747620fbabce27 | C++ | YakirPinchas/C-Project | /Reversi-master/src/Server/ReversiServer.cpp | UTF-8 | 4,510 | 3 | 3 | [] | no_license | /*
* ReversiServer.cpp
*
* Created on: Nov 30, 2017
* Author: avi simson & yakir pinchas
* Avi id: 205789100
* Yakir: 203200530
*/
#include "ReversiServer.h"
#define THREADSSIZE 5
//constructor to server class, gets a port and update port in server.
//constructor initialize serverSocket into 0.
ReversiServer :: ReversiServer(int port1) {
threads = new ThreadPool(THREADSSIZE);
serverSocket = 0;
port = port1;
handler = new HandleClient();
cout << "Server initialized through constructor" << endl;
}
//constructor that gets a name of a file and read the port from it.
ReversiServer :: ReversiServer(string filename) {
threads = new ThreadPool(THREADSSIZE);
handler = new HandleClient();
serverSocket = 0;
string buffer;
ifstream config;
config.open(filename.c_str()); //open file of ip and port
if(!config) {
cout << "Can't open file, aborting";
exit(1);
}
while(!config.eof()) { //read every line until end of file
config >> buffer;
if(buffer == "Port") { // if port line
config >> buffer;
config >> buffer;
port = atoi(buffer.c_str());
return ;
}
}
config.close();
cout << "Server initialized through constructor" << endl;
}
//function opens socket in server and starts listening to clients.
//func opens threads of games and client connections to server.
void ReversiServer :: start() {
//cleaning buffer (put zeros in all buffer array)
//Creating the socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == -1) { //opening socket in server failed.
throw "Error opening socket";
}
//Creating socket address variable for binding
struct sockaddr_in serverAddress;
//initializing it to 0's
bzero((void *) &serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
//Gets connections from anything
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(port);
//binding
if (bind(serverSocket, (struct sockaddr *) &serverAddress,
sizeof(serverAddress)) == -1) { //binding fail.
throw "Error on binding";
}
//start listening for clients
listen(serverSocket, MAX_CLIENTS);
int rc = pthread_create(&mainThread,
NULL, &ClientConnections, (void*)this);
if (rc) { //check if thread was created.
cout << "Error: unable to create main thread, " << rc << endl;
exit(-1);
}
string str;
while(str != "exit") {
cout << "Enter exit to close server" << endl;
cin >> str;
}
stop();
}
//function gets ReversiServer member and connects between clients to server.
void* ReversiServer :: ClientConnections(void* server) {
ReversiServer* rs = (ReversiServer*)server;
//Server start on trying to connects clients and start games.
int countOfClients = 0;
//create a thread of connecting clients to server.
struct Details* details = (struct Details*) malloc(sizeof(struct Details));
struct sockaddr_in clientAddress;
socklen_t clientAddressLen = sizeof(clientAddress);
vector<Game>* vec = new vector<Game>();
Command* commandsOfClient = new DirectorCommand(vec);
details->commandOfClient = commandsOfClient;
while (true) {
cout << "Waiting for connections" << endl;
//Accepting first client
int client_sd = accept(rs->getServerSocket(),
(struct sockaddr *) &clientAddress,
&clientAddressLen);
details->clientSocket = client_sd;
countOfClients++;
cout << "Client number " << countOfClients << " has entered!" << endl;
//if have problem in accepting client close the server
if (client_sd == -1) { //error accepting client-skip to next one.
cout << "Error on accept client: " << countOfClients << endl;
countOfClients--;
continue;
}
//handle client to join/start game.
Task* task = new Task(rs->getHandler()->InitialClientServerConversation, (void*)details);
rs->getThreads()->addTask(task);
}
}
//function closes/deletes all open threads, server socket and all helpers to reversi server class.
void ReversiServer :: stop() {
threads->terminate(); //kill all threads.
close(serverSocket); //close socket.
pthread_cancel(mainThread); // close thread of -while true loop.
} | true |
26aeee33071405f3a6b7c507556443b01976a527 | C++ | hiro-tacky/practice | /ABC/171/B.cpp | UTF-8 | 481 | 2.75 | 3 | [] | no_license | //ABC171
#include <iostream>
#include <vector>
#include <utility>
#include <climits>
#include <random>
#include <queue>
#include <iomanip>
#include <algorithm>
#include <complex>
#include <string>
using namespace std;
int main(){
int n, k, sum=0;
cin >> n >> k;
vector<int> v(n);
for(int i=0; i<n; i++){
cin >> v.at(i);
}
sort(v.begin(), v.end());
for(int i=0; i<k; i++){
sum += v.at(i);
}
cout << sum << endl;
return 0;
} | true |
5d15da600185ea73970ebf6221a1afd9c59adaa5 | C++ | michaels729/ray-tracer | /RayTracer.cpp | UTF-8 | 3,257 | 2.796875 | 3 | [] | no_license | /*
* RayTracer.cpp
*
* Created on: Sep 29, 2016
* Author: mbs729
*/
#include "RayTracer.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include "geo/Intersection.h"
#include "geo/Point.h"
#include "geo/Vector.h"
RayTracer::RayTracer(int maxDepth, Primitive &primitive,
std::vector<Light*> lights) :
maxDepth(maxDepth), primitive(primitive), lights(lights) {
}
RayTracer::~RayTracer() {
}
void RayTracer::trace(const Ray &ray, Color *color) {
trace(ray, 0, color);
}
void RayTracer::trace(const Ray &ray, int depth, Color *color) {
float thit;
Intersection in;
BRDF brdf = { Color(0, 0, 0), Color(0, 0, 0), Color(0, 0, 0), Color(0, 0, 0),
0, Attenuation() };
if (depth >= maxDepth || !primitive.intersect(ray, &thit, &in)) {
color->setColor(0, 0, 0);
return;
}
in.primitive->getBRDF(in.localGeo, &brdf);
*color = brdf.ka + brdf.ke;
for (Light *light : lights) {
Ray lray = { Point(), Vector(), 0, 0 };
Color lcolor;
light->generateLightRay(in.localGeo, &lray, &lcolor);
if (!primitive.intersectP(lray)) {
Color tempColor = *color;
Color shade = shading(ray, &in.localGeo, &brdf, lray, &lcolor);
*color = tempColor + shade;
}
}
if (brdf.ks.r > 0 || brdf.ks.g > 0 || brdf.ks.b > 0) {
Ray reflectRay = createReflectRay(in.localGeo, ray);
Color reflectColor = Color();
trace(reflectRay, depth + 1, &reflectColor);
Color fadedReflectColor = reflectColor * brdf.ks;
*color = *color + fadedReflectColor;
}
}
Color RayTracer::shading(const Ray &eyeRay, LocalGeo *lg, BRDF *brdf, Ray &lray,
Color *lcolor) {
float atten = 1.0f;
// Check if light source is directional by check if if t_max is infinity.
// If the light source is a point light, then calculate the attentuation,
// otherwise use an attenuation of 1.
if (lray.t_max < std::numeric_limits<float>::infinity()) {
atten = brdf->atten.calc(lray.t_max);
}
Color lightColor = *lcolor;
// Need to calculate dot products with normalized direction.
Vector lightDir = lray.dir.normalized();
Vector objNormal = lg->normal;
// Lambert calculation for diffuse term
Color kd = brdf->kd;
float nDotL = objNormal.dot(lightDir);
Color lambert = kd * lightColor * std::max(nDotL, 0.0f);
// Phong calculation for specular term.
Vector eyeDirn = (eyeRay.pos - lg->pos).normalized();
Vector halfVec = (lray.dir + eyeDirn).normalized();
float nDotH = objNormal.dot(halfVec);
Color ks = brdf->ks;
float shininess = brdf->shininess;
Color phong = ks * lightColor * pow(std::max(nDotH, 0.0f), shininess);
return (lambert + phong) * atten;
}
Ray RayTracer::createReflectRay(LocalGeo &lg, const Ray &ray) {
float epsilon = 0.0001f;
// ray.dir is negated for dot product because it is directed *toward* the
// local geometry.
float lDotN = -ray.dir.dot(lg.normal);
Vector direction = ray.dir + lg.normal * 2 * lDotN;
direction.normalize();
// Offset the position to prevent self-intersection.
Point position = lg.pos + direction * epsilon;
// Don't negate ray.dir here for the same reason stated above.
Ray reflect = { position, direction, 0.0f,
std::numeric_limits<float>::infinity() };
return reflect;
}
| true |
deb3070c3000b6c3e214780d78bc325300323e61 | C++ | Squareys/pyromania | /2D/src/MapConv/Main.cpp | UTF-8 | 4,410 | 2.71875 | 3 | [
"MIT"
] | permissive |
#define ALLEGRO_NO_MAGIC_MAIN
#define ALLEGRO_USE_CONSOLE
#include <allegro.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
bool operator== (string s1, string s2){
return (strcmp(s1.c_str(), s2.c_str()) == 0);
}
string itostr(int i){
stringstream out;
out << i;
string s = out.str();
return s;
}
int strtoi(string s){
stringstream out;
out << s;
int i ;
out >> i;
return i;
}
void readmap (string data, int size, int* tiles){
string buf = "";
int num = 0;
unsigned int i;
for (i = 0; i < data.length(); i++){
if (data.substr(i, 1) == ","){
tiles[num] = strtoi(buf);
buf = "";
num++;
continue;
}
buf += data.substr(i, 1);
}
/* got to add the last number which doesn't end with ',' */
buf += data.substr(i, 1);
num ++;
if (num < size)
cout << "Didn't find enough data! (found " << num << "/" << size << ")"<< endl;
return;
}
int main (int argc, char* arg[]){
allegro_init();
/*
if (argc < 2){
cout << "Error: to few arguments!" << endl;
return 1;
}
if (!exists(arg[1])){
cout << "Error: " << arg[1] << " doesn't exist!" << endl;
return 1;
}
*/
cout << "Opening " << "Map.dat" /*arg[1]*/ << "..." << endl;
PACKFILE* file = pack_fopen("Map.dat", "rb");
if (!file) {
cout << "Error: Couldn't read Map.dat!" << endl;
}
char buf[5000];
if (buf == NULL) cout << "Error: Unable to create Buffer!" << endl;
string line;
cout << "Reading..." << endl;
while (pack_fgets(buf, sizeof(buf), file)) {
#ifdef DEBUG
cout << "Debug: Started new Line!" << endl;
#endif
line = buf;
int* walkables;
int walknum = 0;
int* destructables;
int destrnum = 0;
if (line.substr(0, 8) == "walknum:"){
walknum = strtoi(line.substr(8, line.length()));
cout << "Map: Num of walkable tiles is " << walknum << " !" << endl;
}
if (line.substr(0, 9) == "destrnum:"){
destrnum = strtoi(line.substr(9, line.length()));
cout << "Map: Num of destructable tiles is " << destrnum << " !" << endl;
}
if (line.substr(0, 7) == "walkon:"){
walkables = new int[walknum];
readmap(line.substr(7, line.length()), walknum, walkables);
cout << "Map: Walkable tiles part found!" << endl;
}
if (line.substr(0, 9) == "destruct:"){
destructables = new int[destrnum];
readmap(line.substr(9, line.length()), destrnum, destructables);
cout << "Map: Destructable tiles part found!" << endl;
}
if (line.substr(0, 5) == "Name:"){
string name = line.substr(5, line.length());
string filename = name + ".map";
cout << "Info: Found new map! Name is \"" << name << "\"!" << endl;
PACKFILE* map = pack_fopen(filename.c_str(), "wb");
int w, h;
int* FG;
int* BG;
int* MG;
while (pack_fgets(buf, sizeof(buf), file)) {
line = buf;
if (line.substr(0, 3) == "w: "){
w = strtoi(line.substr(3, line.length()));
cout << name << ": Width is " << w << "!" << endl;
}
if (line.substr(0, 3) == "h: "){
h = strtoi(line.substr(3, line.length()));
cout << name << ": Height is " << h << "!" << endl;
}
if (line.substr(0, 3) == "FG:"){
FG = new int[w*h];
readmap(line.substr(3, line.length()), w*h, FG);
cout << name << ": Front part found!" << endl;
}
if (line.substr(0, 3) == "MG:"){
MG = new int [w*h];
readmap(line.substr(3, line.length()), w*h, MG);
cout << name << ": Mid part found!" << endl;
}
if (line.substr(0, 3) == "BG:"){
BG = new int[w*h];
readmap(line.substr(3, line.length()), w*h, BG);
cout << name << ": Back part found!" << endl;
}
if (line.substr(0, 8) == "endofmap") {
cout << "End of " << name << "." << endl;
break;
}
}
int mapsize = w*h;
pack_iputl(w, map); //Width
pack_iputl(h, map); //Heigth
pack_iputl(walknum, map); //Num Of Walkable Tiles
pack_fwrite(walkables, walknum*4, map); //Walkable Tiles
pack_iputl(walknum, map); //Num Of Destructable Tiles
pack_fwrite(walkables, walknum*4, map); //Destructable Tiles
pack_fwrite(BG, mapsize*4, map); //sizeof(BG\FG\MG) int is 4
pack_fwrite(MG, mapsize*4, map);
pack_fwrite(FG, mapsize*4, map);
pack_fclose(map);
cout << "Written new map: " << name << ".map!" << endl;
}
}
pack_fclose(file);
cout << endl << "Thank you for using MapConv for Pyromania!" << endl << "(c) by Jonathan Hale 2012" << endl;
}
| true |
5b0a89ccba8eb1dda4ac00e45341abfc445f8300 | C++ | iamjhpark/BOJ | /17086.cpp | UTF-8 | 1,814 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector<int> safetyDistance;
vector<int> dx = { 0, 0, -1, 1, -1, -1, 1, 1 };
vector<int> dy = { -1, 1, 0, 0, -1, 1, -1, 1 };
void BFS(vector<vector<int>> &map, int N, int M) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
vector<vector<int>> check(N, vector<int>(M, true));
queue<tuple<int, int, int>> q;
if (map[i][j] == 1) { continue; }
q.push(make_tuple(i, j, 0));
check[i][j] = false;
while (!q.empty()) {
tuple<int, int, int> current = q.front();
q.pop();
int currentX = get<0>(current);
int currentY = get<1>(current);
int distance = get<2>(current);
if (map[currentX][currentY] == 1) { safetyDistance.push_back(distance); break; }
for (int k = 0; k < 8; k++) {
int nextX = currentX + dx[k];
int nextY = currentY + dy[k];
if (nextX > -1 && nextX < N && nextY > -1 && nextY < M && check[nextX][nextY]) {
check[nextX][nextY] = false;
q.push(make_tuple(nextX, nextY, distance + 1));
}
}
}
}
}
}
int main(void) {
int N;
scanf("%d\n", &N);
int M;
scanf("%d\n", &M);
vector<vector<int>> map(N, vector<int>(M));
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int el;
scanf("%d", &el);
map[i][j] = el;
}
}
BFS(map, N, M);
int answer = * max_element(safetyDistance.begin(), safetyDistance.end());
printf("%d\n", answer);
} | true |
b74be4ed6552357e3e2a198da5365a988c8bd009 | C++ | polyakovartem/cpp_idioms | /src/iterator_pair.cc | UTF-8 | 896 | 3.921875 | 4 | [
"MIT"
] | permissive | #include <list>
#include <set>
#include <iostream>
template <class T>
class vector
{
T * mem;
public:
template <class InputIterator>
vector (InputIterator begin, InputIterator end) // Iterator-pair constructor
{
// allocate enough memory and store in mem.
mem=new T[std::distance(begin, end)];
for (int i = 0; begin != end; ++i)
{
mem[i] = *begin;
++begin;
}
}
};
int main (void)
{
std::list<int> l(4);
std::fill(l.begin(),l.end(), 10); // fill up list using iterator pair technique.
//std::set<int> s(4);
//std::fill(s.begin(),s.end(), 20); // fill up set using iterator pair technique.
std::cout << "hello gyp" << std::endl;
//std::vector<int> v1(l.begin(), l.end()); // create vector using iterator pair technique.
//std::vector<int> v2(s.begin(), s.end()); // create another vector.
}
| true |
5fc90ae4b0299e015f75e3ae886065e36bb03392 | C++ | Ridaniel/tb1-ia | /Trabajo_Final_CC68_SV32/Trabajo_Final_CC68_SV32/CListaDoble.hpp | UTF-8 | 4,861 | 3.59375 | 4 | [] | no_license | #ifndef CListaDoble_HPP
#define CListaDoble_HPP
#include "CNodo.hpp"
template<typename tipoDato>
class CListaDoble {
private:
CNodo<tipoDato>* inicio;
CNodo<tipoDato>* fin;
int tamanio;
public:
CNodo<tipoDato>* iterator;
bool iniciarIterator() {
if (tamanio == 0)
return false;
iterator = inicio;
return true;
}
bool moverIterator(int cantidad = 1) {
if (tamanio == 0 || iterator==nullptr)
return false;
if (cantidad>0)
while (cantidad-->0 && iterator!=nullptr)
iterator = iterator->getSiguiente();
else
while (cantidad++<0 && iterator!=nullptr)
iterator = iterator->getAnterior();
return true;
}
CListaDoble()
{
inicio = nullptr;
fin = nullptr;
tamanio = 0;
iterator = nullptr;
}
~CListaDoble()
{
delete inicio;
delete fin;
}
void push_back(tipoDato valor)
{
CNodo<tipoDato>* nuevo = new CNodo<tipoDato>(valor);
std::cout << valor->getNumero()<<std::endl;
if (tamanio == 0) {
inicio = nuevo;
fin = nuevo;
}
else {
nuevo->setAnterior(fin);
fin->setSiguiente(nuevo);
fin = nuevo;
}
++tamanio;
}
tipoDato front()
{
if (tamanio <= 0) throw "ERROR: NO HAY ELEMENTOS EN LA LISTA!";
else return inicio->getValor();
}
tipoDato back()
{
if (tamanio <= 0) throw "ERROR: NO HAY ELEMENTOS EN LA LISTA!";
else return fin->getValor();
}
CNodo<tipoDato>* begin()
{
return inicio;
}
CNodo<tipoDato>* end()
{
return fin;
}
bool empty()
{
if (tamanio == 0) return true;
else return false;
}
int size()
{
return tamanio;
}
void clear()
{
CNodo<tipoDato>* iterador = inicio;
for (int i = 0; i < tamanio; ++i) {
CNodo<tipoDato>* borrador = iterador;
iterador = iterador->getSiguiente();
delete borrador;
}
inicio = nullptr;
fin = nullptr;
tamanio = 0;
}
void insert(int posicion, tipoDato valor)
{
if (posicion >= 0 && posicion < tamanio) {
CNodo<tipoDato>* nuevo = new CNodo<tipoDato>(valor);
if (tamanio == 0) {
inicio = nuevo;
fin = nuevo;
++tamanio;
}
else {
CNodo<tipoDato>* iterador = nullptr;
if (tamanio - posicion + 1 < posicion) {
iterador = fin;
for (int i = tamanio - 1; i > posicion; --i) iterador = iterador->getAnterior();
}
else {
iterador = inicio;
for (int i = 0; i < posicion; ++i) iterador = iterador->getSiguiente();
}
if (posicion == 0) {
nuevo->setSiguiente(inicio);
inicio->setAnterior(nuevo);
inicio = nuevo;
}
else if (posicion == tamanio - 1) {
nuevo->setAnterior(fin);
fin->setSiguiente(nuevo);
}
else {
nuevo->setAnterior(iterador->getAnterior());
nuevo->setSiguiente(iterador->getSiguiente());
nuevo->getAnterior()->setSiguiente(nuevo);
nuevo->getSiguiente()->setAnterior(nuevo);
}
}
++tamanio;
}
else throw "ERROR: POSICION NO VALIDA!";
}
void erase(int posicion)
{
if (posicion >= 0 && posicion < tamanio) {
if (tamanio == 0) throw "ERROR: NO HAY ELEMENTOS EN LA LISTA!";
else {
CNodo<tipoDato>* iterador = nullptr;
if (tamanio - posicion + 1 < posicion) {
iterador = fin;
for (int i = tamanio - 1; i > posicion; --i) iterador = iterador->getAnterior();
}
else {
iterador = inicio;
for (int i = 0; i < posicion; ++i) iterador = iterador->getSiguiente();
}
CNodo<tipoDato>* borrador = iterador;
if (posicion == 0) inicio = iterador->getSiguiente();
else if (posicion == tamanio - 1) fin = iterador->getAnterior();
else {
iterador->getAnterior()->setSiguiente(iterador->getSiguiente());
iterador->getSiguiente()->setAnterior(iterador->getAnterior());
}
delete borrador;
}
--tamanio;
}
else throw "ERROR: POSICION NO VALIDA!";
}
void pop_back()
{
if (tamanio > 0) {
CNodo<tipoDato>* borrador = fin;
fin = fin->getAnterior();
delete borrador;
--tamanio;
}
else throw "ERROR: NO HAY ELEMENTOS";
}
void push_front(tipoDato valor)
{
if (tamanio >= 0) {
CNodo<tipoDato>* nuevo = new CNodo<tipoDato>(valor);
nuevo->setSiguiente(inicio);
inicio->setAnterior(nuevo);
inicio = nuevo;
++tamanio;
}
else throw "ERROR: NO HAY ELEMENTOS";
}
void pop_front()
{
if (tamanio > 0) {
CNodo<tipoDato>* borrador = inicio;
inicio = inicio->getSiguiente();
delete borrador;
--tamanio;
}
else throw "ERROR: NO HAY ELEMENTOS";
}
tipoDato at(int pos)
{
if (pos >= 0 && pos < tamanio)
{
CNodo<tipoDato> *iterador = nullptr;
if (tamanio - pos + 1 < pos)
{
iterador = fin;
for (int i = tamanio - 1; i > pos; --i)
iterador = iterador->getAnterior();
}
else
{
iterador = inicio;
for (int i = 0; i < pos; ++i)
iterador = iterador->getSiguiente();
}
return iterador->getValor();
}
else
throw "ERROR: POSICION NO VALIDA!";
}
};
#endif // !CListaDoble_HPP
| true |
9757c9771f4008a8d34a0d6ae5b17f60869e0f4b | C++ | stefanreuther/afl | /u/t_base_ptr.cpp | UTF-8 | 6,402 | 3.078125 | 3 | [] | no_license | /**
* \file u/t_base_ptr.cpp
* \brief Test for afl::base::Ptr
*/
#include "afl/base/ptr.hpp"
#include "u/t_base.hpp"
/*
* Pointer to fundamental type
*/
/** Test pointer to fundamental type. */
void
TestBasePtr::testInt()
{
afl::base::Ptr<int> pi = new int(17);
afl::base::Ptr<int> pj;
pj = pi;
pi = new int(23);
TS_ASSERT_EQUALS(*pi, 23);
TS_ASSERT_EQUALS(*pj, 17);
TS_ASSERT_EQUALS(*pi.get(), 23);
}
/*
* Pointer to object type
*/
namespace {
class Obj {
Obj(const Obj&);
Obj& operator=(const Obj&);
public:
int n;
static int live;
Obj(int n)
: n(n) { ++live; }
~Obj()
{ --live; }
};
int Obj::live = 0;
}
/** Test pointer to object type. */
void
TestBasePtr::testObj()
{
TS_ASSERT_EQUALS(Obj::live, 0);
afl::base::Ptr<Obj> pi = new Obj(12);
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pi->n, 12);
afl::base::Ptr<Obj> pj(pi);
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pj->n, 12);
TS_ASSERT_EQUALS(pi.get(), pj.get());
pi.reset();
TS_ASSERT_EQUALS(pi.get(), (Obj*) 0);
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pj->n, 12);
pi = new Obj(42);
TS_ASSERT_EQUALS(Obj::live, 2);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 12);
pj = pi;
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 42);
// Pass through dumb pointer
pi = 0;
pi = pj.get();
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 42);
pi = 0;
pj = 0;
TS_ASSERT_EQUALS(Obj::live, 0);
}
/** Test pointer to const object type. */
void
TestBasePtr::testConstObj()
{
TS_ASSERT_EQUALS(Obj::live, 0);
{
const Obj* p = new Obj(77);
afl::base::Ptr<const Obj> pi = p;
TS_ASSERT_EQUALS(Obj::live, 1);
TS_ASSERT_EQUALS(pi->n, 77);
}
TS_ASSERT_EQUALS(Obj::live, 0);
}
/*
* Pointer to RefCounted object type
*/
namespace {
class RefCountedObj {
RefCountedObj(const RefCountedObj&);
RefCountedObj& operator=(const RefCountedObj&);
public:
int n;
static int live;
RefCountedObj(int n)
: n(n) { ++live; }
~RefCountedObj()
{ --live; }
};
int RefCountedObj::live = 0;
}
/** Test pointer to RefCounted type. */
void
TestBasePtr::testRefCountedObj()
{
TS_ASSERT_EQUALS(RefCountedObj::live, 0);
afl::base::Ptr<RefCountedObj> pi = new RefCountedObj(12);
TS_ASSERT_EQUALS(RefCountedObj::live, 1);
TS_ASSERT_EQUALS(pi->n, 12);
afl::base::Ptr<RefCountedObj> pj(pi);
TS_ASSERT_EQUALS(RefCountedObj::live, 1);
TS_ASSERT_EQUALS(pj->n, 12);
TS_ASSERT_EQUALS(pi.get(), pj.get());
pi.reset();
TS_ASSERT_EQUALS(pi.get(), (RefCountedObj*) 0);
TS_ASSERT_EQUALS(RefCountedObj::live, 1);
TS_ASSERT_EQUALS(pj->n, 12);
pi = new RefCountedObj(42);
TS_ASSERT_EQUALS(RefCountedObj::live, 2);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 12);
pj = pi;
TS_ASSERT_EQUALS(RefCountedObj::live, 1);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 42);
// Pass through dumb pointer
pi = 0;
pi = pj.get();
TS_ASSERT_EQUALS(RefCountedObj::live, 1);
TS_ASSERT_EQUALS(pi->n, 42);
TS_ASSERT_EQUALS(pj->n, 42);
pi = 0;
pj = 0;
TS_ASSERT_EQUALS(RefCountedObj::live, 0);
}
/*
* Test derivation
*/
namespace {
class Base {
public:
Base()
: m_obj(1)
{ }
virtual ~Base() { }
private:
Obj m_obj;
};
class Derived1 : public Base { };
class Derived2 : public Base { };
}
/** Test pointer to derived classes. */
void
TestBasePtr::testDerivation()
{
TS_ASSERT_EQUALS(Obj::live, 0);
// Make Derived1
afl::base::Ptr<Derived1> pd1(new Derived1());
TS_ASSERT_EQUALS(Obj::live, 1);
// Make Base
afl::base::Ptr<Base> pb(new Base());
TS_ASSERT_EQUALS(Obj::live, 2);
// Store Derived1 in Base pointer
afl::base::Ptr<Base> pb2(pd1);
TS_ASSERT_EQUALS(Obj::live, 2);
// Assign Derived1 to Base (Base dies)
pb = pd1;
TS_ASSERT_EQUALS(Obj::live, 1);
// Make Derived2
afl::base::Ptr<Derived2> pd2(new Derived2());
TS_ASSERT_EQUALS(Obj::live, 2);
// Try casting Derived1->Derived1
afl::base::Ptr<Derived1> pd11 = pd1.cast<Derived1>();
TS_ASSERT_EQUALS(pd11.get(), pd1.get());
// Try casting Base->Derived1. Base still contains the Derived1 object.
pd11 = pb.cast<Derived1>();
TS_ASSERT_EQUALS(pd11.get(), pd1.get());
// Same thing, now with Derived2
pb = pd2;
pd11 = pb.cast<Derived1>();
TS_ASSERT_EQUALS(pd11.get(), (Derived1*) 0);
}
namespace {
class CopyDestructor {
public:
CopyDestructor(afl::base::Ptr<CopyDestructor>& ref)
: m_ref(ref)
{ }
~CopyDestructor()
{
afl::base::Ptr<CopyDestructor> copy = m_ref;
}
private:
afl::base::Ptr<CopyDestructor>& m_ref;
};
}
/** Test copying the pointer in the destructor.
The wrong implementation of the destructor (decRef) will cause infinite recursion.
See https://www.reddit.com/r/cpp/comments/79ak5d/a_bug_in_stdshared_ptr/ */
void
TestBasePtr::testCopyDestructor()
{
// Variant 1
{
afl::base::Ptr<CopyDestructor> p(new CopyDestructor(p));
}
// Variant 2
{
afl::base::Ptr<CopyDestructor> p(new CopyDestructor(p));
p.reset();
}
}
namespace {
class AssignDestructor {
public:
AssignDestructor(afl::base::Ptr<AssignDestructor>* p)
: m_p(p)
{ }
~AssignDestructor()
{
if (m_p) {
*m_p = new AssignDestructor(0);
}
}
private:
afl::base::Ptr<AssignDestructor>* m_p;
};
}
/** Test re-assigning the pointer in the destructor.
This is a variation of testCopyDestructor(). */
void
TestBasePtr::testAssignDestructor()
{
// Variant 1
{
afl::base::Ptr<AssignDestructor> p(new AssignDestructor(&p));
}
// Variant 2
{
afl::base::Ptr<AssignDestructor> p(new AssignDestructor(&p));
p.reset();
}
}
| true |
bb09d5fe7c7f316c1c9729e3d793d3b221b8c37a | C++ | JazmineAlfaro/Computacion-Paralela | /Juego - 3 en raya/player.cpp | UTF-8 | 2,012 | 3.015625 | 3 | [] | no_license | /* Player code in C++ */
//g++ player.cpp -o player -std=c++11 -lpthread
/*
rules:
send 1 to confirm connection and play
send 2 position (1-9) to put your play
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <thread>
int SocketFD;
bool end = false;
char buffer[256];
int port = 45506;
void send_msg(){
char msg[256];
int n;
do{
std::cin.getline(msg, 255);
n = write(SocketFD,msg,255);
msg[n] = '\0';
if (strcmp(msg, "8") == 0) end = true;
} while(!end);
}
void rcv_msg(){
int n;
do{
bzero(buffer,256);
n = read(SocketFD,buffer,255);
if (n < 0) perror("ERROR reading from socket");
buffer[n] = '\0';
//printf("Here is the message: [%s]\n",buffer);
printf("%s\n",buffer);
n = write(SocketFD,"Ok. Message recieved.",21);
} while(!end);
}
int main(void){
struct sockaddr_in stSockAddr;
int Res;
SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
int n;
char msg[256];
if (-1 == SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}
memset(&stSockAddr, 0, sizeof(struct sockaddr_in));
stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(port); //port
Res = inet_pton(AF_INET, "127.0.1.1", &stSockAddr.sin_addr);
if (0 > Res)
{
perror("error: first parameter is not a valid address family");
close(SocketFD);
exit(EXIT_FAILURE);
}
else if (0 == Res)
{
perror("char string (second parameter does not contain valid ipaddress");
close(SocketFD);
exit(EXIT_FAILURE);
}
int cnct = connect(SocketFD, (const struct sockaddr *)&stSockAddr, sizeof(struct sockaddr_in));
if (-1 == cnct)
{
perror("connect failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
std::thread t1(send_msg);
std::thread t2(rcv_msg);
t1.detach();
t2.detach();
rcv_msg(); //confirming disconnection
shutdown(SocketFD, SHUT_RDWR);
close(SocketFD);
return 0;
}
| true |
987431f4717d63236a8d4b4aed635af27a1fdb7b | C++ | mikaepe/cppPro3 | /oldfiles/domain01.cpp | UTF-8 | 1,102 | 2.8125 | 3 | [] | no_license |
class Domain {
/* "_" means local variable
*/
public:
Domain(const Curvebase&,const Curvebase&,const Curvebase&,const Curvebase&);
void generate_grid(int n, int m);
// fråga: om funktionen sitter i klassen ska det inte stå
// void grid_generation(int n, int m){} ???
void Domain::grid_generation(int n, int m){
if ((n < 1) || (m < 1))
std::cout << "exit (Failure)" << std::endl;
if (n_ != 0) { // or m_ != 0
delete[] x_; delete[] y_; // Varför? För att ta bort gamla saker om vi ger
// nya kurvor eller?
}
n_ = n; m_ = m;
x_ = new double[(m+1)*(n+1)];
y_ = new double[(n+1)*(m+1)];
double h1 = 1.0/n; double h2 = 1.0/m;
for (int i = 0; i<= n_; i++){
for (int j = 0; j<= m_; j++){
x_[j+i*(m_+1)] = phi1(i*h1)*sides[3]->x(j*h2)
+ phi2*sides[1]->x(j*h2)
+ term3
+ term4 - corr1 -corr2 - corr3 - corr4;
y_[...] = .... ;
}
private:
Curvebase *sides[4];
int m_=0,n_=0;
double *x_,*y_; // x,y-coordinates, "underscore = internal"
//
// etc...
};
| true |
1995e0e715509ea8e1f1e43da8d438165fca7ec0 | C++ | begeekmyfriend/leetcode | /0146_lru_cache/lru_cache.cc | UTF-8 | 1,227 | 3.015625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
/**
* Your LRUCache object will be instantiated and called as such:
* LRUCache* obj = new LRUCache(capacity);
* int param_1 = obj->get(key);
* obj->put(key,value);
*/
class LRUCache {
public:
LRUCache(int capacity) {
cap_ = capacity;
}
int get(int key) {
if (ht_.count(key) == 0) {
return -1;
}
int value = (*ht_[key]).second;
if (li_.front().first != key) {
li_.erase(ht_[key]);
li_.push_front(make_pair(key, value));
ht_[key] = li_.begin(); // iterator failure
}
return value;
}
void put(int key, int value) {
if (cap_ <= 0) {
return;
}
if (ht_.count(key) == 0) {
li_.erase(ht_[key]);
} else {
if (li_.size() == cap_) {
auto lru = li_.back();
li_.pop_back();
ht_.erase(lru.first);
}
}
li_.push_front(make_pair(key, value));
ht_[key] = li_.begin(); // iterator failure
}
private:
int cap_;
list<pair<int, int>> li_;
unordered_map<int, list<pair<int, int>>::iterator> ht_;
};
| true |
689634ecf77493da1bb6a5357453de12e6f9ea1e | C++ | m4tx/nsfgbe | /src/emulator/timer/Timer.cpp | UTF-8 | 880 | 2.53125 | 3 | [
"MIT"
] | permissive | #include "Timer.hpp"
namespace nsfgbe {
Timer::Timer(InterruptManager &interruptManager) :
interruptManager(interruptManager),
dividerRegister(*this),
timerCounterRegister(0),
timerModuloRegister(0),
timerControlRegister(*this) {}
void Timer::tick(size_t ticks) {
size_t newTotalTicks = totalTicks + ticks;
size_t tickXor = totalTicks ^newTotalTicks;
if (tickXor & DIVIDER_STEP) {
++divider;
}
if (counterEnabled && (tickXor & counterStep)) {
++timerCounterRegister;
if (timerCounterRegister == 0) {
timerCounterRegister = timerModuloRegister;
interruptManager.fireTimerInterrupt();
}
}
totalTicks = newTotalTicks;
}
void Timer::setCounterFrequency(Timer::Frequency frequency) {
counterStep = FREQUENCY_MAP[static_cast<size_t>(frequency)];
}
}
| true |
f15d3c77e4f4614934c88bd3a0f2d1a6c658195f | C++ | acellison/odex | /include/odex/observers/dense_observer.hpp | UTF-8 | 1,059 | 3.078125 | 3 | [
"MIT"
] | permissive |
#ifndef ODEX_OBSERVERS_DENSE_OBSERVER_HPP
#define ODEX_OBSERVERS_DENSE_OBSERVER_HPP
#include <vector>
namespace odex {
namespace observers {
/// A dense observer records the time and state after each sample
/// is computed by the extrapolation_stepper.
template <class Time, class State>
class dense_observer
{
public:
dense_observer()
{ }
explicit dense_observer(std::size_t size)
{
m_time.reserve(size);
m_state.reserve(size);
}
template <class T, class S>
void operator()(T&& t, S&& state)
{
m_time.push_back(std::forward<T>(t));
m_state.push_back(std::forward<S>(state));
}
std::vector<T> const& time() const { return m_time; }
std::vector<T> & time() { return m_time; }
std::vector<T> const& state() const { return m_state; }
std::vector<T> & state() { return m_state; }
private:
std::vector<Time> m_time;
std::vector<State> m_state;
};
} // namespace observers
} // namespace odex
#endif // ODEX_OBSERVERS_DENSE_OBSERVER_HPP
| true |
7a7f0926cf4100840f01034ab86c80a393a43354 | C++ | fromasmtodisasm/Two-pass-assembler | /src/rad.h | UTF-8 | 3,211 | 2.53125 | 3 | [] | no_license | /*
* File: rad.h
* Author: etf
*
* Created on May 25, 2016, 3:23 AM
*/
#ifndef RAD_H
#define RAD_H
#include <iostream>
#include <string>
#include <deque>
#include <vector>
#include <sstream>
#include "SymTable.h"
#include "OpCodeTable.h"
#include "RelocTable.h"
#include "KodoviQ.h"
#include "FileRel.h"
typedef deque<string>::iterator LineIterator;
typedef vector<string>::iterator VIterator;
using namespace std;
class rad {
public:
rad();
virtual ~rad();
void incCnt(int inc) {
loccnt += inc;
}
void resetCnt() {
loccnt = 0;
}
int getCnt() {
return loccnt;
}
string getSek() {
return secCurr;
}
void setSek(string sek) {
secCurr = sek;
}
void resetSek() {
secCurr = "UND";
}
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters=" ");
//^da podeli liniju na reci-svaki clan vektora je jedna rec(pomocu pretrage razmaka)
void priprema();
void prolazI();
void prolazII(); //ne treba mi prosledjivanje parametra al ajd nek bude tu
bool obaProlaza(string filenamein, string filenameout);
bool checkLine(vector<string>& parcad, SymUlaz& ulaz);
//proverava ispravnost komande
bool checkIfStringIsInt(const string& s);
void dealWithInstr(string name, vector<string>& parcad, string& kod, string& relok, string uslov);
void dealWithImmed(string& deo, unsigned long& opcode, string& kod);
void dealWithReg(string& deo, string& name, unsigned long& reg);
void PcRelCall(string& deo, unsigned long& opcode, string& relok, string& kod);
void saveTables(string& kod, string& relok);//pohranjuje podatke trenutne sekcije
void ldcSummon16s(string& name, vector<string>& parcad, unsigned long& vrsimbola, string uslov, string& kod, string& relok);
void ldcAbs16Rel(vector<string>& parcad, string& relok, string tiprel, unsigned long& vrsimbola);
void word1(vector<string>& parcad);
void word2(vector<string>& parcad, string& kod, string& relok);
void long1(vector<string>& parcad);
void long2(vector<string>& parcad, string& kod, string& relok);
void char1(vector<string>& parcad);
void char2(vector<string>& parcad, string& kod);
void align1(vector<string>& parcad, LineIterator& lit);
void align2(vector<string>& parcad, string& kod);
void skip2(vector<string>& parcad, string& kod);
void setFilename(string filename);
string getFilename();
void littleEndian(unsigned long& code, int inc);
string decToHex(unsigned long& code, int inc);
void insertBreaks(string& str);
private:
rad(const rad& orig); //ne treba mi
string secCurr = "UND"; //trenutna sekcija, dok je UND, mocice da se koriste public,extern
int loccnt = 0; //location counter
deque<string> lines; //sadrzi sve linije koda
SymTable simboli;
OpCodeTable komande;
RelocTableQ relokacije;
KodoviQ kodovi;
bool status0 = 1;
bool status1 = 1; //promenimo na 0 ako je prolazak kroz instrukcije zavrsen sa .end(uspesno)
bool status2 = 1;//drugi prolaz
string sekbinKom = "";
string INfilename;//ime fajla iz kog citamo
string OUTfilename;
};
#endif /* RAD_H */
| true |
8e61ad31f23e319cd1f16519cf4ae4b52d7e7164 | C++ | shuhei-hykw/dummy_maker | /src/DAQNode.cc | UTF-8 | 5,571 | 2.59375 | 3 | [] | no_license | /**
* file: DAQNode.cc
* date: 2016.01.28
*
*/
#include "DAQNode.hh"
#include "DAQModule.hh"
#include "NodeManager.hh"
#include <iostream>
#include <string>
extern unsigned int g_run_number;
static const std::string class_name("DAQNode");
//_____________________________________________________________________
DAQNode::DAQNode( const std::string& node_name, const unsigned int node_id )
: m_nest(1),
m_node_name(node_name),
m_node_type("DAQNode"),
m_data_size(k_eb_header_length),
m_event_number(0),
m_run_number(g_run_number),
m_node_id(node_id),
m_event_type(0),
m_n_blocks(0),
m_reserved(0)
{
m_eb_header.resize( k_eb_header_length );
m_eb_header[k_eb_magic] = k_eb_magic_word;
m_eb_header[k_data_size] = m_data_size;
m_eb_header[k_event_number] = m_event_number;
m_eb_header[k_run_number] = m_run_number;
m_eb_header[k_node_id] = m_node_id;
m_eb_header[k_event_type] = m_event_type;
m_eb_header[k_n_blocks] = m_n_blocks;
m_eb_header[k_reserved] = m_reserved;
}
//_____________________________________________________________________
DAQNode::~DAQNode()
{
}
//_____________________________________________________________________
bool
DAQNode::Clear( void )
{
static const std::string func_name("["+class_name+"::"+__func__+"()]");
for( ModuleIterator itr=m_module_container.begin(),
itr_end=m_module_container.end(); itr!=itr_end; ++itr ){
(*itr)->Clear();
}
return true;
}
//_____________________________________________________________________
bool
DAQNode::RegisterNode( DAQNode *node )
{
static const std::string func_name("["+class_name+"::"+__func__+"()]");
static NodeManager& node_manager = NodeManager::GetInstance();
node_manager.AddNodeList( node );
m_eb_header[k_n_blocks] = ++m_n_blocks;
node->SetNest( m_nest+1 );
m_node_container.push_back( node );
return true;
}
//_____________________________________________________________________
bool
DAQNode::RegisterModule( DAQModule *module )
{
static const std::string func_name("["+class_name+"::"+__func__+"()]");
static NodeManager& node_manager = NodeManager::GetInstance();
node_manager.AddModuleList( module );
m_module_container.push_back( module );
return true;
}
//_____________________________________________________________________
void
DAQNode::SetEventNumber( unsigned int number )
{
m_event_number = number;
m_eb_header[k_event_number] = m_event_number;
}
//_____________________________________________________________________
void
DAQNode::SetDataSize( unsigned int size )
{
m_data_size = size;
m_eb_header[k_data_size] = m_data_size;
}
//_____________________________________________________________________
void
DAQNode::SetDataSize( void )
{
m_data_size = k_eb_header_length;
m_data_size += k_node_header_length;
for( NodeIterator itr=m_node_container.begin(),
itr_end=m_node_container.end(); itr!=itr_end; ++itr ){
(*itr)->SetDataSize();
(*itr)->SetLocalDataSize();
m_data_size += (*itr)->GetDataSize();
}
for( ModuleIterator itr=m_module_container.begin(),
itr_end=m_module_container.end(); itr!=itr_end; ++itr ){
m_data_size += (*itr)->GetDataSize();
}
m_eb_header[k_data_size] = m_data_size;
}
//_____________________________________________________________________
void
DAQNode::SetLocalDataSize( void )
{
}
//_____________________________________________________________________
DataWord
DAQNode::SummarizeDataWord( void ) const
{
DataWord data;
data.insert( data.end(), m_eb_header.begin(), m_eb_header.end() );
data.insert( data.end(), m_node_header.begin(), m_node_header.end() );
for( NodeIterator itr=m_node_container.begin(),
itr_end=m_node_container.end(); itr!=itr_end; ++itr ){
DataWord child_data = (*itr)->SummarizeDataWord();
data.insert( data.end(), child_data.begin(), child_data.end() );
}
for( ModuleIterator itr=m_module_container.begin(),
itr_end=m_module_container.end(); itr!=itr_end; ++itr ){
DataWord module_header = (*itr)->GetModuleHeader();
DataWord module_data = (*itr)->GetDataWord();
DataWord module_trailer = (*itr)->GetModuleTrailer();
data.insert( data.end(), module_header.begin(), module_header.end() );
data.insert( data.end(), module_data.begin(), module_data.end() );
data.insert( data.end(), module_trailer.begin(), module_trailer.end() );
}
return data;
}
//_____________________________________________________________________
void
DAQNode::PrintNodeList( void )
{
static const std::string func_name("["+class_name+"::"+__func__+"()]");
std::cout << "#D " << func_name << " " << m_node_name << std::endl;
for( NodeIterator itr=m_node_container.begin(),
itr_end=m_node_container.end(); itr!=itr_end; ++itr ){
std::cout << " " << (*itr)->GetNodeName() << std::endl;
}
}
//_____________________________________________________________________
void
DAQNode::PrintModuleList( void )
{
static const std::string func_name("["+class_name+"::"+__func__+"()]");
std::cout << "#D " << func_name << " " << m_node_name << std::endl;
for( ModuleIterator itr=m_module_container.begin(),
itr_end=m_module_container.end(); itr!=itr_end; ++itr ){
std::cout << " " << (*itr)->GetModuleName() << std::endl;
}
}
//_____________________________________________________________________
void
DAQNode::PrintModuleData( void )
{
for( ModuleIterator itr=m_module_container.begin(),
itr_end=m_module_container.end(); itr!=itr_end; ++itr ){
(*itr)->PrintDataWord();
}
}
| true |
bedc8dc94387457fd033d1117ec46c4e93ed75a0 | C++ | NickLuGithub/school_homework | /資料結構/HWK/2-HWK1/VS/HWK1/OK.cpp | BIG5 | 15,789 | 2.796875 | 3 | [] | no_license | // {: Ctrl + F5 [] > [Ұʦ] \
// {: F5 [] > [Ұʰ] \
// }lϥΪ:
// 1. ϥ [`] AsW/zɮ
// 2. ϥ [Team Explorer] Asulɱ
// 3. ϥ [X] AѾ\իؿXPLT
// 4. ϥ [~M] A˵~
// 5. e [M] > [sW]Aإ߷s{XɮסAάOe [M] > [sW{]AN{{XɮsWܱM
// 6. nA}ҦMɡAЫe [ɮ] > [}] > [M]AM .sln ɮ
// HWK1.cpp : ɮץ]t 'main' 禡C{|ӳB}lεC
//@:YUDA LU
//:2020.03.20(1.0), 2020.03.24(1.1), 2020.04.09(1.2), 2020.04.10(2.0)
//ثe >> back_edge ~B (low~)
#include <iostream>
#include <fstream>
#include <windows.h>
#include <dos.h>
#include <conio.h>
#include <typeinfo>
#define SIZE 20
using namespace std;
class point
{
private:
//number >> Ʀr
//number_line[20] >> Ʀrs쪺Ʀr
//line_n >> Ʀrs`
//ѮvI >> iHbIWy >> aJjƮyP_
int number, number_line[SIZE], line_n,
dfn, back_edge, low, input_number;
bool bool_number_line[SIZE] = { false },
bool_number_end = false;
public:
//ɤJɮ
void in_number(int n);
void in_number_line(int i, int n);
void in_line_n(int n);
void in_bool_number_line(int i, bool op);
void in_dfn(int i);
void in_low(int i);
void in_back_edge(int i);
void in_bool_number_end(bool i);
void in_input_number(int i);
//ɥXɮ
int out_number();
int out_number_line(int i);
int out_line_n();
int out_dfn();
int out_low();
int out_back_edge();
int out_bool_total();
int out_input_number();
bool out_bool_number_line(int i);
bool out_bool_number_end();
//function at class point
int return_number_i(int n);
bool cheak_number(int number);
bool cheak_number_ok(int number);
};
void read_date(string* in_number_date);
void string_to_point_array(string str_number, point point_array[SIZE], int* n);
void print_number_array(int n, point point_array[SIZE]);
void print_numbber_array_line(int n, point point_array[SIZE]);
void print_bool_array(int n, point point_array[SIZE]);
void print_articulation_point_array(int articulation_point[SIZE], int articulation_point_n);
void print_dfs_end(int n, point point_array[SIZE]);
void insert_number_to_point_array(int n, point point_array[SIZE]);
void insert_dfs(int n, point point_array[SIZE], int dfs_array[SIZE]);
void insert_back_edge(int n, point point_array[SIZE], int dfs_array[SIZE]);
void insert_articulation_point(int n, point point_array[SIZE], int dfs_array[SIZE], int articulation_point[SIZE], int* articulation_point_n);
int search_next_number(int search_number, point point_array[SIZE], int dfs_array_n, int dfs_array[SIZE]);
bool ok_number(int next_number, int dfs_array_n, int dfs_array[SIZE]);
//D{
int main(void)
{
/*
W
articulation_point >> `I
ܼ
n `@hּƦr
dfs_array DFS쪺
in_number_date ŪJҮgJrꤤ
point_array Ʀr}C
articulation_point `I}C
articulation_point_n `I}Cn
Ҹu
1.Ū
2.NɮഫPointΦ
3.ϥDFSXDFN}C
4.ϥback_edgeXlow
5.ϥlow & dfn X`I
*/
int n, articulation_point_n, dfs_array[SIZE], articulation_point[SIZE];
string in_number_date;
point point_array[SIZE];
read_date(&in_number_date); //Ū
string_to_point_array(in_number_date, point_array, &n); //ഫɮפ
print_number_array(n, point_array);
print_numbber_array_line(n, point_array);
insert_number_to_point_array(n, point_array);
//ظmpoint_arraynumberƦr
insert_dfs(n, point_array, dfs_array);
print_bool_array(n, point_array);
print_numbber_array_line(n, point_array);
//Xdfs
insert_back_edge(n, point_array, dfs_array);
//back_edgeXlow
insert_articulation_point(n, point_array, dfs_array, articulation_point, &articulation_point_n);
//low and dfn X`I
print_dfs_end(n, point_array);
print_bool_array(n, point_array); //CLboolA
print_articulation_point_array(articulation_point, articulation_point_n); //CL`I
system("pause");
return 0;
}
//class point {Ϭq }l
void point::in_number(int n)
{
number = n;
}
void point::in_number_line(int i, int n)
{
number_line[i] = n;
}
void point::in_line_n(int n)
{
line_n = n;
}
void point::in_bool_number_line(int i, bool op)
{
bool_number_line[i] = op;
}
void point::in_dfn(int i)
{
dfn = i;
}
void point::in_low(int i)
{
low = i;
}
void point::in_back_edge(int i)
{
back_edge = i;
}
void point::in_bool_number_end(bool i)
{
bool_number_end = i;
}
void point::in_input_number(int i)
{
input_number = i;
}
int point::out_number()
{
return number;
}
int point::out_number_line(int i)
{
return number_line[i];
}
int point::out_line_n()
{
return line_n;
}
int point::out_dfn()
{
return dfn;
}
int point::out_low()
{
return low;
}
int point::out_back_edge()
{
return back_edge;
}
int point::out_bool_total()
{
int sum = 0;
for (int i = 0; i < line_n; i++)
{
if (bool_number_line[i] == true)
{
++sum;
}
}
return sum;
}
int point::out_input_number()
{
return input_number;
}
bool point::out_bool_number_line(int i)
{
return bool_number_line[i];
}
bool point::out_bool_number_end()
{
return bool_number_end;
}
int point::return_number_i(int n)
{
int out = 0;
for (int i = 0; i < line_n; i++)
{
if (number_line[i] == n)
{
out = i;
break;
}
}
return out;
}
bool point::cheak_number(int number)
{
bool op = false;
for (int i = 0; i < line_n; i++)
{
if (number_line[i] == number) op = true;
}
if (op) return true;
else return false;
}
bool point::cheak_number_ok(int number)
{
bool op = false;
for (int i = 0; i < line_n; i++)
{
if (number_line[i] == number && bool_number_line[i] == 0) op = true;
}
if (op == true) return true;
else return false;
}
//class point {Ϭq
//}Ū
void read_date(string* in_number_date)
{
fstream InF;
int n = 0;
char FName[20], ch;
cout << "J{ɦW:";
cin >> FName;
InF.open(FName, ios::in);
if (!InF)
{
cout << "ɮLk}\n";
exit(1);
}
else
{
while (InF.get(ch))
{
*in_number_date += ch;
}
InF.close();
}
}
//string to point_array
void string_to_point_array(string str_number, point point_array[SIZE], int* n)
{
int i = 0, number_i = 0, number_n = 0, number_line_n = 0;
bool get_n = false;
string t;
/*
t >> snr
get_n >> PŪnŪF?
number_i >> number_i i
number_n >> number_i
number_line_n >> point_number_line
*/
while (str_number[i])
{
if (!get_n)
{
//ŪJn
if (str_number[i] != '\n')
{
t += str_number[i];
}
else
{
*n = atoi(t.c_str());
get_n = true;
}
i++;
}
else
{
if (str_number[i] != '\n')
{
//pG1~ܸƤ
if (str_number[i] == '1')
{
point_array[number_n].in_number_line(number_line_n, number_i);
number_i++;
number_line_n++;
}
else if (str_number[i] == '0')
{
number_i++;
}
else if (str_number[i] == ' ');
else
{
exit(1);
}
}
else
{
//Tks
point_array[number_n].in_line_n(number_line_n);
number_line_n = 0;
number_i = 0;
number_n++;
}
i++;
}
}
//r̫LӵL̫@T
if (str_number[i - 1] != '\n')
{
point_array[number_n].in_line_n(number_line_n);
}
}
void print_articulation_point_array(int articulation_point[SIZE], int articulation_point_n)
{
cout << "Articulation Point(`I): ";
for (int i = 0; i < articulation_point_n; i++)
{
cout << articulation_point[i] << " ";
}
cout << "\nBo!!\n";
}
void print_dfs_end(int n, point point_array[SIZE])
{
for (int i = 0; i < n; i++)
{
cout << point_array[i].out_bool_number_end() << " ";
}
cout << endl;
}
void print_number_array(int n, point point_array[SIZE])
{
cout << "n = " << n << " x}G" << endl;
printf(" ");
for (int i = 0; i < n; i++) printf("%2d ", i);
cout << endl;
for (int i = 0; i < n; i++)
{
printf("%2d > ", i);
for (int j = 0; j < n; j++)
{
if (point_array[i].cheak_number(j)) cout << "1 ";
else cout << "0 ";
}
cout << endl;
}
cout << "\n";
}
void print_bool_array(int n, point point_array[SIZE])
{
cout << "bool sGp\n";
for (int i = 0; i < n; i++)
{
printf("%2d > ", i);
for (int j = 0; j < point_array[i].out_line_n(); j++)
{
cout << point_array[i].out_bool_number_line(j) << " ";
}
cout << " \ttotal >> " << point_array[i].out_bool_total() << endl;
}
cout << "\n";
}
void print_numbber_array_line(int n, point point_array[SIZE])
{
cout << "²x}G\n";
for (int i = 0; i < n; i++)
{
printf("%2d > ", i);
for (int j = 0; j < n; j++)
{
if (point_array[i].cheak_number(j)) cout << j << " ";
}
cout << endl;
}
cout << "\n";
}
void insert_number_to_point_array(int n, point point_array[SIZE])
{
for (int i = 0; i < n; i++)
{
point_array[i].in_number(i);
}
}
bool ok_number(int next_number, int dfs_array_n, int dfs_array[SIZE])
{
bool op = true;
for (int i = 0; i < dfs_array_n; i++)
{
if (dfs_array[i] == next_number)
{
op = false;
break;
}
}
return op;
}
int search_next_number(int search_number, point point_array[SIZE], int dfs_array_n, int dfs_array[SIZE])
{
int next_number;
/*
MU@I
T{search_numbersSU@I
pGIAreturn I
pGSIAreturn NULL
*/
for (int i = 0; i < point_array[search_number].out_line_n(); i++)
{
next_number = point_array[search_number].out_number_line(i);
if (point_array[search_number].out_bool_number_line(i) == false && ok_number(next_number, dfs_array_n, dfs_array) == true)
{
int get_number = point_array[search_number].out_number_line(i);
int k = point_array[get_number].return_number_i(search_number);
point_array[search_number].in_bool_number_line(i, true);
point_array[get_number].in_bool_number_line(k, true);
return next_number;
break;
}
}
return NULL;
}
void insert_dfs(int n, point point_array[SIZE], int dfs_array[SIZE])
{
//cursor ثeMm
int search_total = 0, next_number, cursor = 0, dfs_array_n = 0;
bool op = false, go_break = false;
while (cursor < n && cursor >= 0)
{
//Qdfs_arraynP_O_Iwg
if (search_total == n) break;
if (op == false)
{
//N_lȿJdfs_array
point_array[cursor].in_dfn(search_total);
dfs_array[dfs_array_n++] = point_array[cursor].out_number();
search_total++, op = true;
}
else if (op == true)
{
//search_next_number >> MU@ӼƦr S^NULL
next_number = search_next_number(cursor, point_array, search_total, dfs_array);
if (next_number != NULL)
{
point_array[cursor].in_dfn(search_total);
dfs_array[search_total++] = next_number;
cursor = next_number;
dfs_array_n = search_total;
go_break = true;
}
else if (next_number == NULL)
{
if (go_break == true)
{
point_array[cursor].in_bool_number_end(true);
go_break = false;
}
cursor = dfs_array[--dfs_array_n];
}
else
{
cout << "GG!!" << endl;
exit(1);
}
}
}
/*
cout << "dfs_array[i] >>" << endl;
for (int i = 0; i < search_total; i++)
{
cout << i << "\t>> " << dfs_array[i] << endl;
}
cout << "seaech_total = " << search_total << "\n\n";
*/
}
//back_edge >> ثe low ~B
void insert_back_edge(int n, point point_array[SIZE], int dfs_array[SIZE])
{
/*
hold_number ثe̤p|
find_number 쪺̵u|
next_op Ss(find_number)̵ui
*/
int hold_number = n - 1, find_number = n - 1;
bool next_op = false;
// i >> dfn
for (int i = n - 1; i >= 0; i--)
{
for (int k = 0; k < i; k++)
{
//Qdfs_array̫@ӧ^
if (point_array[dfs_array[i]].cheak_number_ok(dfs_array[k]) == true)
{
cout << "hi >> " << k << endl;
int a_line_i = 0, b_line_i = 0; // a b Nsܼ ab
//bool
a_line_i = point_array[dfs_array[i]].return_number_i(dfs_array[k]);
b_line_i = point_array[dfs_array[k]].return_number_i(dfs_array[i]);
point_array[dfs_array[i]].in_bool_number_line(a_line_i, true);
point_array[dfs_array[k]].in_bool_number_line(b_line_i, true);
find_number = k;
next_op = true;
break;
}
next_op = false;
//find_number = -1;
}
point_array[0].in_low(0);
if (find_number < hold_number && next_op == true) //L̵u| W@ӤpNsæsJ
{
hold_number = find_number;
point_array[dfs_array[i]].in_low(hold_number);
next_op = false;
}
else if (find_number >= hold_number && next_op == true) //쪺|ӨSW@us
{
point_array[dfs_array[i]].in_low(hold_number);
next_op = false;
}
else if (i <= n - 2 && point_array[dfs_array[i + 1]].out_low() < i && next_op == false) //S|
{
find_number = i;
point_array[dfs_array[i]].in_low(point_array[dfs_array[i + 1]].out_low());
}
else if (next_op == false)
{
find_number = i;
point_array[dfs_array[i]].in_low(i);
}
else
{
point_array[dfs_array[i]].in_low(i);
}
cout << "i = " << i << " find_number >> " << find_number << endl;
//^ hold_number ۦ^̤j
if (point_array[dfs_array[i]].out_number() == 0 || find_number == 0 && i != 0)
{
hold_number = n - 1, find_number = n - 1;
}
}
//jܦ0
point_array[0].in_low(0);
//low̲BG
cout << "number, dfs_number , low >> " << endl;
for (int i = 0; i < n; i++)
{
printf("%2d >> %2d >> %2d\n", i, dfs_array[i], point_array[dfs_array[i]].out_low());
}
cout << endl;
}
//articulation_point >> `I
void insert_articulation_point(int n, point point_array[SIZE], int dfs_array[SIZE], int articulation_point[SIZE], int* articulation_point_n)
{
int out_n = 0;
for (int dfn = n - 2; dfn >= 0; dfn--)
{
if (dfn == 0)
{
if (point_array[dfs_array[dfn]].out_bool_total() > 2) //P_
{
articulation_point[out_n++] = point_array[dfs_array[dfn]].out_number();
}
}
else
{
if (dfn <= point_array[dfs_array[dfn + 1]].out_low()) // && point_array[dfs_array[dfn]].out_bool_number_end() == false
{
articulation_point[out_n++] = point_array[dfs_array[dfn]].out_number(); //QΤX`I
}
}
}
*articulation_point_n = out_n;
} | true |
57caba52ba3c19575b587b2f07c5d17f3007a0fe | C++ | jdrew1303/DobotChess | /piece_set.h | UTF-8 | 600 | 2.640625 | 3 | [] | no_license | #ifndef PIECE_SET_H
#define PIECE_SET_H
#pragma once
#include "chessboard/piece.h"
#include "vars/const_flags.h"
class PieceSet
{
private:
Piece* m_pPiece[32];
public:
PieceSet()
{
for (int i=0; i<=31; ++i)
m_pPiece[i] = new Piece(i+1);
}
Piece* getPiece(short sPieceNr) const { return m_pPiece[sPieceNr-1]; }
QString dumpAllData()
{
QString QStrData;
QStrData = "[piece_set.h]\n";
for (int i=0; i<=31; ++i)
QStrData += m_pPiece[i]->dumpAllData() + "\n";
return QStrData;
}
};
#endif // PIECE_SET_H
| true |
fd443f939b4bd4640415d7a8cf90712dbf1f19bd | C++ | SantoshKumarTandrothu/Cplusplus | /Data Structures/Arrays and Strings/Merge Meeting Times/MergeMeetingTimes.cpp | UTF-8 | 2,927 | 3.84375 | 4 | [] | no_license | /**
Author: Santosh Tandrothu
Date: 12/17/2018
Problem: Given a certain meetings time slots in random order, merge the
meetings into one meeting within the same timeframe.
Ex: [1pm,3pm] [2pm,4pm] results in [1pm,4pm]
**/
/***
Time Complexity = O(nlogn) - (sorting + comparison)
Space Complexity = O(n) (merged meetings considering no merges possible)
**/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
class Meeting{
private:
//30 min block
unsigned int startTime_;
unsigned int endTime_;
public:
Meeting():
startTime_(0),
endTime_(0)
{
}
Meeting(int startTime, int endTime):
startTime_(startTime),
endTime_(endTime)
{
}
unsigned int getStartTime() const{
return startTime_;
}
void setStartTime(unsigned int startTime){
startTime_ = startTime;
}
unsigned int getEndTime() const{
return endTime_;
}
void setEndTime(unsigned int endTime){
endTime_ = endTime;
}
bool operator==(const Meeting &other) const{
return
startTime_ == other.startTime_ &&
endTime_ == other.endTime_;
}
};
//compare function to built-in sort function
bool compareMeetingsByStartTime(const Meeting& m1, const Meeting& m2){
return (m1.getStartTime()<m2.getStartTime());
}
vector<Meeting> mergeMeetings(const vector<Meeting>& meetings){
//sort the meeting by start time
vector<Meeting> sortedMeetings(meetings);
sort(sortedMeetings.begin(),sortedMeetings.end(),compareMeetingsByStartTime);
//initialize merged meeting with earliest meeting
vector<Meeting> mergedMeetings;
mergedMeetings.push_back(sortedMeetings.front());
//iterate over all the meetings
for(const Meeting& currentMeeting: sortedMeetings){
Meeting& lastMergedMeeting = mergedMeetings.back();
//modify
if(currentMeeting.getStartTime() <= lastMergedMeeting.getEndTime()){
lastMergedMeeting.setEndTime(max(currentMeeting.getEndTime(),lastMergedMeeting.getEndTime()));
}
//create a new entry
else{
mergedMeetings.push_back(currentMeeting);
}
}
return mergedMeetings;
}
int main(){
vector<Meeting> meetings;
Meeting meeting1(6,8);
meetings.push_back(meeting1);
Meeting meeting2(3,5);
meetings.push_back(meeting2);
Meeting meeting3(2,3);
meetings.push_back(meeting3);
Meeting meeting4(1,2);
meetings.push_back(meeting4);
vector<Meeting> mergedMeetings = mergeMeetings(meetings);
for(const Meeting meeting:mergedMeetings){
cout<<"Meeting time:"<<meeting.getStartTime()<<"->"<<meeting.getEndTime()<<endl;
}
}
| true |
3f2f4d8cc9c0dad5b7bff41fd1ee541750303f64 | C++ | jatinwatts007/geek-for-geeks | /multiply left and right array sum.cpp | UTF-8 | 488 | 2.6875 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
int i,j,k,n,t;
cin>>t;
while(t--)
{
j=0;
k=0;
cin>>n;
int *arr=new int [n];
for(i=0;i<n;i++)
{
cin>>arr[i];
}
for(i=0;i<n/2;i++)
{
j=arr[i]+j;
}
for(i=n/2;i<n;i++)
{
k=arr[i]+k;
}
cout<<k*j<<endl;
delete [] arr;
}
//code
return 0;
}
| true |
3a6ac710f5520ed1c6d1e02ee7cc34260a8236b6 | C++ | nsergey82/hourglass | /library/src/id.cpp | UTF-8 | 289 | 2.875 | 3 | [
"MIT"
] | permissive | #include "id.h"
int Id_create(int *v1, int *v2) {
*v1 = 0;
*v2 = 1;
return 0;
}
int Id_applyLogic(int *v1, int *v2) {
if (*v2 > 1836311903) { // 46th Fibonacci fits in int
return 1;
}
int temp = *v1 + *v2;
*v1 = *v2;
*v2 = temp;
return 0;
}
| true |
b3149d8a2df8fe7f1c3037bdfc88c08c035df915 | C++ | apple1003232/Leetcode | /Excel Sheet Column Number.cpp | UTF-8 | 218 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for(int i = 0; i != s.length(); i++){
result += (s[i] - 64)*pow(26,s.length()-1-i);
}
return result;
}
}; | true |
fbe44da9a5c454575942fd4135481e46571cb03e | C++ | Pradumnk23/GFG-PS | /Linked List Insertion.cpp | UTF-8 | 854 | 3.625 | 4 | [] | no_license | class Solution{
public:
//Function to insert a node at the beginning of the linked list.
Node *insertAtBegining(Node *head, int x) {
struct Node *temp=new Node(x);
if(head==NULL)
{
head=temp;
return head;
}
else
{
temp->next=head;
head=temp;
}
return head;
}
//Function to insert a node at the end of the linked list.
Node *insertAtEnd(Node *head, int x) {
struct Node *temp=head;
struct Node *temp2=new Node(x);
if(head==NULL)
{
head=temp2;
return head;
}
else
{
while(temp->next!=NULL)
temp=temp->next;
temp->next=temp2;
return head;
}
}
};
| true |
04f7e2dd9b2dc13f0a9cf1efba6b7a93677a3199 | C++ | lisettem/AddMultiplyInfiniteNumbers | /infinitearithmetic.cpp | UTF-8 | 1,441 | 3.4375 | 3 | [] | no_license | #include "doubleLinkedList.h"
#include "ArgumentManager.h"
#include<cmath>
#include<fstream>
int main(int argc, char* argv[]) {
if (argc < 2) {
cerr << "Usage: infinitearithmetic \"filename=xyz.txt;digitsPerNode=<number>\"\n";
}
ArgumentManager am(argc, argv);
string filename = am.get("input");
string digitsPerNode = am.get("digitsPerNode"); //get digits per node and convert them to integer
ifstream myfile;
myfile.open(filename); //open whatever the filename is
string line=" ";//stores the string of numbers
string num1=" "; //stores the first number
string num2=" ";//stores the second number
string op=" ";//stores the operator
while (getline(myfile, line)) {
int len = line.length();
for (int i = 0; i < len; i++) {
if ((line[i] == '*') || (line[i] == '+' || line[i] == '-'))
op = line[i];
if (!isdigit(line[i]))
line[i] = ' ';
}
stringstream ss(line.c_str());
ss >> num1 >> num2;
int digitsPerN = stoi(digitsPerNode);
DoubleLinkedList l1(num1, digitsPerN);
DoubleLinkedList l2(num2, digitsPerN);
DoubleLinkedList l;
if (op == "+") {
l = l1 + l2;
l1.Print();
cout << "+";
l2.Print();
cout << "=";
l.Print();
cout << endl;
}
if (op == "*") {
l = l1 * l2;
l1.Print();
cout << "*";
l2.Print();
cout << "=";
l.Print();
cout << endl;
}
}
system("pause");
return 0;
} | true |
12be2e14f484c893e39b1fb2b548207b6c1be20e | C++ | ktchow1/threadpool | /src/test_coroutine_pc.cpp | UTF-8 | 3,330 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <thread>
#include <concepts>
#include <coroutine>
#include <exception>
struct pod_T
{
char a;
std::uint16_t n;
};
struct pod_U
{
char a;
char b;
char c;
};
inline std::ostream& operator<<(std::ostream& os, const pod_T& t)
{
os << "T = " << t.a << "_" << t.n;
return os;
}
inline std::ostream& operator<<(std::ostream& os, const pod_U& u)
{
os << "U = " << u.a << u.b << u.c;
return os;
}
// ********************************* //
// T = data from caller to coroutine
// U = data from coroutine to caller
// ********************************* //
template<typename T, typename U>
struct future
{
struct promise_type
{
future<T,U> get_return_object()
{
return future<T,U>
{
std::coroutine_handle<promise_type>::from_promise(*this)
};
}
void unhandled_exception(){}
std::suspend_never initial_suspend() { return {}; }
std::suspend_never final_suspend() { return {}; }
std::suspend_always yield_value(const U& u)
{
data_U = u;
return {};
}
T data_T; // from caller to coroutine
U data_U; // from coroutine to caller
};
// ***************************************** //
// *** Future construction / destruction *** //
// ***************************************** //
explicit future(std::coroutine_handle<promise_type> h_) : h(h_) {}
~future()
{
h.destroy();
}
// Mimic python : sink.send(data)
template<typename... ARGS>
void send_T_to_coroutine(ARGS&&... args) const // universal reference
{
h.promise().data_T = T{ std::forward<ARGS>(args)... };
h();
}
// Mimic python : data = next(source)
const U& next_U_from_coroutine() const
{
h();
return h.promise().data_U;
}
std::coroutine_handle<promise_type> h;
};
template<typename T, typename U>
struct awaitable
{
awaitable() : data_T_ptr(nullptr) {}
bool await_ready() const noexcept { return false; }
bool await_suspend(std::coroutine_handle<typename future<T,U>::promise_type> h)
{
data_T_ptr = &(h.promise().data_T);
// data_U_ptr = &(h.promise().data_U);
return true;
}
const T& await_resume() const noexcept
{
return *data_T_ptr;
}
T* data_T_ptr = nullptr;
// U* data_U_ptr = nullptr; // As U is transmitted by co_yield, no need to keep it here.
};
// ************************* //
// *** Example coroutine *** //
// ************************* //
[[nodiscard]] future<pod_T, pod_U> coroutine()
{
// Two suspensions in each loop
while(true)
{
const pod_T& t = co_await awaitable<pod_T, pod_U>{};
pod_U u;
u.a = t.a;
u.b = t.a + t.n;
u.c = t.a + t.n * 2;
std::cout << "\ncoroutine : input " << t << ", output " << u;
co_yield u;
}
}
void test_coroutine_pc()
{
auto f = coroutine();
for(std::uint16_t n=0; n!=10; ++n)
{
pod_T t{static_cast<char>('a'+n), n};
f.send_T_to_coroutine(t);
pod_U u = f.next_U_from_coroutine();
std::cout << "\ncaller : input " << t << ", output " << u;
}
std::cout << "\n\n";
}
| true |
8c860315a2c9873812b119605e3cb9360bad486c | C++ | marmyshev/OpenLP_transparency | /trans.cpp | UTF-8 | 901 | 2.578125 | 3 | [] | no_license | #include <QtCore>
#include <QtGui>
class View : public QGraphicsView
{
public:
View() : QGraphicsView() {
setAttribute(Qt::WA_TranslucentBackground);
setScene(new QGraphicsScene);
QGraphicsItem* i = scene()->addRect(10, 10, 40, 40, Qt::NoPen,
Qt::red);
i->setFlag(QGraphicsItem::ItemIsMovable);
}
protected:
void drawBackground(QPainter* p, const QRectF& rect) {
QPainter::CompositionMode c = p->compositionMode();
p->setCompositionMode(QPainter::CompositionMode_Source);
p->fillRect(rect, Qt::transparent);
p->setCompositionMode(c);
p->fillRect(rect, QColor(0, 0, 255, 120));
}
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
View v;
v.show();
return app.exec();
}
| true |
ff25d2e1685b37a64753e23f566ee2b1a7827fd3 | C++ | Kazuha-Li/LeetCode | /Cpp/876_Middle_of_the_Linked_List.cpp | UTF-8 | 2,450 | 3.765625 | 4 | [] | no_license | /*
https://leetcode.com/problems/middle-of-the-linked-list/
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
ref:
https://leetcode.com/problems/middle-of-the-linked-list/solution/
*/
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode* next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution_count_length {
public:
// Approach 1: 計算長度
// Time = O(n)
// Space = O(1)
ListNode* middleNode(ListNode* head) {
int length = 0;
ListNode* t = head;
while (t) {
length++;
t = t->next;
}
t = head;
length /= 2;
while (length > 0) {
length--;
t = t->next;
}
return t;
}
};
class Solution_array {
public:
// Approach 2: use array
// Time = O(n)
// Space = O(n)
ListNode* middleNode(ListNode* head) {
vector<ListNode*> res{head};
while (res.back()->next) {
res.push_back(res.back()->next);
}
return res[res.size() / 2];
}
};
class Solution_one_pass {
public:
// 利用fast、slow兩個指針
// fast 每次比 slow 多走一格
// Time = O(n)
// Space = O(1)
ListNode* middleNode(ListNode* head) {
ListNode *fast = head, *slow = head;
// 當List長度為偶數如果要第一個mid則條件為
// while(fast->next && fast->next->next)
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
int main() {
return 0;
} | true |
835fc6a9be6fca552f701cb4d903893e8de8f600 | C++ | genius52/leetcode | /src/cpp/number/1450. Number of Students Doing Homework at a Given Time.hpp | UTF-8 | 355 | 2.609375 | 3 | [] | no_license | #include <vector>
class Solution_1450 {
public:
int busyStudent(vector<int>& startTime, vector<int>& endTime, int queryTime) {
int cnt = 0;
int len = startTime.size();
for(int i = 0;i < len;i++){
if(startTime[i] <= queryTime && queryTime <= endTime[i])
cnt++;
}
return cnt;
}
}; | true |
be1f224896c8120fc4b9cfee8b6e5036ab058df1 | C++ | Shincey/thttpd | /src/tools/tools.h | UTF-8 | 4,262 | 2.828125 | 3 | [
"MIT"
] | permissive | #ifndef __TOOLS_H__
#define __TOOLS_H__
#include <cmath>
#include <chrono>
#include <string>
#include <vector>
#include <cstring>
#include "tassert.h"
namespace tool {
inline void smemset(void *__restrict dest, size_t max, int val, size_t n) {
tassert(n <= max, "over flow");
memset(dest, val, (max >=n) ? (n) : (max));
}
inline void smemcpy(void *__restrict dest, size_t max, const void *src, size_t n) {
tassert(n <= max, "over flow");
memcpy(dest, src, (max >=n) ? (n) : (max));
}
inline bool slocaltime(struct tm &ts, const time_t &tt) {
const struct tm *pt = localtime(&tt);
if (nullptr == pt) { return false; }
smemcpy(&ts, sizeof(ts), pt, sizeof(ts));
}
inline uint64_t milliseconds() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
inline uint64_t microseconds() {
return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
}
inline std::string now(const char *format = "%4d-%02d-%02d %02d:%02d:%02d") {
char strtime[64] = {0};
auto tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
struct tm ts;
slocaltime(ts, tt);
snprintf(strtime, sizeof(strtime), format, (int)ts.tm_year + 1900, (int)ts.tm_mon + 1, (int)ts.tm_mday, (int)ts.tm_hour, (int)ts.tm_min, (int)ts.tm_sec);
return strtime;
}
/**
* Convert timestamp to readable time representation
* @param timestamp : timestamp in milliseconds
* @param format : time format to convert
* @return : returns the formatted time.
*/
inline std::string time(const int64_t timestamp , const char *format = "%4d-%02d-%02d %02d:%02d:%02d") {
char strtime[128];
auto ms = std::chrono::milliseconds(timestamp);
auto tp = std::chrono::time_point<std::chrono::system_clock, std::chrono::milliseconds>(ms);
auto tt = std::chrono::system_clock::to_time_t(tp);
struct tm ts;
slocaltime(ts, tt);
snprintf(strtime, sizeof(strtime), format,
(int)ts.tm_year+1900,
(int)ts.tm_mon+1,
(int)ts.tm_mday,
(int)ts.tm_hour,
(int)ts.tm_min,
(int)ts.tm_sec);
return strtime;
}
inline std::string strip(const std::string &str, char ch=' ') {
if (str.empty()) return std::string();
int i = 0, j = str.size() - 1;
while (str[i] == ch) i++;
while (str[j] == ch) j--;
if (i > j) return std::string();
return str.substr(i, j - i + 1);
}
inline std::vector<std::string> split(const std::string &str, const std::string delimiter) {
if (str.empty()) return {};
std::vector<std::string> res;
std::string strs = str + delimiter;
size_t pos = strs.find(delimiter);
size_t len = strs.size();
while (pos != std::string::npos) {
std::string x = strs.substr(0, pos);
if (x != "") res.push_back(x);
strs = strs.substr(pos + delimiter.size(), len);
pos = strs.find(delimiter);
}
return res;
}
inline std::string itos(const int32_t val) {
char str[128] = {0};
snprintf(str, sizeof(str), "%d", val);
return std::string(str);
}
inline std::string ftos(const double val) {
char str[128] = {0};
snprintf(str, sizeof(str), "%f", val);
return std::string(str);
}
inline std::string& operator<<(std::string &target, const std::string &val) {
target += val;
return target;
}
inline std::string& operator<<(std::string &target, const char *val) {
target += std::string(val);
return target;
}
inline std::string& operator<<(std::string &target, const int32_t val) {
target += itos(val);
return target;
}
inline std::string& operator<<(std::string &target, const double val) {
target += ftos(val);
return target;
}
}
#endif // __TOOLS_H__ | true |
97438c6e8956af4ad60e6f8cee4b4ff2cec29618 | C++ | tbfe-de/mc-cppmodern | /Exercises/07_Thursday1_2/no_dupes_copy.cpp | UTF-8 | 2,329 | 3.421875 | 3 | [] | no_license | #include <algorithm>
#include <deque>
#include <iostream>
#include <iterator>
#include <list>
#include <set>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <forward_list>
#include <initializer_list>
#endif
template<typename InIt, typename OutIt>
OutIt no_dupes_copy(InIt b, InIt e, OutIt t) {
typedef std::set<typename std::iterator_traits<InIt>::value_type> SetType;
SetType s;
while (b != e) {
const typename SetType::value_type v = *b++;
if (s.insert(v).second)
*t++ = v;
}
return t;
}
int main() {
std::ostream_iterator<int> osit(std::cout, "; ");
int data1[] = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(data1, data1 + (sizeof data1 / sizeof *data1), osit);
std::cout << std::endl;
#if __cplusplus >= 201103L
std::vector<int> data2 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data2), std::end(data2), osit);
std::cout << std::endl;
std::list<int> data3 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data3), std::end(data3), osit);
std::cout << std::endl;
std::deque<int> data4 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data4), std::end(data4), osit);
std::cout << std::endl;
std::array<int, 15> data5 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data5), std::end(data5), osit);
std::cout << std::endl;
std::forward_list<int> data6 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data6), std::end(data6), osit);
std::cout << std::endl;
std::initializer_list<int> data7 = { 3, 1, 3, 7, 7, 2, 1, 3, 4, 4, 4, 1, 7, 1, 9 };
no_dupes_copy(std::begin(data7), std::end(data7), osit);
std::cout << std::endl;
#else
const std::size_t N = sizeof data1 / sizeof data1[0];
std::vector<int> data2(&data1[0], &data1[N]);
no_dupes_copy(data2.begin(), data2.end(), osit);
std::cout << std::endl;
std::list<int> data3(&data1[0], &data1[N]);
no_dupes_copy(data3.begin(), data3.end(), osit);
std::cout << std::endl;
std::deque<int> data4(&data1[0], &data1[N]);
no_dupes_copy(data4.end(), data4.end(), osit);
std::cout << std::endl;
#endif
}
| true |
44cf696e4fbae2ed22001ee6b2d2a7c2e4a7234b | C++ | minkukjo/Cpp-Algorithm | /BAEKJOON/1717.cpp | UTF-8 | 661 | 2.921875 | 3 | [] | no_license | #include <cstdio>
using namespace std;
int parent[1000001];
int Find(int x)
{
if (x == parent[x])
{
return x;
}
return parent[x] = Find(parent[x]);
}
void Union(int a, int b)
{
int x = Find(a);
int y = Find(b);
if (x != y)
{
parent[y] = x;
}
}
int main()
{
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i <= n; i++)
{
parent[i] = i;
}
int a, b, c;
for(int i=0; i<m; i++)
{
scanf("%d %d %d", &a, &b, &c);
if (a)
{
if (Find(b) == Find(c))
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
else
{
Union(b, c);
}
}
return 0;
} | true |
72077c62fca2e1bc560a234e9bb489fa26d6a66b | C++ | TheMartian0x48/CP | /USACO/2017/open_contest/silver/paired_up.cpp | UTF-8 | 1,343 | 2.546875 | 3 | [] | no_license |
/*
* TheMartian0x48
* USACO 2017 US Open Contest, Silver
* Problem 1. Paired Up
*/
#include <bits/stdc++.h>
using namespace std;
// clang-format off
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define per(i, a, b) for (int i = a; i >= (b); --i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
#define rll(x) x.rbegin(), x.rend()
#define sz(x) (int)x.size()
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using vi = vector<int>;
using vii = vector<long long>;
// (* read and write *)
template <class T>
void re(vector<T> &v, int n) {v.resize(n); for (auto &e : v) cin >> e;}
template <class T>
void re(vector<T> &v){for (auto &e : v) cin >> e;}
void usaco(string s) {freopen((s + ".in").c_str(), "r", stdin );freopen((s + ".out").c_str(), "w", stdout );}
// clang-format on
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
usaco("pairup");
int n; cin >> n;
vector<pii> v(n);
rep(i,0,n) cin >> v[i].second >> v[i].first;
sort(all(v));
ll res = 0;
int i = 0, j = n - 1;
while (i <= j) {
res = max(res, 0LL + v[i].first + v[j].first);
if (v[i].second > v[j].second) v[i].second -= v[j].second, j--;
else if (v[i].second < v[j].second) v[j].second -= v[i].second, i++;
else i++, j--;
}
cout << res;
}
| true |
d17769150eb1646368806c27544d134afb41f850 | C++ | arksm503/Praktikum9 | /soal6.3b/latihan.cpp | UTF-8 | 1,814 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int x;
void zmodus(float bil[], int n, float mds[])
{
int total[100];
int k=1;
x=0;
//urutkan kecil ke besar
for(int j=0; j<n; j++)
{
for(int i=(n-1); i>=0; i--)
{
if (bil[i]<bil[i-1]){
int temp;
temp=bil[i];
bil[i]=bil[i-1];
bil[i-1]=temp;
}
}
}
cout<<"Hasil Pengurutan : ";
for(int d=0; d<n; d++){
cout<< " "<<bil[d];
}cout<<endl;
//hitung berapa kali muncul tiap angka
for(int j=0; j<n; j++)
{
total[j]=0;
for(int i=0; i<n; i++)
{
if (bil[j]==bil[i]){
total[j]++;
}
}
}
//menentukan nilai yg sering muncul
for(int j=0; j<n; j++){
if (total[j]>k){
k=total[j];
}
}
//modus lebih dari satu
for(int j=0; j<n; j++)
{
if(x==0)
mds[x]=0;
else
mds[x]=mds[x-1];
if(total[j]==k)
{
if(bil[j]!=mds[x])
{
mds[x]=bil[j];
x++;
}
}
}
//jika semua angka muncul sama banyak
int z=0;
for(int j=0; j<n; j++)
{
if(total[j]==k){
z++;
}
}
if(z==n){
x=0;
}
}
int main()
{
int n;
float bil[100];
float mds[100];
cout<< "Input Banyaknya Bilangan : ";cin>>n;
for(int j=0; j<n; j++){
cout<< "Input Bilangan ke "<<(j+1)<<" : ";cin>>bil[j];
}
cout<<endl;
zmodus(bil,n,mds);
if(x==0)
cout<<"Tidak Ada Modus ! "<<endl;
else
{
cout<<"Modus : ";
for(int j=0; j<x; j++)
{
cout<<mds[j]<<" ";
}
}
}
| true |
337d9595addedb717f11ea7b64a061e26ee154cb | C++ | Rayenasa/CPlusPlus | /assignment_4/Annoyer.cpp | UTF-8 | 427 | 2.84375 | 3 | [] | no_license | /**
Assignment 4
Annoyer.cpp
Purpose: will make a beeping noise and print out a text
at the same time. This is the child class of Shower and Beeper.
Their doYourThing() function is called.
@author Victor Wernet
@version 1.0 26 october 2015
*/
#include "Annoyer.h"
using namespace std;
void Annoyer::start()
{
Shower::start();
Beeper::start();
}
void Annoyer::end()
{
Shower::end();
Beeper::end();
}
| true |