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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f2f466d447f0d5ff37af2023d0cc9370ecc4651c | C++ | shamanthMuroor/coding | /CodeForces/CppCodeForces/1183b-EqualizePrices.cpp | UTF-8 | 644 | 2.609375 | 3 | [] | no_license | // 130026419 Sep/27/2021 22:42UTC+5.5 shamanthmuroor 1183B - Equalize Prices GNU C++17 Accepted 46 ms 3800 KB
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int q;
cin >> q;
while(q--) {
int n, k;
cin >> n >> k;
vector<int> a(n);
for(int i=0; i<n; i++) {
cin >> a[i];
}
int min = *min_element(a.begin(), a.end());
int max = *max_element(a.begin(), a.end());
if(max - min > 2*k) {
cout << -1 << endl;
}
else {
cout << min + k << endl;
}
}
return 0;
} | true |
d4f19c8a5bb52039b7fb54c0560c7e673f41df0b | C++ | ash1247/DocumentsWindows | /CodeBlocks/Codeforces/Solved/Codeforces236A.cpp | UTF-8 | 423 | 2.765625 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
int main ( void )
{
string word;
int i = 0, j = 0;
cin >> word;
sort( word.begin(), word.end() );
word.erase( unique(word.begin(), word.end()), word.end() );
size_t length = word.length();
if( length % 2 == 0)
{
cout << "CHAT WITH HER!" << endl;
}
else
{
cout << "IGNORE HIM!" << endl;
}
return 0;
}
| true |
bea18ca54a354e9523bf45a3945e11d54d1a21f6 | C++ | ckymn/cpp | /Methods/sizeof.cpp | UTF-8 | 845 | 3.59375 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct byteNumber
{
int id;
char letter;
string name;
float idd;
double iddd;
};
int main()
{
cout << "Char : " << sizeof(char) << endl; //1-8bit
cout << "Integer : " << sizeof(int) << endl; //4-32bit
cout << "Float : " << sizeof(float) << endl; //4-32bit
cout << "Dobule : " << sizeof(double) << endl;//8-64bit
cout << "string : " << sizeof(string) << endl;//32-256bit
cout << "Struct : " << sizeof(byteNumber) << endl;//56-56*8bit (4+1+32+4+8+ compiler ekstradan veriyor)
int values[] = {1,23,4,4,5};
cout << "array : " << sizeof(values) << endl; //20-160bit (int degerler 4+4+4+4 = 20)
cout << "array boyutu : " << sizeof(values)/sizeof(values[0]) << endl; //5
cout << "array sayi degeri : " << sizeof(values[0]);//4
return 0;
} | true |
c7d5301a2a67fb585e5b86e4cf956353dbbb45d2 | C++ | JeastonCS/FlightPlanner_IterativeBacktracking | /tester.cpp | UTF-8 | 15,991 | 3.578125 | 4 | [] | no_license | //
// Created by Jack Easton on 3/25/2020.
//
#include "catch.hpp"
#include "DSString.h"
#include "ListNode.h"
#include "LinkList.h"
#include "LinkListIterator.h"
TEST_CASE ("ListNode class") {
SECTION ("constructor (int)") {
ListNode<int> node1(1);
REQUIRE( node1.getData() == 1 );
REQUIRE( node1.getNext() == nullptr );
REQUIRE( node1.getPrevious() == nullptr );
}
SECTION ("setters (int)") {
ListNode<int> node1(1);
ListNode<int> next(2);
ListNode<int> previous(0);
node1.setNext(&next);
node1.setPrevious(&previous);
REQUIRE( *node1.getNext() == next );
REQUIRE( *node1.getPrevious() == previous );
}
SECTION ("constructor (DSString)") {
ListNode<DSString> node1( "test" );
REQUIRE( node1.getData() == "test" );
REQUIRE( node1.getNext() == nullptr );
REQUIRE( node1.getPrevious() == nullptr );
}
SECTION ("setters (DSString)") {
ListNode<DSString> node1("during");
ListNode<DSString> next("after");
ListNode<DSString> previous("before");
node1.setNext(&next);
node1.setPrevious(&previous);
REQUIRE( *node1.getNext() == next );
REQUIRE( *node1.getPrevious() == previous );
}
}
TEST_CASE ("LinkList class") {
SECTION ("constructor (int)") {
LinkList<int> list1;
REQUIRE( list1.getSize() == 0 );
REQUIRE( list1.getHead() == nullptr );
REQUIRE( list1.getTail() == nullptr );
}
SECTION("push_back() / push_front() (int)") {
LinkList<int> list1;
list1.push_front(3);
REQUIRE( list1.getSize() == 1 );
REQUIRE( list1.getFront() == 3 );
REQUIRE( list1.getBack() == 3 );
list1.push_front(2);
REQUIRE( list1.getSize() == 2 );
REQUIRE( list1.getFront() == 2 );
REQUIRE( list1.getBack() == 3 );
LinkList<int> list2;
list2.push_back(2);
REQUIRE( list2.getSize() == 1 );
REQUIRE( list2.getFront() == 2 );
REQUIRE( list2.getBack() == 2 );
list2.push_back(3);
REQUIRE( list2.getSize() == 2 );
REQUIRE( list2.getFront() == 2 );
REQUIRE( list2.getBack() == 3 );
//back to list 1
list1.push_back(4);
REQUIRE( list1.getSize() == 3 );
REQUIRE( list1.getFront() == 2 );
REQUIRE( list1.getBack() == 4 );
list1.push_front(1);
REQUIRE( list1.getSize() == 4);
REQUIRE( list1.getFront() == 1 );
REQUIRE( list1.getBack() == 4 );
}
SECTION ("operator= (int)") {
LinkList<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
list1.push_back(4);
LinkList<int> list2;
list2 = list1;
REQUIRE( list2.getSize() == 4 );
REQUIRE( list2.getFront() == 1 );
REQUIRE( list2.getHead()->getNext()->getData() == 2 );
REQUIRE( list2.getTail()->getPrevious()->getData() == 3 );
REQUIRE( list2.getBack() == 4 );
LinkList<int> list3;
list3.push_back(119);
list3.push_back(221);
list3.push_back(329);
list3 = list1;
REQUIRE( list3.getSize() == 4 );
REQUIRE( list3.getFront() == 1 );
REQUIRE( list3.getHead()->getNext()->getData() == 2 );
REQUIRE( list3.getTail()->getPrevious()->getData() == 3 );
REQUIRE( list3.getBack() == 4 );
LinkList<int> list4;
LinkList<int> list5;
list5.push_back(9);
list4 = list5 = list1;
REQUIRE( list4.getSize() == 4 );
REQUIRE( list4.getFront() == 1 );
REQUIRE( list4.getHead()->getNext()->getData() == 2 );
REQUIRE( list4.getTail()->getPrevious()->getData() == 3 );
REQUIRE( list4.getBack() == 4 );
REQUIRE( list5.getSize() == 4 );
REQUIRE( list5.getFront() == 1 );
REQUIRE( list5.getHead()->getNext()->getData() == 2 );
REQUIRE( list5.getTail()->getPrevious()->getData() == 3 );
REQUIRE( list5.getBack() == 4 );
}
SECTION("pop_front/pop_back (int)") {
LinkList<int> list1;
list1.pop_back();
list1.pop_front();
list1.push_back(1);
list1.pop_front();
REQUIRE(list1.getSize() == 0);
REQUIRE(list1.getHead() == nullptr);
REQUIRE(list1.getTail() == nullptr);
list1.push_back(1);
list1.pop_back();
REQUIRE(list1.getSize() == 0);
REQUIRE(list1.getHead() == nullptr);
REQUIRE(list1.getTail() == nullptr);
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
list1.pop_front();
REQUIRE(list1.getSize() == 2);
REQUIRE(list1.getFront() == 2);
REQUIRE(list1.getBack() == 3);
REQUIRE(list1.getHead()->getPrevious() == nullptr);
REQUIRE(list1.getHead()->getNext()->getData() == 3);
list1.push_front(1);
list1.pop_back();
REQUIRE(list1.getSize() == 2);
REQUIRE(list1.getFront() == 1);
REQUIRE(list1.getBack() == 2);
REQUIRE(list1.getTail()->getNext() == nullptr);
REQUIRE(list1.getTail()->getPrevious()->getData() == 1);
}
SECTION("contains() (int)") {
LinkList<int> list1;
bool found;
found = list1.contains(3);
REQUIRE(found == false);
list1.push_back(1);
found = list1.contains(1);
REQUIRE(found == true);
list1.push_back(2);
found = list1.contains(1);
REQUIRE(found == true);
found = list1.contains(2);
REQUIRE(found == true);
found = list1.contains(3);
REQUIRE(found == false);
list1.push_front(18);
list1.push_back(29);
found = list1.contains(2);
REQUIRE(found == true);
found = list1.contains(18);
REQUIRE(found == true);
found = list1.contains(29);
REQUIRE(found == true);
found = list1.contains(-1);
REQUIRE(found == false);
list1.pop_back();
found = list1.contains(29);
REQUIRE(found == false);
found = list1.contains(2);
REQUIRE(found == true);
}
//--------------------------------------------------------------------------------------------------------------------//
SECTION ("constructor (DSString)") {
LinkList<DSString> list1;
REQUIRE( list1.getSize() == 0 );
REQUIRE( list1.getHead() == nullptr );
REQUIRE( list1.getTail() == nullptr );
}
SECTION("push_back() / push_front() (DSString)") {
LinkList<DSString> list1;
list1.push_front("c");
REQUIRE( list1.getSize() == 1 );
REQUIRE( list1.getFront() == "c" );
REQUIRE( list1.getBack() == "c" );
list1.push_front("b");
REQUIRE( list1.getSize() == 2 );
REQUIRE( list1.getFront() == "b" );
REQUIRE( list1.getBack() == "c" );
LinkList<DSString> list2;
list2.push_back("b");
REQUIRE( list2.getSize() == 1 );
REQUIRE( list2.getFront() == "b" );
REQUIRE( list2.getBack() == "b" );
list2.push_back("c");
REQUIRE( list2.getSize() == 2 );
REQUIRE( list2.getFront() == "b" );
REQUIRE( list2.getBack() == "c" );
list1.push_back("d");
REQUIRE( list1.getSize() == 3 );
REQUIRE( list1.getFront() == "b" );
REQUIRE( list1.getBack() == "d" );
list1.push_front("a");
REQUIRE( list1.getSize() == 4);
REQUIRE( list1.getFront() == "a" );
REQUIRE( list1.getBack() == "d" );
}
SECTION ("operator= (DSString)") {
LinkList<DSString> list1;
list1.push_back("a");
list1.push_back("b");
list1.push_back("c");
list1.push_back("d");
LinkList<DSString> list2;
list2 = list1;
REQUIRE( list2.getSize() == 4 );
REQUIRE( list2.getFront() == "a" );
REQUIRE( list2.getHead()->getNext()->getData() == "b" );
REQUIRE( list2.getTail()->getPrevious()->getData() == "c" );
REQUIRE( list2.getBack() == "d" );
LinkList<DSString> list3;
list3.push_back("x");
list3.push_back("y");
list3.push_back("z");
list3 = list1;
REQUIRE( list3.getSize() == 4 );
REQUIRE( list2.getFront() == "a" );
REQUIRE( list2.getHead()->getNext()->getData() == "b" );
REQUIRE( list2.getTail()->getPrevious()->getData() == "c" );
REQUIRE( list2.getBack() == "d" );
LinkList<DSString> list4;
LinkList<DSString> list5;
list5.push_back("h");
list4 = list5 = list1;
REQUIRE( list4.getSize() == 4 );
REQUIRE( list2.getFront() == "a" );
REQUIRE( list2.getHead()->getNext()->getData() == "b" );
REQUIRE( list2.getTail()->getPrevious()->getData() == "c" );
REQUIRE( list2.getBack() == "d" );
REQUIRE( list5.getSize() == 4 );
REQUIRE( list2.getFront() == "a" );
REQUIRE( list2.getHead()->getNext()->getData() == "b" );
REQUIRE( list2.getTail()->getPrevious()->getData() == "c" );
REQUIRE( list2.getBack() == "d" );
}
SECTION("pop_front/pop_back (DSString)") {
LinkList<DSString> list1;
list1.pop_back();
list1.pop_front();
list1.push_back("a");
list1.pop_front();
REQUIRE(list1.getSize() == 0);
REQUIRE(list1.getHead() == nullptr);
REQUIRE(list1.getTail() == nullptr);
list1.push_back("a");
list1.pop_back();
REQUIRE(list1.getSize() == 0);
REQUIRE(list1.getHead() == nullptr);
REQUIRE(list1.getTail() == nullptr);
list1.push_back("a");
list1.push_back("b");
list1.push_back("c");
list1.pop_front();
REQUIRE(list1.getSize() == 2);
REQUIRE(list1.getFront() == "b");
REQUIRE(list1.getBack() == "c");
REQUIRE(list1.getHead()->getPrevious() == nullptr);
REQUIRE(list1.getHead()->getNext()->getData() == "c");
list1.push_front("a");
list1.pop_back();
REQUIRE(list1.getSize() == 2);
REQUIRE(list1.getFront() == "a");
REQUIRE(list1.getBack() == "b");
REQUIRE(list1.getTail()->getNext() == nullptr);
REQUIRE(list1.getTail()->getPrevious()->getData() == "a");
}
SECTION("isEmpty (both)") {
LinkList<int> intList;
LinkList<DSString> stringList;
REQUIRE(intList.isEmpty());
REQUIRE(stringList.isEmpty());
intList.push_back(3);
REQUIRE(!intList.isEmpty());
stringList.push_back("a");
REQUIRE(!stringList.isEmpty());
intList.pop_back();
REQUIRE(intList.isEmpty());
stringList.pop_back();
REQUIRE(stringList.isEmpty());
}
//----------------------------------------------------------------------------------------------------------------//
SECTION("Iterable functionality (int)") {
LinkList<int> list;
LinkListIterator<int> iter;
REQUIRE(iter.getCurrIndex() == -1);
REQUIRE(iter.getCurrPosition() == nullptr);
list.push_back(1);
iter = list.begin();
REQUIRE(iter.getCurrPosition()->getData() == 1);
REQUIRE(iter.getCurrIndex() == 0);
iter = list.end();
REQUIRE(iter.getCurrPosition()->getData() == 1);
REQUIRE(iter.getCurrIndex() == 0);
list.push_back(2);
list.push_back(3);
list.push_back(4);
iter = list.begin();
REQUIRE(iter.getCurrPosition()->getData() == 1);
REQUIRE(iter.getCurrIndex() == 0);
iter = list.end();
REQUIRE(iter.getCurrPosition()->getData() == 4);
REQUIRE(iter.getCurrIndex() == 3);
//written out for loop - backwards
iter = list.end();
REQUIRE(list.at(iter) == 4);
iter.operator--();
REQUIRE(list.at(iter) == 3);
iter.operator--();
REQUIRE(list.at(iter) == 2);
iter.operator--();
REQUIRE(iter >= list.begin());
REQUIRE(list.at(iter) == 1);
iter.operator--();
REQUIRE( !(iter >= list.begin()) );
//written out for loop - forwards
iter = list.begin();
REQUIRE(list.at(iter) == 1);
iter.operator++();
REQUIRE(list.at(iter) == 2);
iter.operator++();
REQUIRE(list.at(iter) == 3);
iter.operator++();
REQUIRE(iter <= list.end());
REQUIRE(list.at(iter) == 4);
iter.operator++();
REQUIRE( !(iter <= list.end()) );
//next/hasNext
iter = list.begin();
REQUIRE(iter.hasNext());
iter = list.end();
iter.operator++();
REQUIRE(!iter.hasNext());
iter = list.begin();
REQUIRE(iter.next() == 1);
REQUIRE(iter.next() == 2);
REQUIRE(iter.next() == 3);
REQUIRE(iter.hasNext());
REQUIRE(iter.next() == 4);
//previous/hasPrevious
iter = list.end();
REQUIRE(iter.hasPrevious());
iter = list.begin();
iter.operator--();
REQUIRE(!iter.hasPrevious());
iter = list.end();
REQUIRE(iter.previous() == 4);
REQUIRE(iter.previous() == 3);
REQUIRE(iter.previous() == 2);
REQUIRE(iter.hasPrevious());
REQUIRE(iter.previous() == 1);
}
SECTION("Iterable functionality (DSString)") {
LinkList<DSString> list;
LinkListIterator<DSString> iter;
REQUIRE(iter.getCurrIndex() == -1);
REQUIRE(iter.getCurrPosition() == nullptr);
list.push_back("1");
iter = list.begin();
REQUIRE(iter.getCurrPosition()->getData() == "1");
REQUIRE(iter.getCurrIndex() == 0);
iter = list.end();
REQUIRE(iter.getCurrPosition()->getData() == "1");
REQUIRE(iter.getCurrIndex() == 0);
list.push_back("2");
list.push_back("3");
list.push_back("4");
iter = list.begin();
REQUIRE(iter.getCurrPosition()->getData() == "1");
REQUIRE(iter.getCurrIndex() == 0);
iter = list.end();
REQUIRE(iter.getCurrPosition()->getData() == "4");
REQUIRE(iter.getCurrIndex() == 3);
//written out for loop - backwards
iter = list.end();
REQUIRE(list.at(iter) == "4");
iter.operator--();
REQUIRE(list.at(iter) == "3");
iter.operator--();
REQUIRE(list.at(iter) == "2");
iter.operator--();
REQUIRE(iter >= list.begin());
REQUIRE(list.at(iter) == "1");
iter.operator--();
REQUIRE( !(iter >= list.begin()) );
//written out for loop - forwards
iter = list.begin();
REQUIRE(list.at(iter) == "1");
iter.operator++();
REQUIRE(list.at(iter) == "2");
iter.operator++();
REQUIRE(list.at(iter) == "3");
iter.operator++();
REQUIRE(iter <= list.end());
REQUIRE(list.at(iter) == "4");
iter.operator++();
REQUIRE( !(iter <= list.end()) );
//next/hasNext
iter = list.begin();
REQUIRE(iter.hasNext());
iter = list.end();
iter.operator++();
REQUIRE(!iter.hasNext());
iter = list.begin();
REQUIRE(iter.next() == "1");
REQUIRE(iter.next() == "2");
REQUIRE(iter.next() == "3");
REQUIRE(iter.hasNext());
REQUIRE(iter.next() == "4");
//previous/hasPrevious
iter = list.end();
REQUIRE(iter.hasPrevious());
iter = list.begin();
iter.operator--();
REQUIRE(!iter.hasPrevious());
iter = list.end();
REQUIRE(iter.previous() == "4");
REQUIRE(iter.previous() == "3");
REQUIRE(iter.previous() == "2");
REQUIRE(iter.hasPrevious());
REQUIRE(iter.previous() == "1");
}
} | true |
6d221d45bce3d1047995b591c2a7b2ae627ef432 | C++ | zeyec/CUDA-RSA | /src/shifts.cpp | WINDOWS-1251 | 1,478 | 3.375 | 3 | [] | no_license | #include "shifts.h"
#include "Constants.h"
// 32- 1 carry flag
int shr (unsigned int &input, int leftBit){
int CF;
CF = input & 0x1 ;
input >>= 1;
if ( leftBit == 1 ) {
input |= 0x80000000;
} else {
input &= 0x7FFFFFFF;
}
return CF;
}
// 32- 1 carry flag
int shl (unsigned int &input, int rightBit){
int CF;
CF = ( input & ( 1 << INT_SIZE - 1 ) ) == ( 1 << INT_SIZE - 1 );
input <<= 1;
input &= 0xFFFFFFFE;
input |= rightBit;
return CF;
}
// 64- 1 carry flag
int shr_long (unsigned long long &input, int leftBit){
int CF;
CF = input & 0x1 ;
input >>= 1;
if ( leftBit == 1 ) {
input |= 0x8000000000000000;
} else {
input &= 0x7FFFFFFFFFFFFFFF;
}
return CF;
}
// " " 1 carry flag
int shiftToLeftVariable ( unsigned int *input ) {
int CF = 0;
for (int i = MAX - 1; i >= 0; i--) {
CF = shl( input[ i ], CF );
}
return CF;
}
// " " 1 carry flag
int shiftToRightVariable ( unsigned int *input ) {
int CF = 0;
for (int i = 0; i < MAX; i++) {
CF = shr( input[ i ], CF );
}
return CF;
}
| true |
93b90d2f7851878e2ca1b65d797ba32ed56524d8 | C++ | onealabdulrahim/Programming-Design-Concepts-CSCE121 | /Homework/Homework 5/hw5pr3.cpp | UTF-8 | 2,473 | 3.25 | 3 | [] | no_license | //Oneal Abdulrahim
//CSCE 121-504
//Due: March 23, 2016
//hw5pr3.cpp
#include "std_lib_facilities_4.h"
#include "Simple_window.h"
#include "Graph.h"
void draw_board(int x, int y) {
Simple_window window(Point(200,200), x, y,"HW5PR3: Checkerboard");
//checkerboard is reliant on window size,
//will do its best to fit largest possible squares (must fit to window dimensions)
//if dimensions are not 1x1, it will morph squares into rectangles
int width = x / 8; //width of each rectangle
int height = y / 8; //height of each rectangle
const Color moss_green(0xADDFAD00); //HEX for both of the requested colors
const Color cherry_blossom_pink(0xFFB7C500);
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
Rectangle *square = new Rectangle(Point(width * i, height * j), width, height);
if ((i + j) % 2 == 1) {
square->set_fill_color(moss_green); //on odd blocks, make it green
square->set_color(moss_green);
window.attach(*square);
if (j <= 2) { //if on rows 1, 2, 3, fill in the red pieces
Circle *red_piece = new Circle(Point(width * i + (width / 2), height * j + (height / 2)), width / 4);
Circle *shadow = new Circle(Point(width * i + (width / 2), height * j + (height / 2) + width / 32), width / 3.8);
red_piece -> set_color(Color::black);
red_piece -> set_fill_color(0xC4023300);
shadow -> set_fill_color(0x34343400);
window.attach(*shadow);
window.attach(*red_piece);
}
else if (j >= 5) { //if on rows 6, 7, 8, fill in the white pieces
Circle *white_piece = new Circle(Point(width * i + (width / 2), height * j + (height / 2)), width / 4);
Circle *shadow = new Circle(Point(width * i + (width / 2), height * j + (height / 2) + width / 32), width / 3.8);
white_piece -> set_color(Color::black);
white_piece -> set_fill_color(Color::white);
shadow -> set_fill_color(0x34343400);
window.attach(*shadow);
window.attach(*white_piece);
}
}
else {
square->set_fill_color(cherry_blossom_pink); //on even ones, make it pink
square->set_color(cherry_blossom_pink);
window.attach(*square);
}
}
}
window.wait_for_button();
}
int main()
try {
if(H112 != 201401L)error("Error: incorrect std_lib_facilities_4.h version ",
H112);
draw_board(1000, 1000);
return 0;
}
catch(exception& e) {
cerr << "exception: " << e.what() << '\n';
return 1;
}
catch (...) {
cerr << "Some exception\n";
return 2;
} | true |
7d78dea386dbc2f877bef739ef5f17ed8e86cff0 | C++ | he44/Practice | /codeforces/339/a.cpp | UTF-8 | 639 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include <vector>
int main()
{
std::string input;
std::cin >> input;
std::vector<int> counts(3, 0);
for (int i = 0; i < input.size(); ++i)
{
if (input[i] == '+')
{
continue;
} else
{
counts[input[i] - '1'] += 1;
}
}
bool first = true;
for (int i = 0; i < counts.size(); ++i)
{
for (int j = 0; j < counts[i]; ++j)
{
if (!first)
{
std::cout << "+";
}
std::cout << (char('1' + i));
first = false;
}
}
return 0;
}
| true |
be801aa3e192f8ce2f57448ad40434e7a08ba491 | C++ | vallis/EMRI_Kludge_Suite | /src/numrec/NRsplint.cc | UTF-8 | 1,034 | 2.828125 | 3 | [] | no_license | #include "Globals.h"
#include "NRUtil.h"
void splint(Real xa[], Real ya[], Real y2a[], int n, Real x, Real *y)
{
int klo, khi, k;
Real h, b, a;
klo = 1; khi = n;
while (khi - klo > 1) {
k = (khi + klo) >> 1;
if (xa[k] > x) khi = k;
else klo = k;
}
h = xa[khi] - xa[klo];
if (h == 0.0) Die("Bad xa input to routine splint");
a = (xa[khi] - x)/h;
b = (x - xa[klo])/h;
*y = a*ya[klo] + b*ya[khi] +
((a*a*a - a)*y2a[klo] + (b*b*b - b)*y2a[khi])*(h*h)/6.0;
}
//
// Splint for complex functions of real arguments
//
void splint_complex(Real xa[], Complex ya[], Complex y2a[], int n,
Real x, Complex *y)
{
int klo, khi, k;
Real h, b, a;
klo = 1; khi = n;
while (khi - klo > 1) {
k = (khi + klo) >> 1;
if (xa[k] > x) khi = k;
else klo = k;
}
h = xa[khi] - xa[klo];
if (h == 0.0) Die("Bad xa input to routine splint_complex");
a = (xa[khi] - x)/h;
b = (x - xa[klo])/h;
*y = a*ya[klo] + b*ya[khi] +
((a*a*a - a)*y2a[klo] + (b*b*b - b)*y2a[khi])*(h*h)/6.0;
}
| true |
1f9ecc5bcc520eeec28b79364521aa272a44a1ac | C++ | Ralphson/CRC_detector | /src/creator.cc | UTF-8 | 4,717 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include "creator.h"
using namespace std;
int Creator::genData(int dataLength, int * p)
{
if (! p)
{
if (crcLength) len = dataLength + crcLength - 1;
else if (hammingLength) len = dataLength + hammingLength;
else
{
cout << "setCrcCode First!" << endl;
return 0;
}
delete[] data;
data = new int[len];
p = this->data;
this->dataLength = dataLength;
}
int r; //随机数
srand((int)time(NULL));
for(int i=0; i<dataLength; i++)
{
r = rand()%2;
p[i]= r;
}
p[0] = 1;
cout << "随机数据为:";
show(p, dataLength);
}
int Creator::genCRC()
{
if (! crcLength || ! dataLength)
{
cout << "crc长度为0" << endl;
return 1;
}
this->fillZeroAF(data, dataLength, crcLength);
//计算
int shift = 0;
int answer[crcLength]; //计算答案
// this->machine(data, crcCode, answer, crcLength);
this->oper_machine(data, crcCode, answer, crcLength);
for(int i=crcLength; i<len + 1;)
{
this->oper_machine(answer, crcCode, answer, crcLength);
// show(answer, crcLength);
//跟新结果:将结果往左移并且从数据中补齐尾部
shift = shift_L(answer, crcLength);
// show(answer, crcLength);
for(int j=shift-1, k = 1; j>=0; j--, k ++)
{
// cout << i << endl;
answer[crcLength-1 - j] = data[i];
i ++;
if (i >= len)
{
int true_len = crcLength - (shift - k);
// cout << shift << ":" << k << ":" << j << endl;
// show(answer, crcLength);
if (true_len == crcLength)
{
this->oper_machine(answer, crcCode, answer, crcLength);
for (int q = 0; q < crcLength - 1; q++)
{
target[q] = answer[q + 1];
}
}
else if (true_len == crcLength - 1)
{
for (int k = 0; k < crcLength - 1; k++)
{
target[k] = answer[k];
}
}
else
{
for (int k = 0; k < crcLength - 1; k++)
{
if (k < crcLength - 1 - true_len)
{
target[k] = 0;
}
else
{
target[k] = answer[k - (crcLength - 1 - true_len)];
}
}
}
cout << "冗余码:";
show(target, crcLength - 1);
cout << "最终结果:";
stickData();
show(data, len);
// p = new int[len];
// for (int k = 0; k < len; k++)
// {
// p[k] = data[k];
// }
// show(p, len);
return len;
}
}
// cout << "---" << i - crcLength << "---" << endl;
// show(answer, crcLength);
}
}
int Creator::genHamming()
{
if (! dataLength)
{
cout << "没有数据" << endl;
return 1;
}
//数据补齐海明码位
int _data[len];
for (int i = 0; i < hammingLength; i++)
_data[hammingCode[i]] = -1;
for (int i = 0, k = 0; i < len; i++)
{
if (_data[i] == -1)
{
k++;
continue;
}
else
_data[i] = data[i - k];
}
for (int i = 0; i < len; i++)
{
data[i] = _data[i];
}
cout << "待处理的数据";
show(data, len);
// 生成检测位
for (int i = 0; i < hammingLength; i++)
{
int dector[len] = {};
int flag = pow(2, i + 1);
for (int j = hammingCode[i]; j < len; j += flag)
{
for (int k = 0; k < hammingCode[i] + 1; k++)
{
if (j + k < len)
dector[j + k] = 1;
else
break;
}
}
dector[hammingCode[i]] = 0;
int answer = 0;
for (int j = 0; j < len; j++)
{
if (dector[j])
answer = data[j] ^ answer;
}
data[hammingCode[i]] = answer;
}
cout << "生成的海明码:";
show(data, len);
return len;
}
| true |
cd539e5255dde7c353393384f119492c8e624ac3 | C++ | WildBoarGonnaGo/42-Piscine-CPP | /day05/ex03/main.cpp | UTF-8 | 916 | 2.671875 | 3 | [] | no_license | #include "ShrubberyCreationForm.hpp"
#include "PresidentialPardonForm.hpp"
#include "RobotomyRequestForm.hpp"
#include "Bureaucrat.hpp"
#include "Intern.hpp"
#include <cstdlib>
#include <ctime>
int main(void)
{
srand(time(NULL));
Intern someRandomIntern;
Form *rrf;
Bureaucrat donald("Donald Trump", 1);
rrf = someRandomIntern.makeForm("robotomy request", "Bender");
donald.executeForm(*rrf);
rrf->beSigned(donald);
donald.executeForm(*rrf);
delete rrf;
std::cout << std::endl;
rrf = someRandomIntern.makeForm("ShrubberyCreationForm", "Bush_Junior");
rrf->beSigned(donald);
donald.executeForm(*rrf);
delete rrf;
std::cout << std::endl;
rrf = someRandomIntern.makeForm("presidential pardon", donald.getName());
rrf->beSigned(donald);
donald.executeForm(*rrf);
delete rrf;
std::cout << std::endl;
rrf = someRandomIntern.makeForm("Monka's revenge", donald.getName());
delete rrf;
return (0);
} | true |
a91fdf2246a9fb2173fed1f63b58d6949fcf8ae0 | C++ | Zingam/PureCpp | /delete-this/src/main.cpp | UTF-8 | 1,764 | 4.125 | 4 | [] | no_license | // Example program
#include <cassert>
#include <iostream>
#include <string>
class TheClass
{
public:
TheClass(std::string name)
: name(name)
{
std::cout << "\tObject \"" << this->name << "\" of class TheClass was constructed" << std::endl;
}
virtual ~TheClass()
{
std::cout << "\tObject \"" << this->name << "\" of class TheClass was destructed" << std::endl << std::endl;
}
void DeleteMe()
{
std::cout << "\tDelete the class from within!" << std::endl;
delete this;
}
void ToString()
{
std::cout << "\tObject \"" << this->name << "\" of class TheClass" << std::endl;
}
private:
std::string name;
};
int main()
{
std::cout << "\nStep 1.: Create object \"First\":" << std::endl;
TheClass theClass("First");
theClass.ToString();
// Undefined behavior - don't do this. You can use 'delete this' only on object created by 'new'.
//theClass.DeleteMe();
std::cout << "\nStep 2.: Create object \"Second\":" << std::endl;
TheClass* theClassAgain = new TheClass("Second");
theClassAgain->ToString();
theClassAgain->DeleteMe();
assert(nullptr != theClassAgain);
// Calling a method on a 'null pointer' is 'undefined behavior'.
//theClassAgain->ToString();
// Deleting an invalid pointer is 'undefined behavior'.
//delete theClassAgain;
theClassAgain = nullptr;
// Calling a method on a 'null pointer' is an 'undefined behavior'.
//theClassAgain->ToString();
// Deleting a 'null pointer' gets ignored and there is no need to check a 'null pointer' gets deleted.
delete theClassAgain;
std::cout << "\ntheClass(\"First\") object will be destroyed on exit:" << std::endl;
return 0;
}
| true |
0a864db382dbbd4508d3c5ce16d94c00ac0b91d8 | C++ | mtbtaiyyab/Placement-Program | /oddocc.cpp | UTF-8 | 369 | 3.53125 | 4 | [] | no_license | #include<iostream>
using namespace std;
int findres(int arr[],int size){
int res=arr[0];
for(int i=1;i<size;i++){
res=res^arr[i];
}
return res;
}
int main(){
int size;
cout<<"Enter size\t";
cin>>size;
cout<<"Enter Array\n";
int arr[size];
for(int i=0;i<size;i++){
cin>>arr[i];
}
int res= findres(arr,size);
cout<<"\n Odd occuring element is\t"<<res;
}
| true |
3cd4a99838119ea7c255a33877ddc06b20fb456c | C++ | ExitStatus-1/hanoi | /stack.cpp | UTF-8 | 925 | 3.40625 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<math.h>
#include "stack.h"
#include "disc.h"
using namespace std;
Stack::Stack()
{
pTop = NULL;
}
void Stack::push(void* inData)
{
Node* newnode = (Node*) malloc(sizeof(Node));
newnode->data = inData;
if(pTop == NULL){
pTop = newnode;
newnode->pNext = NULL;
}
else{
Node* previous = pTop;
newnode->pNext = previous;
pTop = newnode;
}
}
void* Stack::pop()
{
Node* temp = new Node;
temp = pTop;
void* data = temp->data;
pTop = temp->pNext;
delete temp;
return data;
}
void* Stack::top()
{
return pTop;
}
bool Stack::empty()
{
if(pTop == NULL){
return true;
}
return false;
}
void Stack::display()
{
Node *p1;
p1 = pTop;
while (p1 != NULL)
{
cout<< ((Disc*)(p1->data))->toString()<<"\t";
p1 = p1->pNext;
}
cout<<endl;
}
| true |
622821875c1e75ad8a2b1ddbeeef6b813a5a90a5 | C++ | PYChih/CppPrimer | /ch14_Overloaded_Operations_and_Conversions/exercise_14_38.cc | UTF-8 | 989 | 3.546875 | 4 | [] | no_license | // Exercise 14.38
// Write a class that tests whether the length
// of a given string matches a given bound.
// Use that object to write a program
// to report how many words in an input
// file are of sizes 1 through 10 inclusive.
#include <cstddef>
#include <iostream>
#include <string>
#include <fstream>
#include <map>
using std::string;
class IsInBound {
public:
IsInBound(std::size_t low, std::size_t upp) : _lower(low), _upper(upp) { }
bool operator() (const string &s) const {
return s.size() >= _lower && s.size() <= _upper;
}
private:
std::size_t _lower = 1;
std::size_t _upper = 10;
};
int main() {
std::map<std::size_t, std::size_t> count_table;
std::ifstream f("data/finding_cycle_start");
string s;
IsInBound iib(1, 10);
while (f >> s) {
// std::cout << s << std::endl;
if (iib(s)) {
++count_table[1];
}
}
// print
for (auto p : count_table) {
std::cout << "count in range [1, 10] : " << p.second << std::endl;
}
}
| true |
60734d1f96262f7806992252b7322364083a49a3 | C++ | gowthamv441/interview | /arrays/print_sub_set.cpp | UTF-8 | 605 | 3.34375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void print_subset(vector<int> arr)
{
int n=arr.size();
n=1<<n;
for(int i=0;i<n;i++)
{
int j=1;
int index=0;
cout<<"Set :: "<< i+1<<endl;
cout<<"{ ";
while(j<=i)
{
if(j&i)
{
cout<<arr[index]<<" ";
}
j=j<<1;
index++;
}
cout<<"}\n===========================================\n";
}
}
main()
{
/* BEWARE PRINTS ALL 10,48,576 SUBSETS HAHAHA!!! */
vector<int> arr={100,200,300,400,500,600,700,800,900,1000,1100,1200,1300,1400,1500,1600,1700,1800,1900,2000};
print_subset(arr);
}
| true |
7faac71d23765721689fe21d1af8c2d4eeb81272 | C++ | s-nandi/contest-problems | /computational-geometry/convex-hull/rotating-calipers/playing_the_slots.cpp | UTF-8 | 1,435 | 3.171875 | 3 | [] | no_license | // convex polygon width (rotating calipers)
// https://open.kattis.com/problems/playingtheslots
// 2018 Mid-Atlantic Regional
#include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-9;
const long double INF = 1e20;
typedef long double ptT;
struct pt
{
ptT x, y;
pt operator - (const pt &o) const {return {x - o.x, y - o.y};}
ptT operator ^ (const pt &o) const {return x * o.y - y * o.x;}
ptT norm2() const {return x * x + y * y;}
};
ptT distLine(const pt &a, const pt &b, const pt &p) {return abs((p - a) ^ (b - a)) / sqrt((b - a).norm2());}
int orientation(const pt &o, const pt &a, const pt &b)
{
ptT cp = (b - o) ^ (a - o);
return cp > EPS ? 1 : (cp < -EPS ? -1 : 0);
} //cw: 1, ccw: -1, col: 0
typedef vector <pt> polygon;
int next(int i, int n, int st = 1){return (i + st) % n;};
const pt origin = {0, 0};
ptT width(const polygon &poly)
{
int n = poly.size();
long double res = INF;
for (int i = 0, j = 1; i < n; ++i)
{
for(; ; j = next(j, n))
{
if (orientation(origin, poly[next(i, n)] - poly[i], poly[next(j, n)] - poly[j]) != 1)
break;
}
res = min(res, distLine(poly[i], poly[next(i, n)], poly[j]));
}
return res;
}
int main()
{
int n;
cin >> n;
polygon poly(n);
for (auto &p: poly)
cin >> p.x >> p.y;
cout << fixed << setprecision(11) << width(poly) << endl;
}
| true |
1ff7d894e5744fcdca9ae3db7abe3adc6b92d91e | C++ | CompPhysics/ComputationalPhysics | /doc/Programs/LecturePrograms/programs/NumericalIntegration/cpp/program1.cpp | UTF-8 | 1,371 | 3.296875 | 3 | [
"CC0-1.0"
] | permissive | #include <iostream>
#include "lib.h"
using namespace std;
// Here we define various functions called by the main program
double int_function(double x);
// Main function begins here
int main()
{
int n;
double a, b;
cout << "Read in the number of integration points" << endl;
cin >> n;
cout << "Read in integration limits" << endl;
cin >> a >> b;
// reserve space in memory for vectors containing the mesh points
// weights and function values for the use of the gauss-legendre
// method
double *x = new double [n];
double *w = new double [n];
// set up the mesh points and weights
gauleg(a, b,x,w, n);
// evaluate the integral with the Gauss-Legendre method
// Note that we initialize the sum
double int_gauss = 0.;
for ( int i = 0; i < n; i++){
int_gauss+=w[i]*int_function(x[i]);
}
// final output
cout << "Trapez-rule = " << trapezoidal_rule(a, b,n, &int_function)
<< endl;
cout << "Simpson's rule = " << simpson(a, b,n, &int_function)
<< endl;
cout << "Gaussian quad = " << int_gauss << endl;
delete [] x;
delete [] w;
return 0;
} // end of main program
// this function defines the function to integrate
double int_function(double x)
{
double value = 4./(1.+x*x);
return value;
} // end of function to evaluate
| true |
4c24d198df32feb210b0fb7b08fde7e7b38b60a9 | C++ | Cordylidae/BlackJack | /BlackJack/BlackJack/Deck.cpp | UTF-8 | 2,099 | 3.203125 | 3 | [] | no_license | #include"Deck.h"
#include"TextureManager.h"
#include<algorithm>
#include<thread>
Deck::Deck(double x,double y):xpos(x),ypos(y)
{
std::shared_ptr<Card> card;
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 14; j++)
{
std::string part = ""; int score = 10; bool isAce = false;
switch (i)
{
case 0:
part += "Heart";
break;
case 1:
part += "Pika";
break;
case 2:
part += "Krest";
break;
case 3:
part += "Rube";
break;
}
switch (j)
{
case 1:
{
part += "Ace";
score += 1;
isAce = true;
}
break;
case 10:
part += "10";
break;
case 11:
part += "Jack";
break;
case 12:
part += "Queen";
break;
case 13:
part += "King";
break;
default:
{
char digit = j + '0';
part += digit;
score = j;
}
break;
}
card = std::make_shared<Card>(part + ".png",score, sin(SDL_GetTicks())*5.0 + xpos, cos(SDL_GetTicks())*5.0 + ypos, isAce);
cards.push_back(card);
}
std::random_shuffle(cards.begin(),cards.end());
}
}
Deck::~Deck()
{
cards.clear();
std::cout << "Deck Cleaned" << std::endl;
}
void Deck::update()
{
}
bool Deck::animationFinish()
{
bool animYet = false;
for (int i = 0; i < cards.size(); i++) {
if (cards[i]->getIsAnimation())animYet = true;
}
return !animYet;
}
void Deck::render()
{
for (int i = 0; i < cards.size(); i++) {
cards[i]->render();
}
}
std::shared_ptr<Card> Deck::moveTopCard()
{
if (isEmpty()) {
std::cout << "Empty Deck cant delete object" << std::endl;
}
std::shared_ptr<Card> temp;
//cards.back()->update();
temp = cards.back();
cards.pop_back();
return temp;
}
void Deck::openCard()
{
for (int i = 0; i < cards.size(); i++) {
cards[i]->isFace = true;
}
}
Vector2D Deck::getPos()
{
Vector2D vec;
vec.x = xpos;
vec.y = ypos;
return vec;
}
void Deck::swapTextureCard(std::string namePath)
{
for (auto c : cards)
{
c->swapTextureCard(namePath);
}
}
void Deck::swapTextureBack(std::string namePath)
{
for (auto c : cards)
{
c->swapTextureBack(namePath);
}
} | true |
380a8828cd82b2737fb3946f2143939569df165a | C++ | ReiMatsuzaki/cbasis2 | /src_cpp/time_check/timer.hpp | UTF-8 | 822 | 3.09375 | 3 | [] | no_license | #ifndef TIMER_HPP
#define TIMER_HPP
#include <map>
#include <string>
namespace
{
using std::map;
using std::string;
using std::cout;
using std::endl;
}
class Timer {
enum Status {
kNone,
kStart,
kEnd,
};
struct TimeData {
int id;
clock_t t0;
clock_t t1;
Status status;
};
private:
/* ====== Member Field ====== */
int current_id;
map<string, TimeData> label_data_list;
public:
/* ====== Constructor ======= */
Timer() : current_id(0) {}
public:
/* ===== Pure Functional ======= */
Status GetStatus(const string& label);
double GetTime(const string& label);
/* ====== Side Effect ========== */
void Reset();
void Start(const string& label) ;
void End(const string& label);
/* ====== Input / Output ======= */
void Display();
};
#endif
| true |
d55a95fe0d825dd04743c76c6449a6abdd39d5ad | C++ | metaphysis/Code | /UVa Online Judge/volume123/12300 Smallest Regular Polygon/program.cpp | UTF-8 | 788 | 2.765625 | 3 | [] | no_license | // Smallest Regular Polygon
// UVa ID: 12300
// Verdict: Accepted
// Submission Date: 2018-05-08
// UVa Run Time: 0.000s
//
// 版权所有(C)2018,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
const double PI = 2 * acos(0);
int main(int argc, char *argv[])
{
cin.tie(0), cout.tie(0), ios::sync_with_stdio(false);
int xa, ya, xb, yb, n;
while (cin >> xa >> ya >> xb >> yb >> n, n > 0)
{
double r = 1.0;
if (n % 2 == 1)
{
r /= sin((n - 1) * PI / n / 2) * sin((n - 1) * PI / n / 2);
}
r *= (pow(xa - xb, 2) + pow(ya - yb, 2)) / 4.0;
r *= sin(PI / n) * cos(PI / n);
r *= n;
cout << fixed << setprecision(6) << r << '\n';
}
return 0;
}
| true |
bae805b9d7e4af3de6497bc69f14280271008581 | C++ | pinam45/MagicPlayer | /src/utils/path_utils.cpp | UTF-8 | 6,730 | 2.796875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //
// Copyright (c) 2018 Maxime Pinard
//
// Distributed under the MIT license
// See accompanying file LICENSE or copy at
// https://opensource.org/licenses/MIT
//
#include "utils/path_utils.hpp"
#include <utf8.h>
utf8_path::utf8_path() noexcept: m_valid_encoding(true), m_utf8_str(), m_path()
{
}
utf8_path::utf8_path(const utf8_path& other) noexcept
: m_valid_encoding(other.m_valid_encoding), m_utf8_str(other.m_utf8_str), m_path(other.m_path)
{
}
utf8_path::utf8_path(utf8_path&& other) noexcept
: m_valid_encoding(other.m_valid_encoding)
, m_utf8_str(std::move(other.m_utf8_str))
, m_path(std::move(other.m_path))
{
}
utf8_path::utf8_path(const char* str) noexcept: m_valid_encoding(true), m_utf8_str(str), m_path()
{
set_path();
}
utf8_path::utf8_path(std::string_view str) noexcept
: m_valid_encoding(true), m_utf8_str(str), m_path()
{
set_path();
}
utf8_path::utf8_path(std::string&& str) noexcept
: m_valid_encoding(true), m_utf8_str(std::move(str)), m_path()
{
set_path();
}
utf8_path::utf8_path(const std::filesystem::path& path) noexcept
: m_valid_encoding(true), m_utf8_str(), m_path(path)
{
set_str();
}
utf8_path::utf8_path(std::filesystem::path&& path) noexcept
: m_valid_encoding(true), m_utf8_str(), m_path(std::move(path))
{
set_str();
}
utf8_path& utf8_path::operator=(const utf8_path& other) noexcept
{
if(this != &other)
{
m_valid_encoding = other.m_valid_encoding;
m_utf8_str = other.m_utf8_str;
m_path = other.m_path;
}
return *this;
}
utf8_path& utf8_path::operator=(utf8_path&& other) noexcept
{
if(this != &other)
{
m_valid_encoding = other.m_valid_encoding;
m_utf8_str = std::move(other.m_utf8_str);
m_path = std::move(other.m_path);
}
return *this;
}
utf8_path& utf8_path::operator=(const char* str) noexcept
{
m_utf8_str = str;
set_path();
return *this;
}
utf8_path& utf8_path::operator=(std::string_view str) noexcept
{
m_utf8_str = str;
set_path();
return *this;
}
utf8_path& utf8_path::operator=(std::string&& str) noexcept
{
m_utf8_str = std::move(str);
set_path();
return *this;
}
utf8_path& utf8_path::operator=(const std::filesystem::path& path) noexcept
{
m_path = path;
set_str();
return *this;
}
utf8_path& utf8_path::operator=(std::filesystem::path&& path) noexcept
{
m_path = std::move(path);
set_str();
return *this;
}
std::string_view utf8_path::str() const noexcept
{
return m_utf8_str;
}
const std::string& utf8_path::str_cref() const noexcept
{
return m_utf8_str;
}
const std::filesystem::path& utf8_path::path() const noexcept
{
return m_path;
}
void utf8_path::set_str() noexcept
{
m_valid_encoding = path_to_generic_utf8_string(m_path, m_utf8_str);
if(!m_valid_encoding)
{
m_utf8_str = path_to_generic_utf8_string(m_path);
}
}
void utf8_path::set_path() noexcept
{
m_valid_encoding = utf8_string_to_path(m_utf8_str, m_path);
if(!m_valid_encoding)
{
m_path = utf8_string_to_path(m_utf8_str);
}
}
bool utf8_path::valid_encoding() const noexcept
{
return m_valid_encoding;
}
std::ostream& operator<<(std::ostream& os, const utf8_path& utf8_path)
{
return os << '\"' << utf8_path.str() << '\"';
}
bool utf8_string_to_path(const std::string_view str, std::filesystem::path& path) noexcept
{
static_assert(std::is_same<std::filesystem::path::value_type, wchar_t>::value
|| std::is_same<std::filesystem::path::value_type, char>::value,
"std::filesystem::path::value_type has an unsupported type");
if constexpr(std::is_same<std::filesystem::path::value_type, wchar_t>::value)
{
try
{
std::wstring wstr;
utf8::utf8to16(str.cbegin(), str.cend(), std::back_inserter(wstr));
path = wstr;
}
catch(...)
{
return false;
}
return true;
}
if constexpr(std::is_same<std::filesystem::path::value_type, char>::value)
{
path.clear();
if(!utf8::is_valid(str.cbegin(), str.cend()))
{
return false;
}
path = str;
return true;
}
}
bool path_to_generic_utf8_string(const std::filesystem::path& path, std::string& str) noexcept
{
static_assert(std::is_same<std::filesystem::path::value_type, wchar_t>::value
|| std::is_same<std::filesystem::path::value_type, char>::value,
"std::filesystem::path::value_type has an unsupported type");
if constexpr(std::is_same<std::filesystem::path::value_type, wchar_t>::value)
{
str.clear();
std::wstring wstr = path.generic_wstring();
try
{
utf8::utf16to8(wstr.begin(), wstr.end(), std::back_inserter(str));
}
catch(...)
{
return false;
}
}
if constexpr(std::is_same<std::filesystem::path::value_type, char>::value)
{
str = path.generic_string();
if(!utf8::is_valid(str.cbegin(), str.cend()))
{
str.clear();
return false;
}
}
return true;
}
std::string invalid_utf8_path_representation(const std::filesystem::path& path) noexcept
{
static_assert(std::is_same<std::filesystem::path::value_type, wchar_t>::value
|| std::is_same<std::filesystem::path::value_type, char>::value,
"std::filesystem::path::value_type has an unsupported type");
std::string str = path_to_generic_utf8_string(path);
str += "(?) [invalid utf8]";
return str;
}
std::filesystem::path utf8_string_to_path(const std::string_view str) noexcept
{
static_assert(std::is_same<std::filesystem::path::value_type, wchar_t>::value
|| std::is_same<std::filesystem::path::value_type, char>::value,
"std::filesystem::path::value_type has an unsupported type");
if constexpr(std::is_same<std::filesystem::path::value_type, wchar_t>::value)
{
std::wstring wstr;
try
{
utf8::utf8to16(str.cbegin(), str.cend(), std::back_inserter(wstr));
}
catch(...)
{
}
return std::filesystem::path(wstr);
}
if constexpr(std::is_same<std::filesystem::path::value_type, char>::value)
{
return std::filesystem::path(str.cbegin(), utf8::find_invalid(str.cbegin(), str.cend()));
}
}
std::string path_to_generic_utf8_string(std::filesystem::path path) noexcept
{
static_assert(std::is_same<std::filesystem::path::value_type, wchar_t>::value
|| std::is_same<std::filesystem::path::value_type, char>::value,
"std::filesystem::path::value_type has an unsupported type");
if constexpr(std::is_same<std::filesystem::path::value_type, wchar_t>::value)
{
std::wstring wstr = path.generic_wstring();
std::string str;
try
{
utf8::utf16to8(wstr.begin(), wstr.end(), std::back_inserter(str));
}
catch(...)
{
}
return str;
}
if constexpr(std::is_same<std::filesystem::path::value_type, char>::value)
{
std::string str = path.generic_string();
return std::string(str.cbegin(), utf8::find_invalid(str.cbegin(), str.cend()));
}
}
| true |
8edc2b764cb6f34629bc70b2aa616726f86caae7 | C++ | plescaevelyn/oop-simple-program | /oop-simple-program/oop-simple-program/Motherboard.h | UTF-8 | 660 | 2.671875 | 3 | [] | no_license | #pragma once
#include "pcUnit.h"
#include <iostream>
#include <string>
class Motherboard :
public PcUnit
{
public:
void setChipsetModel(std::string chipsetModel);
std::string getChipsetModel();
void setFormat(std::string format);
std::string getFormat();
void setGamingRecommended(bool gamingRecommended);
bool getGamingRecommended();
void setPrice(float price);
float getPrice();
void displayPrice(float price);
Motherboard() : chipsetModel("Unspecified"), format{ "Unspecified" }, gamingRecommended{ false } {}
~Motherboard();
private:
std::string chipsetModel;
std::string format;
bool gamingRecommended;
};
| true |
fa224bdbdfc7127dd87b5792703873e5b1a1ca35 | C++ | egorodet/CML | /tests/mathlib/quaternion_rotation1.cpp | UTF-8 | 6,819 | 2.671875 | 3 | [
"BSL-1.0"
] | permissive | /* -*- C++ -*- ------------------------------------------------------------
@@COPYRIGHT@@
*-----------------------------------------------------------------------*/
/** @file
*/
// Make sure the main header compiles cleanly:
#include <cml/mathlib/quaternion/rotation.h>
#include <cml/vector.h>
#include <cml/matrix.h>
#include <cml/quaternion.h>
#include <cml/mathlib/matrix/rotation.h>
/* Testing headers: */
#include "catch_runner.h"
CATCH_TEST_CASE("world_axis1")
{
cml::quaterniond qx; cml::quaternion_rotation_world_x(qx, M_PI/3.);
CATCH_CHECK(qx.real() == Approx(0.86602540378443871).epsilon(1e-12));
CATCH_CHECK(qx.imaginary()[0] == Approx(0.49999999999999994).epsilon(1e-12));
CATCH_CHECK(qx.imaginary()[1] == 0.);
CATCH_CHECK(qx.imaginary()[2] == 0.);
cml::quaterniond qy; cml::quaternion_rotation_world_y(qy, M_PI/2.);
CATCH_CHECK(qy.real() == Approx(0.70710678118654757).epsilon(1e-12));
CATCH_CHECK(qy.imaginary()[0] == 0.);
CATCH_CHECK(qy.imaginary()[1] == Approx(0.70710678118654757).epsilon(1e-12));
CATCH_CHECK(qy.imaginary()[2] == 0.);
cml::quaterniond qz; cml::quaternion_rotation_world_z(qz, M_PI);
CATCH_CHECK(0 == Approx(qz.real()).epsilon(0).margin(2e-16));
CATCH_CHECK(qz.imaginary()[0] == 0.);
CATCH_CHECK(qz.imaginary()[1] == 0.);
CATCH_CHECK(qz.imaginary()[2] == Approx(1.).epsilon(1e-12));
}
CATCH_TEST_CASE("axis_angle1")
{
cml::quaterniond q; cml::quaternion_rotation_axis_angle(
q, cml::vector3d(1.,1.,1.).normalize(), M_PI/3.);
CATCH_CHECK(q.real() == Approx(0.86602540378443871).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[0] == Approx(0.28867513459481287).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[1] == Approx(0.28867513459481287).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[2] == Approx(0.28867513459481287).epsilon(1e-12));
}
CATCH_TEST_CASE("matrix1")
{
cml::matrix33d M; cml::matrix_rotation_axis_angle(
M, cml::vector3d(1.,1.,1.).normalize(), M_PI/3.);
cml::quaterniond q; cml::quaternion_rotation_matrix(q, M);
CATCH_CHECK(q.real() == Approx(0.86602540378443871).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[0] == Approx(0.28867513459481287).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[1] == Approx(0.28867513459481287).epsilon(1e-12));
CATCH_CHECK(q.imaginary()[2] == Approx(0.28867513459481287).epsilon(1e-12));
}
CATCH_TEST_CASE("align_ref1")
{
cml::quaterniond q; cml::quaternion_rotation_align(
q, cml::vector3d(0., 0., 1.), cml::vector3d(1., 0., 0.));
cml::matrix33d M; cml::matrix_rotation_quaternion(M, q);
auto v = M*cml::vector3d(0., 1., 0.); // 0,0,1
CATCH_CHECK(v[0] == Approx(1.).epsilon(1e-12));
CATCH_CHECK(0 == Approx(v[1]).epsilon(0).margin(1e-7));
CATCH_CHECK(0 == Approx(v[2]).epsilon(0).margin(1e-7));
}
CATCH_TEST_CASE("aim_at_ref1")
{
cml::quaterniond q; cml::quaternion_rotation_aim_at(
q, cml::vector3d(0.,0.,0.), cml::vector3d(0., 0., 1.),
cml::vector3d(1., 0., 0.));
cml::matrix33d M; cml::matrix_rotation_quaternion(M, q);
auto v = M*cml::vector3d(0., 1., 0.); // 0,0,1
CATCH_CHECK(v[0] == Approx(1.).epsilon(1e-12));
CATCH_CHECK(0 == Approx(v[1]).epsilon(0).margin(1e-7));
CATCH_CHECK(0 == Approx(v[2]).epsilon(0).margin(1e-7));
}
CATCH_TEST_CASE("euler1")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::rad(90.), 0., 0., cml::euler_order_xyz);
cml::matrix33d M; cml::matrix_rotation_quaternion(M, q);
auto v = M*cml::vector3d(0., 1., 0.); // 0,0,1
CATCH_CHECK(0 == Approx(v[0]).epsilon(0).margin(1e-7));
CATCH_CHECK(0 == Approx(v[1]).epsilon(0).margin(1e-7));
CATCH_CHECK(v[2] == Approx(1.).epsilon(1e-12));
}
CATCH_TEST_CASE("euler2")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::vector3d(cml::rad(90.), 0., 0.), cml::euler_order_xyz);
cml::matrix33d M; cml::matrix_rotation_quaternion(M, q);
auto v = M*cml::vector3d(0., 1., 0.); // 0,0,1
CATCH_CHECK(0 == Approx(v[0]).epsilon(0).margin(1e-7));
CATCH_CHECK(0 == Approx(v[1]).epsilon(0).margin(1e-7));
CATCH_CHECK(v[2] == Approx(1.).epsilon(1e-12));
}
CATCH_TEST_CASE("to_axis_angle1")
{
cml::quaterniond q;
cml::quaternion_rotation_axis_angle(
q, cml::vector3d(1., 2., 3.).normalize(), cml::rad(23.));
cml::vector3d axis;
double angle;
cml::quaternion_to_axis_angle(q, axis, angle);
CATCH_CHECK(axis[0] == Approx(0.2672612419124244).epsilon(1e-12));
CATCH_CHECK(axis[1] == Approx(0.53452248382484879).epsilon(1e-12));
CATCH_CHECK(axis[2] == Approx(0.80178372573727308).epsilon(1e-12));
}
CATCH_TEST_CASE("to_axis_angle_tuple1")
{
cml::quaterniond q;
cml::quaternion_rotation_axis_angle(
q, cml::vector3d(1., 2., 3.).normalize(), cml::rad(23.));
cml::vector3d axis;
double angle;
std::tie(axis,angle) = cml::quaternion_to_axis_angle(q);
CATCH_CHECK(axis[0] == Approx(0.2672612419124244).epsilon(1e-12));
CATCH_CHECK(axis[1] == Approx(0.53452248382484879).epsilon(1e-12));
CATCH_CHECK(axis[2] == Approx(0.80178372573727308).epsilon(1e-12));
}
CATCH_TEST_CASE("to_euler1")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::rad(22.), cml::rad(10.), cml::rad(89.9), cml::euler_order_xyz);
cml::vector3d v;
cml::quaternion_to_euler(q, v[0], v[1], v[2], cml::euler_order_xyz);
CATCH_CHECK(v[0] == Approx(cml::rad(22.)).epsilon(1e-12));
CATCH_CHECK(v[1] == Approx(cml::rad(10.)).epsilon(1e-12));
CATCH_CHECK(v[2] == Approx(cml::rad(89.9)).epsilon(1e-12));
}
CATCH_TEST_CASE("to_euler2")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::rad(22.), cml::rad(10.), cml::rad(89.9), cml::euler_order_xyx);
cml::vector3d v;
cml::quaternion_to_euler(q, v[0], v[1], v[2], cml::euler_order_xyx);
CATCH_CHECK(v[0] == Approx(cml::rad(22.)).epsilon(1e-12));
CATCH_CHECK(v[1] == Approx(cml::rad(10.)).epsilon(1e-12));
CATCH_CHECK(v[2] == Approx(cml::rad(89.9)).epsilon(1e-12));
}
CATCH_TEST_CASE("to_euler_vector1")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::rad(22.), cml::rad(10.), cml::rad(89.9), cml::euler_order_xyz);
auto v = cml::quaternion_to_euler(q, cml::euler_order_xyz);
CATCH_CHECK(v[0] == Approx(cml::rad(22.)).epsilon(1e-12));
CATCH_CHECK(v[1] == Approx(cml::rad(10.)).epsilon(1e-12));
CATCH_CHECK(v[2] == Approx(cml::rad(89.9)).epsilon(1e-12));
}
CATCH_TEST_CASE("to_euler_vector2")
{
cml::quaterniond q;
cml::quaternion_rotation_euler(
q, cml::rad(22.), cml::rad(10.), cml::rad(89.9), cml::euler_order_xyz);
auto v = cml::quaternion_to_euler<cml::vectord>(q, cml::euler_order_xyz);
CATCH_CHECK(v[0] == Approx(cml::rad(22.)).epsilon(1e-12));
CATCH_CHECK(v[1] == Approx(cml::rad(10.)).epsilon(1e-12));
CATCH_CHECK(v[2] == Approx(cml::rad(89.9)).epsilon(1e-12));
}
// -------------------------------------------------------------------------
// vim:ft=cpp:sw=2
| true |
64c7ea7c821b29938d0dc928a0a5800a989cdcb8 | C++ | awarirahul365/CSE-2003-Data-Structures-and-Algorithms | /Leetcode 30 Days Solution/Convert BST to Greater Tree.cpp | UTF-8 | 1,752 | 3.40625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int checksum(int num,vector<int>& vect)
{
int sum=0;
for(int j=0;j<vect.size();j++)
{
if(vect[j]>=num)
{
sum=sum+vect[j];
}
}
return sum;
}
void inorder(TreeNode *root,vector<int>& vect)
{
if(root!=NULL)
{
inorder(root->left,vect);
vect.push_back(root->val);
inorder(root->right,vect);
}
}
TreeNode* convertBST(TreeNode* root) {
if(root==NULL)
{
return NULL;
}
else
{
vector<int>vect;
inorder(root,vect);
queue<TreeNode*>q;
q.push(root);
int outp;
while(!q.empty())
{
int sz=q.size();
for(int i=0;i<sz;i++)
{
TreeNode *cp=q.front();
q.pop();
outp=checksum(cp->val,vect);
cp->val=outp;
if(cp->left!=NULL)
{
q.push(cp->left);
}
if(cp->right!=NULL)
{
q.push(cp->right);
}
}
}
return root;
}
}
};
| true |
23dfd879ea058f0f73818e7b64bcb7a2fe4fcb73 | C++ | SebastianMestre/Competitive-Programming | /Codeforces/GlobalRound7/b.cpp | UTF-8 | 535 | 2.625 | 3 | [] | no_license | #include <iostream>
#include <cstdint>
#include <vector>
#define forn(i,n) for(int i = 0; i < int(n); ++i)
#define forsn(i,s,n) for(int i = s; i < int(n); ++i)
using namespace std;
constexpr int INF = 1<<25; // 33e6
constexpr int MOD = 1000000007; // 1e9+7
int main () {
int n ;
cin >> n;
vector<int> b(n);
forn(i, n){
cin >> b[i];
}
vector<int> a(n);
vector<int> x(n);
a[0] = b[0];
forsn(i, 1, n){
x[i] = max(x[i-1], a[i-1]);
a[i] = x[i] + b[i];
}
forn(i, n){
cout << a[i] << ' ';
}
cout << '\n';
}
| true |
ca9eb9f6a835b58edd5d950e49cf528b6195f2be | C++ | slacker247/3dGameEngine | /Source/Engine/PlayState.cpp | UTF-8 | 449 | 2.6875 | 3 | [] | no_license | #include "PlayState.h"
namespace States
{
PlayState::PlayState(void)
{
}
PlayState::PlayState(const PlayState &inPlayState)
: BaseState(inPlayState)
{
copy(inPlayState);
}
PlayState& PlayState::operator=( const PlayState& rhs )
{
copy(rhs);
return *this;
}
PlayState* PlayState::clone() const
{
return new PlayState(*this);
}
void PlayState::copy(const PlayState &inPlayState)
{
}
PlayState::~PlayState(void)
{
}
} | true |
249e1a18148fbabf6f37de97b99ff06c8180d596 | C++ | Gianluhub/Learning-Arduino | /Arduinonano/Arduinonano.ino | UTF-8 | 3,374 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <Nextion.h>
#include "Leds.h"
char buffer[20] = {0};
char trama[18] = {0};
int temperatura[2] = {0};
const unsigned long intervalo = 1000;
unsigned long tiempoprevio = 0;
NexButton b0=NexButton(2,10,"b0");
NexButton bNext=NexButton(2,7,"bNext");
NexButton bOn= NexButton(0,5,"bOn");
NexButton bOff= NexButton(0,6,"bOff");
NexText tState= NexText(0,4,"tState");
NexTouch *nex_listen_list[] = {
&bOn,
&bOff,
&b0,
&bNext,
NULL
};
void bOnCallback(void *ptr){
tState.setText ("Led on");
digitalWrite(LED1,HIGH);
Serial.print("Led on");
}
void bOffCallback(void *ptr){
tState.setText ("Led off");
digitalWrite(LED1,LOW);
Serial.print("Led off");
}
void bnextCallback(void *ptr){
//String data;
memset(buffer, 0, sizeof(buffer)); // Clear the buffer, so we can start using it
bNext.getText(buffer, sizeof(buffer));
Serial.println(buffer);
desentramado(trama,temperatura);
Serial.println(trama);
Serial.println(temperatura[0]);
Serial.println(temperatura[1]);
}
void b0Callback(void *ptr){
//String data;
memset(buffer, 0, sizeof(buffer)); // Clear the buffer, so we can start using it
b0.getText(buffer, sizeof(buffer));
Serial.println(buffer);
desentramado(trama,temperatura);
Serial.println(trama);
Serial.println(temperatura[0]);
Serial.println(temperatura[1]);
}
void desentramado(char trama[],int temperatura[]){
int i = 0;
int j = 0;
int k = 0;
//char trama[18] = {0};
char aux[4] = {0};
//int temperatura[2] = {0};
// Extrae los datos hasta que se lea el caracter de fin 'X'
do
{
// Revisa si hay un dato nuevo que tomar
if(buffer[i] == '+')
{
trama[j] = buffer[i+1]; // Toma el dato siguiente
i+=2; // Incrementa en dos para saltar al siguiente dato a extraer
// Verifica si es necesario extraer un valor de temperatura
if (buffer[i] == '-')
{
i++; // Incrementa al siguiente dato a extraer
// Guarda los valores hasta que se lea el caracter de fin '-'
do
{
aux[k] = buffer[i];
k++;
i++;
}while(buffer[i]!='-');
// Si la temperatura pertenece a la del poliester guarda ese valor en la posicion 0 del array
if(trama[j] == 'D') temperatura[0] = String(aux).toInt(); // Convierte los caracteres a un entero y se guarda
// Si la temperatura pertenece a la del algodon guarda ese valor en la posicion 1 del array
if(trama[j] == 'E') temperatura[1] = String(aux).toInt(); // Convierte los caracteres a un entero y se guarda
memset(aux, 0, sizeof(aux)); // Limpia el auxiliar para la siguiente interacion
k = 0; // Reinicia el indice del auxiliar
i++; // Incrementa la trama al siguiente dato a leer
}
j++; // Incrementa la posicion del array trama
}
}while(buffer[i]!='X');
}
void loop() {
// unsigned long currentTime = millis();
//
// //PrenderLed();
// //delay(1000);
// if (currentTime - tiempoprevio >= intervalo)
// {
// led(1);
// tiempoprevio = currentTime;
//
// }
//
// if (timer(1000))
// {
// //Serial.println("True\n");
// led(2);
// }
nexLoop(nex_listen_list);
}
| true |
bee652f3eca419c24b380861ba2fcb66b1fa6b89 | C++ | SubhamPanigrahi/MyCodechefCodes | /dec1.cpp | UTF-8 | 700 | 2.640625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int m,n;
cin>>m>>n;
int a[m][n];
int i,j;
int ca = 0,cb = 0,b[m][n],c[m][n];
char d[n];
for(i =0 ;i<m;i++){
scanf("\n%s",&d);
for(j =0 ;j<n;j++){
a[i][j] = 0;
if(d[j] == 'R'){
a[i][j] = 1;
}
b[i][j] = (i%2) ^ (j % 2);
c[i][j] = (b[i][j]+1)%2 ;
if(a[i][j] < b[i][j] ){
ca += 3;
}
else if (a[i][j] > b[i][j]){
ca += 5;
}
if(a[i][j] < c[i][j] ){
cb += 3;
}
else if (a[i][j] > c[i][j]){
cb += 5;
}
}
}
cout<<ca<<endl<<cb<<endl;
cout<<((ca < cb) ? ca : cb )<<endl ;
}
}
| true |
5956b669bfaa06441557e76066727cd2b897ee53 | C++ | ubiratansoares/bira-bachelor-files | /courses/POO/Curso Mello (2009)/Archives/COMP07 Files/exemplos/ex02/ex02.cc | UTF-8 | 209 | 3.046875 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
using namespace std;
void funcao(int x, int y = 5) {
cout << "x = " << x << " y = " << y << endl;
return;
}
int main(int argc, char *argv[]) {
funcao(3);
funcao(5,7);
return 0;
}
| true |
4aed4c8d571fa8562bc4d21876a6568a1252ec6a | C++ | annsshadow/fakepractice | /c-cpp/sort/select.cpp | GB18030 | 520 | 3.4375 | 3 | [] | no_license | void Selectsort(int a[], int n)
{
int i, j, nMinIndex;
for(i = 0; i < n; i++)
{
nMinIndex = i; //СԪصλ
for(j = i + 1; j < n; j++)
if(a[j] < a[nMinIndex])
nMinIndex = j;
Swap(a[i], a[nMinIndex]); //ԪطŵĿͷ
}
}
inline void Swap(int &a, int &b)
{
int c = a;
a = b;
b = c;
}
inline void Swap1(int &a, int &b)
{
if(a != b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
| true |
de3dd9aa1835fb93c268c9e1783b3d8d1990bba5 | C++ | alicchm892/programowanie | /funkcje.cpp | UTF-8 | 9,512 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>
#include <random>
#include "deklaracje.h"
using namespace std;
void wypelnij_1(Pole plansza[9][9]) //wypelnienie pustej planszy liczba -1 (by pozniej moc sprawdzic czy wszystkie komorki zostaly uzupelnione przy przepisywaniu)
{
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
plansza[i][j].liczba = -1;
plansza[i][j].czy_do_zmiany = 0;
}
}
}
string wylosuj_plansze() //losowanie planszy z osmiu dostepnych plikow
{
random_device device;
mt19937 generator(device());
uniform_int_distribution<int> ktora_plansza(1, 8);
int nr_planszy = ktora_plansza(generator);
switch (nr_planszy)
{
case 1:
return "1.txt";
break;
case 2:
return "2.txt";
break;
case 3:
return "3.txt";
break;
case 4:
return "4.txt";
break;
case 5:
return "5.txt";
break;
case 6:
return "6.txt";
break;
case 7:
return "7.txt";
break;
case 8:
return "8.txt";
break;
}
}
bool przepisz_z_pliku(string nazwa_pliku, Pole plansza[9][9])
{
ifstream plik(nazwa_pliku);
char pobierany_znak;
Pole *wskaznik_na_plansze = &plansza[0][0];
int i{};
if (plik.is_open())
{
while (!plik.eof() && i < 81) //przepisywnie cyfr z pliku do planszy - dopoki nie skonczy sie tekst w pliku lub nie zapelni sie cala tablica
{
plik.get(pobierany_znak);
if (pobierany_znak >= '0' && pobierany_znak <= '9') //zalozenie ze przepisywane beda jedynie cyfry od 0 do 9
{
if (pobierany_znak != '0') //jesli cyfra jest rozna od 0 to uzytkownik nie moze jej zmienic podczas gry
(wskaznik_na_plansze + i)->czy_do_zmiany = 0;
else //jesli cyfra jest rowna 0 to uzytkownik moze ja podczas gry zmienic
(wskaznik_na_plansze + i)->czy_do_zmiany = 1;
(wskaznik_na_plansze + i)->liczba = pobierany_znak - 48; //wpisanie cyfry do planszy z uwzglednieniem zamiany char -> int
i++;
}
}
for (int i = 0; i < 9; i++) //sprawdzenie czy cala plansza jest wypelniona liczbami od 0 do 9
{
for (int j = 0; j < 9; j++)
{
if (plansza[i][j].liczba == -1) //jesli ktoras z komorek jest wypelniona liczba -1, to plansza nie zostala poprawnie przepisana
{
plik.close();
return 0;
}
}
}
}
else
cout << "nie mozna otworzyc pliku" << endl;
plik.close();
return 1;
}
void wypisz_plansze(Pole plansza[9][9])
{
HANDLE kolor_znakow;
kolor_znakow = GetStdHandle(STD_OUTPUT_HANDLE);
int nr_wiersza = 0;
for (int i = 1; i < 21; i++)
{
if (i == 20)
{
cout << " 1 2 3 4 5 6 7 8 9 " << endl;
}
else if (i % 2 == 0) //wypisanie rzedu cyfr
{
for (int j = 0; j < 9; j++)
{
if (j == 0)
cout << (char)0xBA; // ║
if (plansza[nr_wiersza][j].liczba != 0) //jesli cyfra jest rozna od zera to ja wypisz
{
if (plansza[nr_wiersza][j].czy_do_zmiany == 0) //zmiana kolorow cyfr ktorych uzytkownik nie moze zmienic
{
SetConsoleTextAttribute(kolor_znakow, 9);
cout.width(3);
cout << plansza[nr_wiersza][j].liczba;
SetConsoleTextAttribute(kolor_znakow, 15);
}
else //wypisanie cyfr ktore gracz moze zmieniac
{
cout.width(3);
cout << plansza[nr_wiersza][j].liczba;
}
}
else //jesli cyfra jest rowna 0 to jej nie wypisuj
{
cout.width(3);
cout << " ";
}
if (j == 2 || j == 5 || j == 8)
cout << " " << (char)0xBA;
}
cout << " [" << (nr_wiersza + 1) << "]";
nr_wiersza++;
}
else if (i == 1)
{
cout << (char)0xC9; // ╔
for (int k = 0; k < 35; k++)
{
if (k == 11 || k == 23)
cout << (char)0xCB; // ╦
else
cout << (char)0xCD; // ═
}
cout << (char)0xBB; // ╗
}
else if (i == 7 || i == 13)
{
cout << (char)0xCC; // ╠
for (int k = 0; k < 35; k++)
{
if (k == 11 || k == 23)
cout << (char)0xCE; // ╬
else
cout << (char)0xCD; // ═
}
cout << (char)0xB9; // ╣
}
else if (i == 19)
{
cout << (char)0xC8; // ╚
for (int k = 0; k < 35; k++)
{
if (k == 11 || k == 23)
cout << (char)0xCA; // ╩
else
cout << (char)0xCD; // ═
}
cout << (char)0xBC; // ╝
}
else
{
cout << (char)0xBA << " " << (char)0xBA << " " << (char)0xBA << " " << (char)0xBA;
}
cout << endl;
}
}
void wpisz_nowa_liczbe(Pole plansza[9][9])
{
int wiersz, kolumna;
bool czy_poprawna_komorka = 0;
cout << "podaj komorke do ktorej chcesz wpisac liczbe: " << endl;
while (czy_poprawna_komorka == 0)
{
cout << "kolumna: "; //pobranie od gracza wspolrzednych komorki
cin >> kolumna;
cout << "wiersz: ";
cin >> wiersz;
if (kolumna > 0 && kolumna < 10 && wiersz > 0 && wiersz < 10) //sprawdzenie czy wspolrzedne sa prawidlowe
{
if (plansza[wiersz-1][kolumna-1].czy_do_zmiany == 0) //jesli gracz nie moze zmienic zawartosci komorki
{
cout << "tej liczby zmienic nie mozesz" << endl;
cout << "wybierz inna komorke" << endl;
}
else //jesli gracz moze zmienic zawartosc komorki
{
int wpisywana_liczba;
cout << "podaj liczbe ktora chcesz wpisac do tej komorki: ";
cin >> wpisywana_liczba;
plansza[wiersz-1][kolumna-1].liczba = wpisywana_liczba;
czy_poprawna_komorka = 1;
}
}
}
}
int sprawdz(Pole plansza[9][9]) //0 jesli blad, 1 jesli poprawnie, 2 jesli nie jest w pelni wypelniona
{
for (int i = 0; i < 9; i++) //sprawdzanie czy jest w pelni wypelniona
{
for (int j = 0; j < 9; j++)
{
if (plansza[i][j].liczba == 0)
return 2;
}
}
for (int i = 0; i < 9; i++) //sprawdzanie rzedami
{
for (int j = 0; j < 9; j++)
{
int sprawdzana_liczba = plansza[i][j].liczba;
for (int k = j + 1; k < 9; k++)
{
if (plansza[i][j].liczba == plansza[i][k].liczba) //jesli liczba sie powtarza
return 0;
}
}
}
for (int i = 0; i < 9; i++) //sprazwdzanie kolumnami
{
for (int j = 0; j < 9; j++)
{
int sprawdzana_liczba = plansza[i][j].liczba;
for (int k = j + 1; k < 9; k++)
{
if (plansza[j][i].liczba == plansza[k][i].liczba) //jesli liczba sie powtarza
return 0;
}
}
}
for (int i = 1; i <= 9; i++) //sprawdzanie kwadratami 3x3
{
if (i % 3 == 1)
{
for (int j = 1; j <= 9; j++)
{
if (j % 3 == 1)
{
//sprawdzanie komorek 3x3
for (int k = 1; k <= 9; k++)
{
int sprawdzana_liczba = k;
int ile_powtorzen = 0;
for (int m = 0; m < 3; m++)
{
for (int n = 0; n < 3; n++)
{
if (plansza[m + i - 1][n + j - 1].liczba == sprawdzana_liczba)
ile_powtorzen++;
}
}
if (ile_powtorzen > 1)
return 0; //jesli liczba sie powtarza
}
}
}
}
}
return 1; //jesli liczby sie nie powtarzaja
}
bool glowne_menu()
{
while (true)
{
cout << " _____ _ _ ____ _____ _ __ _ _ " << endl;
cout << "| __| | | | | | \\ | _ | | | / / | | | |" << endl;
cout << "| |__ | | | | | |\\ | | | | | | |/ / | | | |" << endl;
cout << "|__ | | | | | | | | | | | | | | < | | | |" << endl;
cout << " __| | | |_| | | |/ | | |_| | | |\\ \\ | |_| |" << endl;
cout << "|____| |_____| |____/ |_____| |_| \\_\\ |_____|" << endl;
cout << endl;
char wybor_menu;
cout.width(34);
cout << "1. jak grac zeby wygrac?" << endl;
cout.width(27);
cout << "2. nowa gra" << endl;
cout.width(28);
cout << "3. zakoncz gre" << endl;
cout << endl;
cout << "co wybierasz? wpisz cyfre: ";
cin >> wybor_menu;
if (wybor_menu == '1') //wypisanie instrukcji
{
system("cls");
cout << "INSTRUKCJA GRY: " << endl;
cout << endl;
cout << "Musisz wypelnic wszystkie komorki cyframi od 0 do 9, tak by:" << endl;
cout << "1. W kazdym wierszu kazda cyfra wystepowala tylko raz" << endl;
cout << "2. W kazdej kolumnie kazda cyfra wystepowala tylko raz" << endl;
cout << "3. W kazdym kwadracie 3x3 kazda cyfra wystepowala tylko raz" << endl;
cout << endl;
cout << "Nie musisz zgadywac, wystarczy logiczne myslenie!" << endl;
cout << endl;
cout << "WSKAZOWKA: \nJesli po wybraniu numeru komorki i numeru wiersza stwierdzisz, \nze jednak nie chcesz do tej komorki wpisywac zadnej cyfry, wpisz cyfre 0" << endl;
cout << endl;
system("pause");
}
else if (wybor_menu == '2') //nowa gra (czy_koniec_gry = 0)
return 0;
else if (wybor_menu == '3') //koniec gry (czy_koniec_gry = 1)
return 1;
else
{
cout << "nie ma takiej opcji" << endl;
Sleep(550);
}
system("cls");
}
return 0;
}
void gratulacje()
{
cout << " _____ _____ ____ ________ ____ _____ ______ ______ " << endl;
cout << " / | \\ / \\ | | | | / \\ / | | " << endl;
cout << "| ___ | ___| |______| | | | | |______| | | |____ " << endl;
cout << "| | | \\ | | | | | | | | | | | " << endl;
cout << " \\____| | \\ | | | \\____/ |_____ | | \\_____ |____/ |______ " << endl;
}
| true |
a642372d3a40def55425d4a00fbe0fb607342c07 | C++ | mihailitu/bookexercise | /interviews/intervalmap/main.cpp | UTF-8 | 9,884 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <cstdio>
#include <map>
#include <limits>
template<typename K, typename V>
class interval_map {
std::map<K,V> m_map;
public:
// constructor associates whole range of K with val by inserting (K_min, val)
// into the map
interval_map( V const& val) {
m_map.insert(m_map.end(),std::make_pair(std::numeric_limits<K>::lowest(),val));
}
auto size() const {
return m_map.size();
}
void print() const {
for(auto const &elem : m_map)
std::cout << "(" << elem.first << ", " << elem.second << ")" << '\n';
std::cout << "\n\n";
}
bool is_equal(K const &key1, K const &key2) {
return !((key1 < key2) || (key2 < key1));
}
void assign2( K const& keyBegin, K const& keyEnd, V const& val ) {
printf("assign2: %d %d %c\n", keyBegin, keyEnd, val);
if (!(keyBegin < keyEnd))
return;
if (std::next(m_map.begin()) == m_map.end()) { // if no more elements, just slice the map
if ((*m_map.begin()).second == val) // keep the map canonical
return;
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, (*m_map.begin()).second));
return;
}
auto endInterval = m_map.lower_bound(keyEnd);
auto beginInterval = m_map.upper_bound(keyBegin);
if (beginInterval == m_map.end()) {
V slice_value = (*(--beginInterval)).second;
if (slice_value == val)
return;
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, slice_value));
return;
}
printf("Interval: (%d, %c), (%d, %c)\n", (*beginInterval).first, (*beginInterval).second, (*endInterval).first, (*endInterval).second);
if(val == (*(--beginInterval)).second)
return;
if (endInterval == m_map.end()) {
if ((*m_map.begin()).second == val) // keep the map canonical
return;
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, (*m_map.begin()).second));
m_map.erase(++m_map.find(keyBegin), m_map.find(keyEnd)); // remove any key in between
return;
}
if((*endInterval).second == val)// another early exit. map must be canonical
return;
V slice_value = (*(--endInterval)).second;
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, slice_value));
m_map.erase(++m_map.find(keyBegin), m_map.find(keyEnd)); // remove any key in between
}
// Assign value val to interval [keyBegin, keyEnd).
// Overwrite previous values in this interval.
// Conforming to the C++ Standard Library conventions, the interval
// includes keyBegin, but excludes keyEnd.
// If !( keyBegin < keyEnd ), this designates an empty interval,
// and assign must do nothing.
void assign1( K const& keyBegin, K const& keyEnd, V const& val ) {
printf("assign1: %d %d %c\n", keyBegin, keyEnd, val);
if (!(keyBegin < keyEnd))
return;
// auto map_iter = m_map.begin();
if (std::next(m_map.begin()) == m_map.end()) { // if no more elements, just slice the map
if ((*m_map.begin()).second == val)
return; // keep the map canonical
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, (*m_map.begin()).second));
return;
}
auto endInterval = m_map.lower_bound(keyEnd);
auto beginInterval = m_map.upper_bound(keyBegin);
printf("Interval: (%d, %c), (%d, %c)\n", (*beginInterval).first, (*beginInterval).second, (*endInterval).first, (*endInterval).second);
V slice_value = (*m_map.begin()).second;
for(auto elem = m_map.begin(); elem != m_map.end(); ++elem) {
if (keyBegin < (*elem).first) {
if(slice_value == val) // // early exit. map must be canonical
return;
if (std::next(elem) == m_map.end()) { // if no more elements, just slice the map
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, slice_value));
return;
}
auto endInterval = elem;
for(; endInterval != m_map.end(); ++endInterval) { // now, find the end of the interval
if ((keyEnd < (*endInterval).first) || is_equal(keyEnd, (*endInterval).first)) {
if((*endInterval).second == val)// another early exit. map must be canonical
return;
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, slice_value));
// remove any key in between
auto bbegin = ++m_map.find(keyBegin);
auto bend = m_map.find(keyEnd);
std::cout << "Erase: " << (*bbegin).first << " " << (*bend).first << std::endl;
m_map.erase(++m_map.find(keyBegin), m_map.find(keyEnd));
return;
}
slice_value = (*endInterval).second;
}
if (endInterval == m_map.end()) { // if no more elements, just slice the map
m_map.insert(std::make_pair(keyBegin, val));
m_map.insert(std::make_pair(keyEnd, slice_value));
m_map.erase(++m_map.find(keyBegin), m_map.find(keyEnd));
return;
}
}
slice_value = (*elem).second;
}
}
void assign( K const& keyBegin, K const& keyEnd, V const& val ) {
assign2(keyBegin, keyEnd, val);
}
// look-up of the value associated with key
V const& operator[]( K const& key ) const {
return ( --m_map.upper_bound(key) )->second;
}
};
#include "imap.h"
// Many solutions we receive are incorrect. Consider using a randomized test
// to discover the cases that your implementation does not handle correctly.
// We recommend to implement a test function that tests the functionality of
// the interval_map, for example using a map of unsigned int intervals to char.
int main()
{
test_interval_map();
{
interval_map<unsigned, char> im('A');
im.assign(10, 20, 'B');
im.print();
im.assign(3, 7, 'C');
im.print();
im.assign(9, 20, 'D');
im.print();
im.assign(5, 15, 'E');
im.print();
im.assign(17, 30, 'X');
im.print();
im.assign(20, 50, 'A');
im.print();
im.assign(100, 200, 'W');
im.print();
}
{
interval_map<unsigned, char> im('A');
im.assign(0, 20, 'B');
}
std::cout << std::endl << std::endl;
return 0;
}
/**
Task Description
interval_map<K,V> is a data structure that efficiently associates intervals of keys of type K with values of type V. Your task is to implement the assign member function of this data structure, which is outlined below.
interval_map<K, V> is implemented on top of std::map. In case you are not entirely sure which functions std::map provides, what they do and which guarantees they provide, we provide an excerpt of the C++ standard here:
Each key-value-pair (k,v) in the std::map means that the value v is associated with the interval from k (including) to the next key (excluding) in the std::map.
Example: the std::map (0,'A'), (3,'B'), (5,'A') represents the mapping
0 -> 'A'
1 -> 'A'
2 -> 'A'
3 -> 'B'
4 -> 'B'
5 -> 'A'
6 -> 'A'
7 -> 'A'
... all the way to numeric_limits<int>::max()
The representation in the std::map must be canonical, that is, consecutive map entries must not have the same value: ..., (0,'A'), (3,'A'), ... is not allowed. Initially, the whole range of K is associated with a given initial value, passed to the constructor of the interval_map<K,V> data structure.
Key type K
* besides being copyable and assignable, is less-than comparable via operator<
* is bounded below, with the lowest value being std::numeric_limits<K>::lowest()
* does not implement any other operations, in particular no equality comparison or arithmetic operators
Value type V
* besides being copyable and assignable, is equality-comparable via operator==
* does not implement any other operations
Pass Criteria
Type requirements are met: You must adhere to the specification of the key and value type given above.
Correctness: Your program should produce a working interval_map with the behavior described above. In particular, pay attention to the validity of iterators. It is illegal to dereference end iterators. Consider using a checking STL implementation such as the one shipped with Visual C++ or GCC.
Canonicity: The representation in m_map must be canonical.
Running time: Imagine your implementation is part of a library, so it should be big-O optimal. In addition:
Do not make big-O more operations on K and V than necessary, because you do not know how fast operations on K/V are; remember that constructions, destructions and assignments are operations as well.
Do not make more than two operations of amortized O(log N), in contrast to O(1), running time, where N is the number of elements in m_map. Any operation that needs to find a position in the map "from scratch", without being given a nearby position, is such an operation.
Otherwise favor simplicity over minor speed improvements.
You should not take longer than 9 hours, but you may of course be faster. Do not rush, we would not give you this assignment if it were trivial.
*/
| true |
3a9d101f3e804a60366612dd40cdc148d4bad175 | C++ | Treekay/Learn-CG | /final/Final-CG-Project/object/Object.cpp | GB18030 | 3,918 | 2.921875 | 3 | [] | no_license | #include "Object.h"
//Object::Object(vector<float> _vertices, vector<unsigned int> _textures): textures(_textures) {
// vertices_num = _vertices.size();
//
// //
// glGenVertexArrays(1, &VAO);
// glGenBuffers(1, &VBO);
// // VAO, VBO
// glBindVertexArray(VAO);
// glBindBuffer(GL_ARRAY_BUFFER, VBO);
// glBufferData(GL_ARRAY_BUFFER, vertices_num * sizeof(float), _vertices.data(), GL_STREAM_DRAW);
// // λ
// glEnableVertexAttribArray(0);
// glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
// //
// glEnableVertexAttribArray(1);
// glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
// //
// glEnableVertexAttribArray(2);
// glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
// glBindBuffer(GL_ARRAY_BUFFER, 0);
// glBindVertexArray(0);
//}
//Object::~Object() {
// //
// glDeleteVertexArrays(1, &VAO);
// glDeleteBuffers(1, &VBO);
//}
//// Ⱦ
//void Object::Render(vector<glm::vec3> positions, Shader *shader, bool renderShadow) {
// glActiveTexture(GL_TEXTURE0);
// glBindTexture(GL_TEXTURE_2D, textures[0]); //
//
// if (renderShadow) {
// glActiveTexture(GL_TEXTURE1);
// glBindTexture(GL_TEXTURE_2D, textures[1]); // Ӱ
// }
//
// // Ⱦ
// glBindVertexArray(VAO);
//
// for (int i = 0; i < positions.size(); i++) {
// glm::mat4 model = glm::mat4(1.0f);
// model = glm::translate(model, positions[i]);
// shader->setMat4("model", model);
//
// glDrawArrays(GL_TRIANGLES, 0, vertices_num);
// }
// glBindVertexArray(0);
//}
Object::Object(vector<float> _vertices, vector<unsigned int> _textures, glm::vec3 _position, unsigned int _VAO, unsigned int _VBO): position(_position), textures(_textures){
vertices_num = _vertices.size();
if (_VAO == 0 && _VBO == 0) {
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
setBuffer(_vertices, VAO, VBO);
}
else {
VAO = _VAO;
VBO = _VBO;
}
}
void Object::Render(Shader *_shader, bool renderShadow) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textures[0]); //
if (renderShadow) {
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textures[1]); // Ӱ
}
glm::mat4 model = glm::mat4(1.0f);
model = glm::translate(model, position);
_shader->setMat4("model", model);
// Ⱦ
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, vertices_num);
glBindVertexArray(0);
}
vector<Object> createObjects(vector<float> _vertices, vector<unsigned int> _textures, vector<glm::vec3> positions) {
vector<Object> objects;
// generate VAO, VBO
unsigned int VAO, VBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
setBuffer(_vertices, VAO, VBO);
cout << VAO << endl;
for (int i = 0; i < positions.size(); i++) {
objects.push_back(Object(_vertices, _textures, positions[i], VAO, VBO));
}
return objects;
}
void renderObjects(vector<Object> _objects, Shader *_shader, bool renderShadow) {
for (int i = 0; i < _objects.size(); i++) {
_objects[i].Render(_shader, renderShadow);
}
}
void setBuffer(vector<float> _vertices, unsigned int _VAO, unsigned int _VBO) {
// VAO, VBO
glBindVertexArray(_VAO);
glBindBuffer(GL_ARRAY_BUFFER, _VBO);
glBufferData(GL_ARRAY_BUFFER, _vertices.size() * sizeof(float), _vertices.data(), GL_STREAM_DRAW);
// λ
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
//
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
//
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
} | true |
d9f440c55d2530417abe524218416f96fdc6951d | C++ | narubond007/datastructure | /c-concept/types_of_casting_in_cplusplus.cc | UTF-8 | 186 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
int main(){
const int c=3;
// c is a const and you want to remove the constness
int &i = const_cast<int &>(c);
//int &i = c;
i = 5;
printf("%d \n",i);
return 0;
}
| true |
3fa6562eec7c8bcb80ab5d5549257027512a2c34 | C++ | MarvinS26/MiyukiRenderer | /src/cameras/camera.h | UTF-8 | 3,401 | 2.609375 | 3 | [
"MIT"
] | permissive | //
// Created by Shiina Miyuki on 2019/3/3.
//
#ifndef MIYUKI_CAMERA_H
#define MIYUKI_CAMERA_H
#include "miyuki.h"
#include "core/geometry.h"
#include "core/ray.h"
#include "math/transform.h"
#include "core/parameter.h"
namespace Miyuki {
class Scene;
class Sampler;
struct ScatteringEvent;
struct VisibilityTester;
struct CameraSample {
Point2f pFilm, pLens;
Float weight;
};
class Camera {
friend class Scene;
protected:
Vec3f viewpot;
// euler angle;
Vec3f direction;
Matrix4x4 rotationMatrix, invMatrix;
Point2i dimension;
public:
Camera(const Point2i &dim) : dimension(dim) {}
const Vec3f &translation() const {
return viewpot;
}
const Vec3f &rotation() const {
return direction;
}
void moveTo(const Vec3f &v);
void move(const Vec3f &v);
void moveLocal(const Vec3f &v) {
move(cameraToWorld(v));
}
void rotate(const Vec3f &v);
void rotateTo(const Vec3f &v);
void computeTransformMatrix();
virtual Float generateRay(Sampler &sampler,
const Point2i &raster,
Ray *ray, CameraSample*) = 0;
virtual Float
generateRayDifferential(Sampler &sampler, const Point2i &raster, RayDifferential *ray, Float *weight) = 0;
virtual void preprocess() { computeTransformMatrix(); }
virtual Spectrum We(const Ray &ray, Point2f *raster) const = 0;
virtual Spectrum
sampleWi(const ScatteringEvent &event, const Point2f &u, Vec3f *wi, Float *pdf, Point2f *pRaster,
VisibilityTester *) = 0;
virtual void pdfWe(const Ray &ray, Float *pdfPos, Float *pdfDir) const = 0;
Vec3f cameraToWorld(Vec3f w) const {
w.w() = 1;
w = rotationMatrix.mult(w);
return w;
}
Vec3f worldToCamera(Vec3f w) const {
w.w() = 1;
w = invMatrix.mult(w);
return w;
}
virtual bool rasterize(const Vec3f &p, Point2i *rasterPos) const = 0;
};
class PerspectiveCamera : public Camera {
friend class Scene;
Float fov;
Float lensRadius;
Float focalDistance;
Float A;
public:
PerspectiveCamera(const Point2i &dim, Float fov, Float lensRadius = 0, Float focalDistance = 0)
: Camera(dim),
fov(fov), lensRadius(lensRadius), focalDistance(focalDistance) {}
Float generateRay(Sampler &sampler, const Point2i &raster, Ray *ray, CameraSample*) override;
Float generateRayDifferential(Sampler &sampler, const Point2i &raster,
RayDifferential *ray, Float *weight) override;
Spectrum We(const Ray &ray, Point2f *raster) const override;
void preprocess() override;
Spectrum
sampleWi(const ScatteringEvent &event, const Point2f &u, Vec3f *wi, Float *pdf, Point2f *pRaster,
VisibilityTester *tester) override;
void pdfWe(const Ray &ray, Float *pdfPos, Float *pdfDir) const override;
bool rasterize(const Vec3f &p, Point2i *rasterPos) const override;
};
std::unique_ptr<PerspectiveCamera> CreatePerspectiveCamera(const ParameterSet &);
}
#endif //MIYUKI_CAMERA_H
| true |
9de40d75c7c3c1aad78fd2e810a2a0d8c94b680b | C++ | karolinaWu/leetcode-lintcode | /leetcode/Cpp/859.BuddyStrings.cpp | UTF-8 | 592 | 2.96875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #include"AllInclude.h"
//https://leetcode.com/problems/buddy-strings/
class Solution {
public:
bool buddyStrings(string A, string B) {
string tmpa = "", tmpb = "";
if (A.length() != B.length()) return false;
if (A == B && set<char>(A.begin(), A.end()).size() < A.size()) return true;
vector<int> diff;
for (int i = 0; i < A.length(); ++i)
if (A[i] != B[i]) diff.push_back(i);
return diff.size() == 2 && A[diff[0]] == B[diff[1]] && A[diff[1]] == B[diff[0]];
}
};
int main()
{
string A = "abcd" , B="badc";
cout << Solution().buddyStrings(A, B);
getchar();
return 0;
} | true |
3c5879fb3f7a558a9cd29229e84a0d9792d4c5ec | C++ | jazz4rabbit/problem-solving | /OnlineJudges/BOJ/15059/main.cc | UTF-8 | 288 | 2.609375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
ios::sync_with_stdio(false), cin.tie(NULL);
int ca, ba, pa, cr, br, pr;
cin >> ca >> ba >> pa >> cr >> br >> pr;
cout << max(cr-ca,0) + max(br-ba,0) + max(pr-pa,0) << endl;
return 0;
}
| true |
48ed5ccda79fad62e54807ce16c8159859cd6fc3 | C++ | nattee/data2020 | /07/custom-1.cpp | UTF-8 | 1,295 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <queue>
using namespace std;
class Student {
public:
Student(float score, string a, string b) {
name = a;
surname = b;
gpax = score;
}
bool is1stHornor() { return gpax >= 3.6; }
//not good, now our data is public
string name,surname;
float gpax;
//overloading <
bool operator<(const Student& other) const {
return gpax < other.gpax;
}
};
class StudentByNameComparator {
public:
bool operator()(const Student& lhs, const Student& rhs) {
return lhs.name < rhs.name;
}
};
class GpaxThenName {
public:
bool operator()(const Student& lhs, const Student& rhs) {
if (lhs.gpax == rhs.gpax) return lhs.name < rhs.name;
return lhs.gpax < rhs.gpax;
}
};
int main() {
Student a(2.95,"nattee","niparnan");
Student b(4.00,"attawith","sudsang");
Student c(4.00,"vishnu","kotrajaras");
cout << (a < b) << endl;
StudentByNameComparator comp1;
GpaxThenName comp2;
cout << comp1(a,b) << endl;
priority_queue<Student,vector<Student>,StudentByNameComparator> pq(comp1);
pq.push(a);
pq.push(b);
cout << pq.top().name << endl;
priority_queue<Student,vector<Student>,GpaxThenName> pq2(comp2);
pq2.push(a);
pq2.push(b);
pq2.push(c);
cout << pq2.top().name << endl;
} | true |
d929bbc420186913fc827e969c8d2ed95bfe3998 | C++ | chermaine/CPP-Projects | /Final Project/Lobby.cpp | UTF-8 | 4,903 | 2.9375 | 3 | [] | no_license | /*******************************************************************************
* Name: Chermaine Cheang
* Date: Jun 1, 2016
* Description: Lobby class implementation file
* ****************************************************************************/
#include "Lobby.hpp"
/*******************************************************************************
* Function: setDoorToBasement()
* Description: set pointer to basement
* Parameter: Space*
* Pre-condition: lobby exists
* Post-condition: the pointer to basement is set
* ****************************************************************************/
void Lobby::setDoorToBasement(Space* doorToBasement)
{
this->doorToBasement = doorToBasement;
}
/*******************************************************************************
* Function: getDoorToBasement()
* Description: return pointer to basement
* Pre-condition: lobby exists
* ****************************************************************************/
Space* Lobby::getDoorToBasement() const
{
return this->doorToBasement;
}
/*******************************************************************************
* Function: setDoorToRooftop()
* Description: set pointer to rooftop
* Parameter: Space*
* Pre-condition: lobby exists
* Post-condition: the pointer to rooftop is set
* ****************************************************************************/
void Lobby::setDoorToRooftop(Space* doorToRoof)
{
this->doorToRooftop = doorToRoof;
}
/*******************************************************************************
* Function: getDoorToRooftop()
* Description: return pointer to rooftop
* Pre-condition: lobby exists
* ****************************************************************************/
Space* Lobby::getDoorToRooftop() const
{
return this->doorToRooftop;
}
/*******************************************************************************
* Function: Lobby()
* Description: default constructor
* ****************************************************************************/
Lobby::Lobby():Space()
{
this->nameOfSpace = "Lobby";
this->doorToBasement = NULL;
this->doorToRooftop = NULL;
this->builtBasement = false;
this->builtRooftop = false;
createObject();
}
/*******************************************************************************
* Function: ~Lobby()
* Description: default destructor
* ****************************************************************************/
Lobby::~Lobby()
{
}
/*******************************************************************************
* Function: createObject()
* Description: create objects needed in Lobby and add to queue
* Pre-condition: Lobby exists
* Post-condition: objects are created and added to queue
* ****************************************************************************/
void Lobby::createObject()
{
Object* receptionistDesk = new Object("Receptionist Desk",
"There's a computer on the left, a phone right next to it,\ntwo drawers underneath and a log book for checking in visitors", false, "");
Object* drawer1 = new Object("First Drawer", "There's a lot of stationary in the drawer.",
false, "");
Object* drawer2 = new Object("Second Drawer", "A pile of papers is in this drawer.",
true, "It's a name tag!!!");
setObjectInSpace(receptionistDesk);
setObjectInSpace(drawer1);
setObjectInSpace(drawer2);
}
/*******************************************************************************
* Function: setBuiltBasement()
* Description: set variable builtBasement
* Parameter: bool
* Pre-condition: Lobby exists
* Post-condition: variable is set
* ****************************************************************************/
void Lobby::setBuiltBasement(bool val)
{
this->builtBasement = val;
}
/*******************************************************************************
* Function: setBuiltRooftop()
* Description: set variable builtRooftop
* Parameter: bool
* Pre-condition: Lobby exists
* Post-condition: variable is set
* ****************************************************************************/
void Lobby::setBuiltRooftop(bool val)
{
this->builtRooftop = val;
}
/*******************************************************************************
* Function: getBuiltBasement()
* Description: return variable builtBasement
* Pre-condition: Lobby exists
* ****************************************************************************/
bool Lobby::getBuiltBasement() const
{
return this->builtBasement;
}
/*******************************************************************************
* Function: getBuiltBasement()
* Description: return variable builtBasement
* Pre-condition: Lobby exists
* ****************************************************************************/
bool Lobby::getBuiltRooftop() const
{
return this->builtRooftop;
}
| true |
e7c37ab6b640c270e7f5e048b1437e6a563b1144 | C++ | Mengbabity/Longest-Substring-Without-Repeating-Characters | /my.cpp | UTF-8 | 751 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int n = s.size();
if (n == 0)
return 0;
int res = 1;
int mid = 0;
int vn = 0;
map<char, int> m;
map<char, vector<int>> mtmp;
int i = 0;
while (i<n)
{
m[s[i]]++;
mtmp[s[i]].push_back(i);
if (m[s[i]]>1)
{
int tmp = 0;
for (auto e : m)
tmp += e.second;
res = max(tmp - 1, res);
m.clear();
vn = mtmp[s[i]].size();
i = mtmp[s[i]][vn-2] + 1;
m[s[i]]++;
}
i++;
}
for (auto e : m)
mid += e.second;
res = max(mid, res);
return res;
}
};
void main()
{
Solution s;
s.lengthOfLongestSubstring("abcabcbb");
}
| true |
e6695610fb935f235094f9abbd7bc970e0899016 | C++ | zhouchuyi/WebServer | /Chat/ChatServer.cpp | UTF-8 | 3,677 | 2.921875 | 3 | [] | no_license | #include"codec.h"
#include"../TcpServer.h"
#include"../base/ThreadLocalSingleton.h"
#include"../EventLoop.h"
#include<set>
using namespace std::placeholders;
class ChatServer:noncopyable
{
public:
ChatServer(EventLoop* loop,const InetAddress& listenAddr)
: server_(loop,listenAddr,"ChatServer"),
codec_(std::bind(&ChatServer::onStringMessage,this,_1,_2)),
mutex_()
{
server_.setConnectionCallback(std::bind(&ChatServer::onConnection,this,_1));
server_.setMessageCallback(std::bind(&LengthHeaderCodec::onMessage,&codec_,_1,_2));
server_.setThreadInitCallback(std::bind(&ChatServer::ThreadInit,this,_1));
}
~ChatServer()=default;
void start()
{ server_.start(); }
void setThreadNum(int n)
{ server_.setThreadNum(n); }
private:
typedef std::set<TcpConnectionPtr> Connectionlist;
typedef ThreadLocalSingleton<Connectionlist> LocalConnectionList;
void onConnection(const TcpConnectionPtr&);
void onStringMessage(const TcpConnectionPtr&,const std::string&);
void distributeMessage(const std::string& message);
void ThreadInit(EventLoop* loop);
TcpServer server_;
LengthHeaderCodec codec_;
MutexLock mutex_;
std::set<EventLoop*> loops_;
};
void ChatServer::onConnection(const TcpConnectionPtr& conn)
{
Log<<conn->peerAddress().toIpPort()<<" -> "
<<conn->localAddress().toIpPort()
<<(conn->connected() ? " ON " : " OFF ");
if(conn->connected())
{
auto res=LocalConnectionList::instace().insert(conn);
assert(res.second==true);
char buf[64];
snprintf(buf,sizeof buf,"Welcome --%s--!!",conn->peerAddress().toIpPort().c_str());
std::string message(buf);
EventLoop::Functor f=std::bind(&ChatServer::distributeMessage,this,message);
std::set<EventLoop*> temp;
{
MutexLockGuard lcok(mutex_);
temp=loops_;
}
for (auto &ioloop : temp)
{
ioloop->queueInLoop(f);
}
}
else
{
auto res=LocalConnectionList::instace().erase(conn);
assert(res==true);
char buf[64];
snprintf(buf,sizeof buf,"GoodBye --%s--!!",conn->peerAddress().toIpPort().c_str());
std::string message(buf);
EventLoop::Functor f=std::bind(&ChatServer::distributeMessage,this,message);
std::set<EventLoop*> temp;
{
MutexLockGuard lcok(mutex_);
temp=loops_;
}
for (auto &ioloop : temp)
{
ioloop->queueInLoop(f);
}
}
}
void ChatServer::onStringMessage(const TcpConnectionPtr& conn,const std::string& message)
{
// printf("%s",message.c_str());
EventLoop::Functor f=std::bind(&ChatServer::distributeMessage,this,message);
std::set<EventLoop*> temp;
{
MutexLockGuard lcok(mutex_);
temp=loops_;
}
for (auto &ioloop : temp)
{
ioloop->queueInLoop(f);
}
}
void ChatServer::distributeMessage(const std::string& message)
{
for (auto &conn : LocalConnectionList::instace())
{
codec_.send(conn,message);
}
}
void ChatServer::ThreadInit(EventLoop* loop)
{
assert(LocalConnectionList::pointer()==NULL);
LocalConnectionList::instace();
assert(LocalConnectionList::pointer()!=NULL);
MutexLockGuard lock(mutex_);
auto res=loops_.insert(loop);
assert(res.second==true);
}
int main(int argc, char const *argv[])
{
EventLoop base;
InetAddress listenAddr(9985);
ChatServer server(&base,listenAddr);
server.setThreadNum(3);
server.start();
base.loop();
return 0;
}
| true |
8c8522c7726c62ffd28c307f224dc3dd189be029 | C++ | mohsinabbas14/CPlusPlus | /vector.cpp | UTF-8 | 482 | 2.671875 | 3 | [] | no_license | # include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
vector<string> shoppingList;
shoppingList.push_back("eggs") ;
shoppingList.push_back("milk");
shoppingList.push_back("sugar");
shoppingList.push_back("choclate");
shoppingList.push_back("flour");
shoppingList.pop_back();
shoppingList.push_back("coffee");
cout<<shoppingList.at(4)<<endl;
for (int i=0; i< shoppingList.size();i++)
cout <<shoppingList.at(i)<< endl;
}
| true |
fcfa542fc71a4a029ccc90d42097a34833e8570c | C++ | 3DHome/3DHome | /3DHomeEngine/src/main/jni/src/SE_Layer.h | UTF-8 | 810 | 2.71875 | 3 | [] | no_license | #ifndef SE_LAYER_H
#define SE_LAYER_H
#include "SE_Common.h"
class SE_ENTRY SE_Layer
{
public:
SE_Layer();
SE_Layer(int layer);
~SE_Layer();
SE_Layer(const SE_Layer& layer);
SE_Layer& operator=(const SE_Layer& layer);
friend bool operator==(const SE_Layer& left, const SE_Layer& right);
friend bool operator<(const SE_Layer& left, const SE_Layer& right);
friend bool operator>(const SE_Layer& left, const SE_Layer& right);
friend SE_Layer operator+(const SE_Layer& left, const SE_Layer& right);
friend SE_Layer operator-(const SE_Layer& left, const SE_Layer& right);
int getLayer() const
{
return mLayer;
}
void setLayer(int layer)
{
mLayer = layer;
}
private:
int mLayer;
};
#endif
| true |
5c0af7445a797acbe527106c02a5b7ff0ec6f4fd | C++ | juansala/6.08-Poker | /poker.cpp | UTF-8 | 12,355 | 2.65625 | 3 | [] | no_license | #include "Arduino.h"
#include "Poker.h"
Poker::Poker(char* user_id, TFT_eSPI tft){
sprintf(USER_ID,user_id);
sprintf(host, "608dev-2.net");
initialized = 0; //whether user's been initialized in game
sprintf(GAME_STATE, "DEAL"); //initialize to DEAL to generate
sprintf(PREV_STATE, "DEAL");
hand_index = 0;
bet_added = 0;
tft_g = tft;
result = 0;
timer = millis();
}
int Poker::update(int button1, int button2){
if (strcmp(GAME_STATE, "DEAL") == 0 && !initialized){
makeGame();
getGame(); //update GAME_STATE and other info
initialized = 1;
}
if (millis()-5000 > timer){ //Get game info every 5 sec
getGame();
timer = millis();
Serial.println("TEST");
if (strcmp(GAME_STATE, "DEAL") == 0){
tft_g.drawString("Waiting for other player...", 0, 0, 1);
}
}
if (button2 == 2){ //button2 long press -> fold detected
requestPOST("fold", "NULL", "NULL");
}
if (strcmp(GAME_STATE, PREV_STATE) != 0){
tft_g.fillScreen(TFT_BLACK);
sprintf(PREV_STATE, GAME_STATE);
}
if (strcmp(GAME_STATE, "BET_1") == 0){
displayCards(false);
if (strcmp(CURRENT_PLAYER, USER_ID) == 0){
tft_g.drawString("Add Bet: ", 0, 60, 1);
tft_g.drawString(" ", 0, 100, 1); //clear the "not your turn" message
if (button1 == 1){ //button1 short press -> add to bet only on screen
bet_added = bet_added + 1;
char tempStr[10];
sprintf(tempStr, "%d", bet_added);
tft_g.drawString(tempStr, 60, 60, 1);
}
if (button2 == 1){ //button2 short press -> finish turn, POST bet
char tempStr[10];
sprintf(tempStr, "%d", bet_added);
requestPOST("bet", tempStr, "NULL");
bet_added = 0;
}
}
else {
tft_g.drawString("Not your turn.", 0, 100, 1);
}
}
if (strcmp(GAME_STATE, "DISCARD") == 0){
//Serial.println("It's discarding time!");
displayCards(false);
if (strcmp(CURRENT_PLAYER, USER_ID) == 0){
tft_g.drawString("Discard: ", 0, 60, 1);
tft_g.drawString(" ", 0, 100, 1); //clear the "not your turn" message
if (button1 == 1){ //button1 short press -> browse through cards
hand_index++;
sprintf(chosen_card, "%s,", hand_array[((hand_index % 5) + 5) % 5]);
tft_g.drawString(chosen_card, 60, 60, 1);
}
if (button1 == 2){ //button1 long press -> select card to discard
strcat(discarded, chosen_card);
tft_g.drawString("Chosen: ", 0, 70, 1);
tft_g.drawString(chosen_card, 60, 70, 1);
}
if (button2 == 1 || strlen(discarded) == 15){ //button2 short press -> finish turn, POST discarded cards, fix to limit number of cards discarded to 5
discarded[strlen(discarded) - 1] = '\0';
tft_g.drawString("Discarded!: ", 0, 80, 1);
tft_g.drawString(discarded, 70, 80, 1);
requestPOST("discard", "NULL", discarded);
sprintf(discarded, ""); //reset discarded string
hand_index = 0;
}
}
else {
tft_g.drawString("Not your turn.", 0, 100, 1);
}
}
if (strcmp(GAME_STATE, "BET_2") == 0){
//Serial.println("It's betting time (again)!");
displayCards(false);
if (strcmp(CURRENT_PLAYER, USER_ID) == 0){
tft_g.drawString("Add Bet: ", 0, 60, 1);
tft_g.drawString(" ", 0, 100, 1); //clear the "not your turn" message
if (button1 == 1){ //button1 short press -> add to bet only on screen
bet_added = bet_added + 1;
char tempStr[10];
sprintf(tempStr, "%d", bet_added);
tft_g.drawString(tempStr, 60, 60, 1);
}
if (button2 == 1){ //button2 short press -> finish turn, POST bet
char tempStr[10];
sprintf(tempStr, "%d", bet_added);
requestPOST("bet", tempStr, "NULL");
bet_added = 0;
}
}
else {
tft_g.drawString("Not your turn.", 0, 100, 1);
}
}
if (strcmp(GAME_STATE, "REVEAL") == 0){
//Serial.println("It's revealing time!");
displayCards(true);
tft_g.drawString("Short press 1 = restart!.", 0, 100, 1);
if (button1 == 1){ //button1 short press -> restart
requestPOST("restart", "NULL", "NULL");
}
else if (button2 == 2){ //button1 long press -> quit
requestPOST("leave", "NULL", "NULL");
result = 1;
}
}
return result;
}
void Poker::makeGame() {
char action[] = "generate";
requestPOST(action,"NULL", "NULL"); // add yourself (user) to the game
}
void Poker::getGame(){
requestGET();
parser(response_buffer, "|");
}
void Poker::parser(char* data_array, char* delim){
// Returns first token
char *token = strtok(data_array, delim);
int i = 0;
while (token != NULL)
{
//printf("%s\n", token);
//Serial.println(i);
indexField(i, token);
token = strtok(NULL, delim);
i++;
}
int_extractor(BETS, bets, ',');
}
void Poker::indexField(int i, char* token){
switch(i){
case 0:
sprintf(CURRENT_PLAYER, token);
//Serial.println(CURRENT_PLAYER);
break;
case 1:
{
sprintf(CURRENT_HAND, token);
sprintf(card_1, "%c%c", CURRENT_HAND[0], CURRENT_HAND[1]);
sprintf(card_2, "%c%c", CURRENT_HAND[3], CURRENT_HAND[4]);
sprintf(card_3, "%c%c", CURRENT_HAND[6], CURRENT_HAND[7]);
sprintf(card_4, "%c%c", CURRENT_HAND[9], CURRENT_HAND[10]);
sprintf(card_5, "%c%c", CURRENT_HAND[12], CURRENT_HAND[13]);
hand_array[0]= card_1;
hand_array[1] = card_2;
hand_array[2]= card_3;
hand_array[3] = card_4;
hand_array[4] = card_5;
// for (int j = 0; j <= 4; j++){
// Serial.println(hand_array[j]);
// }
//Serial.println(CURRENT_HAND);
break;
}
case 2:
sprintf(OTHER_HAND, token);
sprintf(other_card_1, "%c%c", OTHER_HAND[0], OTHER_HAND[1]);
sprintf(other_card_2, "%c%c", OTHER_HAND[3], OTHER_HAND[4]);
sprintf(other_card_3, "%c%c", OTHER_HAND[6], OTHER_HAND[7]);
sprintf(other_card_4, "%c%c", OTHER_HAND[9], OTHER_HAND[10]);
sprintf(other_card_5, "%c%c", OTHER_HAND[12], OTHER_HAND[13]);
other_hand_array[0]= other_card_1;
other_hand_array[1] = other_card_2;
other_hand_array[2]= other_card_3;
other_hand_array[3] = other_card_4;
other_hand_array[4] = other_card_5;
//Serial.println(OTHER_HAND);
break;
case 3:
sprintf(GAME_STATE, token);
//Serial.println(GAME_STATE);
break;
case 4: {
sprintf(BETS, token);
// char temp[50];
// strcpy(temp, BETS);
// int_extractor(temp, bets, ',');
// for (int j = 0; j <= 1; j++){
// Serial.println(bets[j]);
// }
//Serial.println(BETS);
break;
}
case 5:
sprintf(WINNER, "%s", token);
//Serial.println(WINNER);
break;
}
}
void Poker::int_extractor(char* data_array, int* output_values, char delimiter){
char* ptr;
char* delPointer = &delimiter;
ptr = strtok(data_array, delPointer);
int i = 0;
while (ptr != NULL)
{
output_values[i] = atoi(ptr);
ptr = strtok(NULL, delPointer);
i++;
}
}
void Poker::displayCards(uint8_t reveal) {
tft_g.drawLine(58, 0, 58, tft_g.height(), TFT_WHITE);
tft_g.drawString("You:", 0, 0, 1);
tft_g.drawString("Opponent:", 65, 0, 1);
for (int i = 0; i < 5; i++) {
char el[50];
tft_g.drawString(hand_array[i], 0, 10 + i * 10, 1);
}
tft_g.drawString("Bet:", 0, 140, 1);
tft_g.drawString("Bet:", 65, 140, 1);
char temp[4];
sprintf(temp, "%d", bets[0]);
tft_g.drawString(temp, 0, 150, 1);
if (reveal == false) { //not displaying opponent's cards
sprintf(temp, "%d", bets[1]);
tft_g.drawString(temp, 65, 150, 1);
} else { //show all of opponent's cards
for (int i = 0; i < 5; i++) {
tft_g.drawString(other_hand_array[i], 65, 10 + i * 10, 1);
sprintf(temp, "%d", bets[1]);
tft_g.drawString(temp, 65, 150, 1);
}
if (strcmp(WINNER, USER_ID) == 0){ // you are the winner!
displayWon();
}
else if (strcmp(WINNER, "None") == 0){
displayTie();
}
else {
displayLost();
}
}
}
void Poker::displayLost() {
tft_g.setTextColor(TFT_RED, TFT_BLACK);
tft_g.drawString("REVEAL!", 0, 110, 2);
char temp [50];
sprintf(temp, "YOU LOST %d!", bets[0]);
tft_g.drawString(temp, 0, 130, 1);
tft_g.setTextColor(TFT_GREEN, TFT_BLACK);
}
void Poker::displayWon() {
tft_g.setTextColor(TFT_RED, TFT_BLACK);
int win_amt = bets[0] + bets[1];
tft_g.drawString("REVEAL!", 0, 110, 2);
char temp [50];
sprintf(temp, "YOU WON %d! :)", win_amt);
tft_g.drawString(temp, 0, 130, 1);
tft_g.setTextColor(TFT_GREEN, TFT_BLACK);
}
void Poker::displayTie() {
tft_g.setTextColor(TFT_RED, TFT_BLACK);
tft_g.drawString("GAME OVER - TIE", 0, 110, 2);
tft_g.setTextColor(TFT_GREEN, TFT_BLACK);
}
void Poker::requestPOST(char* action, char* bet_value, char* discarded_cards) {
char body[200]; //for body;
if (strcmp(action, "generate") == 0 || strcmp(action, "restart") == 0 || strcmp(action, "fold") == 0 || strcmp(action, "leave") == 0){ // simple POST requests only requiring user ID -> generate, restart, fold, leave
sprintf(body, "action=%s&user=%s",action,USER_ID); //generate body, posting to User, 1 step
int body_len = strlen(body); //calculate body length (for header reporting)
sprintf(request_buffer, "POST http://608dev-2.net/sandbox/sc/salazarj/Poker/poker.py HTTP/1.1\r\n");
strcat(request_buffer, "Host: 608dev-2.net\r\n");
strcat(request_buffer, "Content-Type: application/x-www-form-urlencoded\r\n");
sprintf(request_buffer + strlen(request_buffer), "Content-Length: %d\r\n", body_len); //append string formatted to end of request buffer
strcat(request_buffer, "\r\n"); //new line from header to body
strcat(request_buffer, body); //body
strcat(request_buffer, "\r\n"); //header
do_http_request("608dev-2.net", request_buffer, response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT, true);
}
if (strcmp(action, "bet") == 0){ // POST request requiring more than user ID -> bet
sprintf(body, "action=%s&user=%s&value=%s",action,USER_ID,bet_value); //generate body, posting to User, 1 step
int body_len = strlen(body); //calculate body length (for header reporting)
sprintf(request_buffer, "POST http://608dev-2.net/sandbox/sc/salazarj/Poker/poker.py HTTP/1.1\r\n");
strcat(request_buffer, "Host: 608dev-2.net\r\n");
strcat(request_buffer, "Content-Type: application/x-www-form-urlencoded\r\n");
sprintf(request_buffer + strlen(request_buffer), "Content-Length: %d\r\n", body_len); //append string formatted to end of request buffer
strcat(request_buffer, "\r\n"); //new line from header to body
strcat(request_buffer, body); //body
strcat(request_buffer, "\r\n"); //header
do_http_request("608dev-2.net", request_buffer, response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT, true);
}
if (strcmp(action, "discard") == 0){ // POST request requiring more than user ID -> discard
sprintf(body, "action=%s&user=%s&cards=%s",action,USER_ID,discarded_cards); //generate body, posting to User, 1 step
int body_len = strlen(body); //calculate body length (for header reporting)
sprintf(request_buffer, "POST http://608dev-2.net/sandbox/sc/salazarj/Poker/poker.py HTTP/1.1\r\n");
strcat(request_buffer, "Host: 608dev-2.net\r\n");
strcat(request_buffer, "Content-Type: application/x-www-form-urlencoded\r\n");
sprintf(request_buffer + strlen(request_buffer), "Content-Length: %d\r\n", body_len); //append string formatted to end of request buffer
strcat(request_buffer, "\r\n"); //new line from header to body
strcat(request_buffer, body); //body
strcat(request_buffer, "\r\n"); //header
do_http_request("608dev-2.net", request_buffer, response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT, true);
}
}
void Poker::requestGET() { // response format: CURRENT_PLAYER|CURRENT_HAND|OTHER_HAND|STATE|BETS|WINNER|
sprintf(request_buffer, "GET /sandbox/sc/salazarj/Poker/poker.py?get=%s", USER_ID);
strcat(request_buffer, " HTTP/1.1\r\n");
strcat(request_buffer, "Host: iesc-s3.mit.edu\r\n");
strcat(request_buffer, "\r\n"); //add blank line!
do_http_request("608dev-2.net", request_buffer, response_buffer, OUT_BUFFER_SIZE, RESPONSE_TIMEOUT, true);
}
| true |
625615bf26537ca530debb181d3076e8bd9cdb4a | C++ | wenmingxing1/leetcode_for_github | /169_majorityElement.cpp | GB18030 | 1,641 | 3.671875 | 4 | [] | no_license | //ָoffer29
class Solution {
public:
/*
//ȫʽ
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
int middle = nums.size()/2;
return nums[middle];
}
*/
//partation
int majorityElement(vector<int>& nums) {
int length = nums.size();
int middle = length >> 1;
int start = 0;
int end = length - 1;
int index = Partation(nums, start, end);
//ֱҵmiddle
while (index != middle){
if (index > middle){
end = index - 1;
index = Partation(nums, start, end);
}
else if (index < middle){
start = index + 1;
index = Partation(nums, start, end);
}
}
return nums[middle];
}
private:
int Partation(vector<int>& nums, int start, int end){
int small = start - 1;
//int index = start;
int temp = Random(start, end);
//
Swap(&nums[temp], &nums[end]);
for (int i = start; i < end; ++i){
if (nums[i] < nums[end]){
++small;
if (small != i)
Swap(&nums[small], &nums[i]);
}
}
++small;
Swap(&nums[small], &nums[end]);
return small;
}
int Random(int start, int end){
if (end > start)
return start + rand() % (end - start);
else
return 0;
}
void Swap(int* i, int* j){
int temp = *i;
*i = *j;
*j = temp;
}
};
| true |
41fe933da313c658c247b0333247e06b345c93c8 | C++ | John-Fenge/Exercise | /EssentialC++/ch2/ch2.cpp | UTF-8 | 2,701 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include<vector>
#include <fstream>
using namespace std;
bool is_pos_ok(int pos){
if(pos<1||pos>1024){
cout<<"Illegel Position!"<<endl;
return false;
}
return true;
}
const vector<int>* fibon_seq(int pos){
static vector<int> elem;
if(!is_pos_ok(pos))
return 0;
for(int i=elem.size();i<pos;i++){
if(i==0||i==1)
elem.push_back(1);
else
elem.push_back(elem[i-1]+elem[i-2]);
}
return &elem;
}
const vector<int>* squ_seq(int pos){
static vector<int> elem;
if(!is_pos_ok(pos))
return 0;
for(int i=elem.size();i<pos;i++){
elem.push_back((i+1)*(i+1));
}
return &elem;
}
const int fun_num=2;
const vector<int>* (*fun_arry[fun_num])(int)={fibon_seq,squ_seq};
//void print_elem(const vector<int> *pseq, ofstream *os=0){//此处是ofstream,目的是利用指针选择是否输出信息
// (*os)<<"The sequec is: "<<endl;
// for(int i=0;i<(*pseq).size();i++){
// (*os)<<(*pseq)[i]<<" ";
// if((i+1)%10==0)
// (*os)<<endl;
// }
//}
void print_elem(const vector<int> *pseq, ostream &os=cout){//此处是ostream,目的是使cout成为ostream的默认参数
(os)<<"The sequec is: "<<endl;
for(int i=0;i<(*pseq).size();i++){
(os)<<(*pseq)[i]<<" ";
if((i+1)%10==0)
(os)<<endl;
}
}
bool seq_elem(int pos, int &elem, const vector<int>* (*seq_ptr)(int)){
const vector<int>* pseq = seq_ptr(pos);
if(!pseq){
cerr<<"Internal Error: seq_ptr is set to null!"<<endl;
return false;
}
else{
elem = (*pseq)[pos-1];
char user_output;
cout<<"Write into a file named \"text.txt\"(Y/N)? : ";
cin>>user_output;
if(user_output=='Y'||user_output=='y'){
ofstream outfile("data.txt");
if(!outfile){
cerr<<"No such file! Show on screen!"<<endl;
print_elem(pseq);
}
else
// print_elem(pseq,&outfile);
print_elem(pseq,outfile);
}
else
print_elem(pseq);
return true;
}
}
int main()
{
int pos;
int element;
bool user_try=true;
char user_choose;
while(user_try){
cout<<"Please enter a position(1~1024): ";
cin>>pos;
if(seq_elem(pos,element,fun_arry[1])){//fun_arry[0] 或者 fun_arry[1]
cout<<"element # "<<pos<<" is "<<element<<endl;;
}
cout<<"Do you want to try again? (Y/N)"<<endl;
cin>>user_choose;
if(user_choose!='Y'&& user_choose!='y')
user_try=false;
}
return 0;
}
| true |
9848756259a4fab52d8cb2030492640db2c8b518 | C++ | wallaceowen/VentDriver | /VentDriver.ino | UTF-8 | 929 | 2.734375 | 3 | [] | no_license | // VentDriver.ino
// -*- mode: C++ -*-
//
// Drive a stepper motor to move a piston/diaphragm/bellows
//
#include <Arduino.h>
#include "constants.h"
#include "ports.h"
#include "ventilator.h"
#include "commander.h"
// The ventilator
Ventilator *ventilator;
char v_buffer[sizeof(Ventilator)];
// Comms interface to the ventilator
Commander*commander;
char c_buffer[sizeof(Commander)];
// When home pin goes low inform the ventilator
void home_pin_changed()
{
ventilator->home_triggered();
}
void setup()
{
Serial.begin(115200);
while (!Serial)
;
pinMode(STEPPER_STEP, OUTPUT);
pinMode(STEPPER_DIR, OUTPUT);
pinMode(STEPPER_ENABLE, OUTPUT);
ventilator = new (v_buffer) Ventilator();
attachInterrupt(digitalPinToInterrupt(HOME_PIN), home_pin_changed, LOW);
commander = new (c_buffer) Commander(ventilator);
}
void loop()
{
commander->loop();
ventilator->loop();
}
| true |
c1d5e610f831fdd238ca4056daaa514284ef76e6 | C++ | mtgeoma/geomamt | /progsProcMT/mtlab/src/lib/udouble/measure.hpp | UTF-8 | 711 | 3.171875 | 3 | [] | no_license | #ifndef MEASURE_HPP
#define MEASURE_HPP
#include <cmath> // sqrt
//!
/*! \brief Representação de uma medida (valor +/- incerteza)
*/
struct measurement
{
long double value; /*!< valor da medida */
long double variance; /*!< variança da medida */
//! @name Construtor
/*@{*/
//!
/*! \brief Construtor default
\param val valor da medida
\param var variança da medida
\return um objeto do tipo \a measurement
*/
measurement ( long double val = 0.0, long double var = 0.0 )
: value(val), variance(var) {};
/*@}*/
//!
/*! \brief Calcula o valor da incereteza
\return O valor da Incerteza
*/
long double uncertainty() { return sqrt( variance ); }
};
#endif
| true |
25560157a56a4c5d71f0ecf0b0b197572258d703 | C++ | Du0ngkylan/C-Cpp | /TKDGTT/Tuan 6/BT6.Nhom2/Code/Bai 1/Daycondondieutang.cpp | UTF-8 | 1,596 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void input(int *a, int n)
{
int i;
printf("Nhap vao day so:\n");
for(i=1; i<=n; i++)
{
printf("a[%d] = ", i); scanf("%d", &a[i]);
}
}
void output(int *a, int n)
{
int i;
printf("\nIn ra day so vua nhap la\n");
for(i=1; i<=n; i++)
{
printf("%5d", a[i]);
}
}
int dayconlonnhat(int *a, int *L, int n)
{
int i, j;
//L=(int *)malloc((n+1)*sizeof(int));
for(i=0; i<=n; i++)
{
L[i]=0;
}
for(i=1; i<=n; i++)
{
L[i]=1;
if(i>1)
{
for(j=1; j<i; j++)
{
if(a[i]>a[j]&&L[i]<L[j]+1)
{
L[i]=L[j]+1;
}
}
}
}
j=L[1];
for(i=2; i<=n; i++)
{
if(L[i]>j)
{
j=L[i];
}
}
return j;
}
void Truyvet(int *a, int *L, int *dd, int n)
{
int i, k, j;
for(i=1; i<=n; i++)
{
dd[i]=0;
}
for(i=1; i<=n; i++)
{
if(L[i]==dayconlonnhat(a, L, n))
{
k=i;
break;
}
}
j=k;
dd[j]=1;
for(i=k-1; i>=1; i--)
{
if(a[i]<a[j]&&L[i]==L[j]-1)
{
dd[i]=1;
j=i;
printf("->%d", j);
}
}
printf("\nDay con do la:\n");
for(i=1; i<=n; i++)
{
if(dd[i]==1)
{
printf("%5d", a[i]);
}
}
}
int main()
{
int *a, *L, *dd, n;//mang a chua day so dau vao
//mang L chua chi so cua so a[i] thu tu nam trong day con
//mang dd danh dau cac so nam trong day con dai nhat
printf("\nNhap vao do dai ca day so n="); scanf("%d", &n);
a=(int *)malloc((n+1)*sizeof(int));
L=(int *)malloc((n+1)*sizeof(int));
dd=(int *)malloc((n+1)*sizeof(int));
input(a, n);
output(a, n);
printf("\nDo dai day con tang dai nhat la %d", dayconlonnhat(a, L, n));
Truyvet(a, L, dd, n);
getch();
}
| true |
dd1a4231732c8489c6e6e74a15a7185d23ff042b | C++ | ppnnh/OAP-1-sem | /лаба 9/доп9.1/доп9.1/доп9.1.cpp | UTF-8 | 2,882 | 2.625 | 3 | [] | no_license | // доп9.1.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <ctime>
int main()
{
using namespace std;
setlocale(LC_ALL, "rus");
const int N = 100;
int i, sz, A[N], k = 0, m1 = 0, m2 = 0, m3 = 0, m4 = 0;
int rmx = 99;
cout << "Введите количество недель ";
cin >> sz;
k = sz * 7;
cout << "Массив А:" << endl;
srand((unsigned)time(NULL));
for (i = 0; i < k; i++)
{
A[i] = rand() % rmx;
cout << "[" << i + 1 << " день] " << A[i] << endl;
}
for (i = 0; i < k; i++)
{
if (i < 7) {
m1 = m1 + A[i];
}
else if (7 < i && i < 15) {
m2 = m2 + A[i];
}
else if (14 < i && i < 22) {
m3 = m3 + A[i];
}
else if (21 < i && i < 29) {
m4 = m4 + A[i];
}
}
cout << endl;
if (m1 * (sz - 1) > m2 + m3 + m4) {
cout << "В первую неделю выпало больше всего осадков";
}
else if (m2 * (sz - 1) > m1 + m3 + m4) {
cout << "Во вторую неделю выпало больше всего осадков";
}
else if (m3 * (sz - 1) > m1 + m2 + m4) {
cout << "В третью неделю выпало больше всего осадков";
}
else if (m4 * (sz - 1) > m1 + m2 + m3) {
cout << "В четвертую неделю выпало больше всего осадков";
}
}
// Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки"
// Отладка программы: F5 или меню "Отладка" > "Запустить отладку"
// Советы по началу работы
// 1. В окне обозревателя решений можно добавлять файлы и управлять ими.
// 2. В окне Team Explorer можно подключиться к системе управления версиями.
// 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения.
// 4. В окне "Список ошибок" можно просматривать ошибки.
// 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода.
// 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
| true |
7ba359379fde6338e453cb11e9dbd0a3d7c8bb4e | C++ | strangeTany/pss_assignments | /Assignment2/Rooms/Room.h | UTF-8 | 1,149 | 2.796875 | 3 | [] | no_license | //
// Created by strangetany on 05.03.2021.
//
#ifndef ASSIGNMENT2_ROOM_H
#define ASSIGNMENT2_ROOM_H
#ifndef CONDITION
#define CONDITION
enum Condition {
on, off, broken
};
#endif
#include "../AccessLevel.cpp"
#include "../Users/User.h"
#include <string>
#include <vector>
class User;
class Room {
protected:
Room(int roomNumber, int floor, Level accessLevel);
Room(int roomNumber, int floor, Level accessLevel, std::string name);
void setClosed(bool closed);
inline static std::vector<Room*> allRooms;
private:
int roomNumber;
Level accessLevel;
std::string name;
bool closed = true;
int floor;
public:
std::vector<std::string> specialAccess;
Room(int roomNumber, int floor, std::string name);
int getRoomNumber() const;
Level getAccessLevel() const;
void changeAccessLevel(Level accessLevel);
const std::string &getName() const;
void setName(const std::string &name);
int getFloor() const;
virtual bool open(const User&, bool isEmergency);
virtual void close();
static const std::vector<Room *> &getAllRooms();
};
#endif //ASSIGNMENT2_ROOM_H
| true |
375dc5d2b2226446c96841875e3c0532f3c97885 | C++ | SoltiHo/LeetRepository | /Single_Number_II/Single_Number_II/Single_Number_II.h | UTF-8 | 2,416 | 3.703125 | 4 | [] | no_license | // Given an array of integers, every element appears three times except for one.Find that single one.
//
// Note:
// Your algorithm should have a linear runtime complexity.Could you implement it without using extra memory ?
#include <unordered_map>
using namespace std;
class Solution_LatestTrial {
public:
int singleNumber(int A[], int n) {
int AA = 0; // twice
int BB = 0; // once
int lastAA = 0;
int lastBB = 0;
for (int i = 0; i < n; ++i){
lastAA = AA;
lastBB = BB;
AA = (A[i] & lastBB) | (~A[i] & lastAA);
BB = (A[i] & ~lastAA & ~lastBB) | (~A[i] & lastBB);
}
if (n % 3 == 2){
return AA;
}
else{
return BB;
}
}
};
class Solution_LogicTable {
public:
int singleNumber(int A[], int n) {
int once = 0;
int twice = 0;
int lastOnce = 0;
int lastTwice = 0;
for (int i = 0; i < n; ++i){
lastOnce = once;
lastTwice = twice;
once = (A[i] & (~lastOnce) & (~lastTwice)) | (~A[i] & lastOnce);
twice = (A[i] & lastOnce) | (~A[i] & lastTwice);
}
if (n % 3 == 2){
return twice;
}
else{
return once;
}
}
};
class Solution_HashTable {
public:
int singleNumber(int A[], int n) {
unordered_map<int, int> counter;
unordered_map<int, int>::iterator it;
for (int i = 0; i < n; ++i){
if ((it = counter.find(A[i])) == counter.end()){
// new number
counter.insert({ A[i], 1 });
}
else{
it->second++;
}
}
for (auto& i : counter){
if (i.second != 3){
return i.first;
}
}
}
};
class Solution {
public:
int singleNumber(int A[], int n) {
unordered_map<int, int> counter;
unordered_map<int, int>::iterator it;
for (int i = 0; i < n; ++i){
if ((it = counter.find(A[i])) == counter.end()){
// new number
counter.insert({ A[i], 1 });
}
else{
it->second++;
}
}
for (auto& i : counter){
if (i.second != 3){
return i.first;
}
}
}
}; | true |
921e99fe561f741f4b64ff7d0e1b826b09868153 | C++ | ramssrez/InicioProgramacionC | /ejerciciosconC/EjerciciosPrevios/TiposDeDatosC.cpp | UTF-8 | 535 | 3.0625 | 3 | [] | no_license | //Declaracion de librerias ya de defult o que se pueden construir
#include <iostream>
#include <stdio.h>
#include <complex.h>
#include <stdlib.h
using namespace std;
int main (){
//Salida de datos, para ambos lenguajes de programción
cout <<"Hola mundo"; // Esto es para C++
printf("\nAdios") ; //Esto es para C
//Tipos de datos primitivos.
\*
*Los tipos de enteros son los char, short, int , long, enum.
* Los tipos reales son los siguientes de tipo: float, double, long double.
*
*\
} | true |
182d50051df201d7a0d4d1cb5278ab099a20adc4 | C++ | eddast/T-528-HLUT | /Assignments/Assignment solutions/Assignment1 - Matrix/include/matrix.h | UTF-8 | 2,830 | 3.84375 | 4 | [] | no_license | #ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
#include <vector>
namespace matrix {
typedef int Element;
class matrix_dimensions_wrong: public std::exception {
virtual const char* what() const throw() {
return "Wrong matrix dimensions for operation";
}
};
class Matrix {
public:
Matrix(int num_rows, int num_cols, const Element initial = Element());
Matrix(const Matrix& m);
Matrix& operator=(const Matrix& rhs);
virtual ~Matrix();
// Mathematical operations on a matrix (and a scalar).
Matrix transpose();
Matrix operator+(const Element& elem) const;
Matrix operator*(const Element& elem) const;
// Mathematical operations on two matrices.
Matrix operator+(const Matrix& rhs) const;
Matrix operator-(const Matrix& rhs) const;
Matrix operator*(const Matrix& rhs) const; // dot-product
Matrix& operator+=(const Matrix& rhs);
Matrix& operator-=(const Matrix& rhs);
Matrix& operator*=(const Matrix& rhs); // dot-product
// Check for equality.
bool operator==(const Matrix& rhs ) const;
// Access individual elements
Element& operator()(const int& row, const int& col);
const Element& operator()(const int& row, const int& col) const;
// Accessors for number of rows and columns.
int get_num_rows() const;
int get_num_cols() const;
// Input / Output
friend std::istream& operator >> ( std::istream& is, Matrix& rhs );
friend std::ostream& operator << ( std::ostream& os, const Matrix& rhs );
private:
int index(int row, int col ) const {
return row * num_cols_ + col;
}
int num_rows_;
int num_cols_;
Element* data_; // implement 2D using 1D array and above index function
};
inline std::istream& operator >> ( std::istream& is, Matrix& rhs )
{
for ( int row = 0; row < rhs.get_num_rows(); ++row ) {
for ( int col = 0; col < rhs.get_num_cols(); ++col ) {
Element elem;
is >> elem;
rhs(row,col) = elem;
}
}
return is;
}
inline std::ostream& operator << ( std::ostream& os, const Matrix& rhs )
{
for ( int row = 0; row < rhs.get_num_rows(); ++row ) {
for ( int col = 0; col < rhs.get_num_cols(); ++col ) {
os << ' ' << rhs(row,col);
}
os << '\n';
}
return os;
}
inline Matrix operator+(const Element& elem, const Matrix& rhs)
{
return rhs + elem;
}
inline Matrix operator*(const Element& elem, const Matrix& rhs)
{
return rhs * elem;
}
}
#endif //MATRIX_H
| true |
dd180c6a521a00b06d9a524f850bf265eb37b081 | C++ | a60504a60504/OnlineJudge_Solution | /Leetcode/leetcode36.cpp | UTF-8 | 921 | 2.9375 | 3 | [] | no_license | #include <bits/stdc++.h>
#define endl '\n'
using namespace std;
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
for (vector<vector<char>>::iterator col=board.begin();col!=board.end();++col) {
for (vector<char>::iterator row=col->begin();row!=col->end();++row){
cout << *row<< endl;
}
}
return true;
}
};
int main () {
//ios::sync_with_stdio(false);
//cin.tie(0);
Solution s;
string input_list;
vector<vector<char>> board;
vector<char> newCol;
char item;
while (1) {
while (board.size() < 81){
getline(cin,input_list);
istringstream T(input_list);
while (T >> item) {
if ((item >= '1' && item <='9')||item == '.') {
board.push_back(newCol);
board.at(int(board.size()/9)).push_back(item);
}
}
}
cout << s.isValidSudoku(board) << endl;
system("pause");
}
return 0;
} | true |
9b33a294691cad0077446f884ec20583a4094e85 | C++ | Khaled-Issa/Data-Encryption-Standard | /DESDecrypt.cpp | UTF-8 | 9,730 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
//[8][8]
vector <int> InitialPermutation = {
58, 50, 42, 34, 26, 18, 10, 2 ,
60, 52, 44, 36, 28, 20, 12, 4 ,
62, 54, 46, 38, 30, 22, 14, 6 ,
64, 56, 48, 40, 32, 24, 16, 8 ,
57, 49, 41, 33, 25, 17, 9, 1 ,
59, 51, 43, 35, 27, 19, 11, 3 ,
61, 53, 45, 37, 29, 21, 13, 5 ,
63, 55, 47, 39, 31, 23, 15, 7
};
//8*7
vector <int> PermutationChoice1 = {
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
int LShiftRound[16] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
//8*6
vector <int> PermutationChoice2 = {
14, 17, 11, 24, 1, 5,3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32
};
vector<int> ExpansionPermutation = {
32, 1, 2, 3, 4, 5 ,
4, 5, 6, 7, 8, 9 ,
8, 9, 10, 11, 12, 13 ,
12, 13, 14, 15, 16, 17 ,
16, 17, 18, 19, 20, 21 ,
20, 21, 22, 23, 24, 25 ,
24, 25, 26, 27, 28, 29 ,
28, 29, 30, 31, 32, 1
};
int sbox[8][4][16] = {
{
{ 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7 },
{ 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8 },
{ 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0 },
{ 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13 }
},
{
{ 15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10 },
{ 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5 },
{ 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15 },
{ 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9 }
},
{
{ 10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8 },
{ 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1 },
{ 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7 },
{ 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12 }
},
{
{ 7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15 },
{ 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9 },
{ 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4 },
{ 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14 }
},
{
{ 2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9 },
{ 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6 },
{ 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14 },
{ 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3 }
},
{
{ 12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11 },
{ 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8 },
{ 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6 },
{ 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13 }
},
{
{ 4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1 },
{ 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6 },
{ 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2 },
{ 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12 }
},
{
{ 13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7 },
{ 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2 },
{ 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8 },
{ 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11 }
}
};
//Permutation[4][8]
vector<int> PermutationFunction = {
16, 7, 20, 21 , 29, 12, 28, 17,
1, 15, 23, 26 ,5 , 18, 31, 10,
2, 8, 24, 14 , 32, 27, 3, 9,
19, 13, 30, 6 ,22, 11, 4, 25
};
//[8][8]
vector <int> InverseInitPermutation = {
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
const char* hex_char_to_bin(char c)
{
switch (toupper(c))
{
case '0': return "0000";
case '1': return "0001";
case '2': return "0010";
case '3': return "0011";
case '4': return "0100";
case '5': return "0101";
case '6': return "0110";
case '7': return "0111";
case '8': return "1000";
case '9': return "1001";
case 'A': return "1010";
case 'B': return "1011";
case 'C': return "1100";
case 'D': return "1101";
case 'E': return "1110";
case 'F': return "1111";
}
}
string hex_str_to_bin_str(const string& hex)
{
string bin;
for (unsigned i = 0; i != hex.length(); ++i)
bin += hex_char_to_bin(hex[i]);
return bin;
}
const char* bin_char_to_hex4(string c)
{
if (!c.compare("0000")) return "0";
else if (!c.compare("0001")) return "1";
else if (!c.compare("0010")) return "2";
else if (!c.compare("0011")) return "3";
else if (!c.compare("0100")) return "4";
else if (!c.compare("0101")) return "5";
else if (!c.compare("0110")) return "6";
else if (!c.compare("0111")) return "7";
else if (!c.compare("1000")) return "8";
else if (!c.compare("1001")) return "9";
else if (!c.compare("1010")) return "A";
else if (!c.compare("1011")) return "B";
else if (!c.compare("1100")) return "C";
else if (!c.compare("1101")) return "D";
else if (!c.compare("1110")) return "E";
else if (!c.compare("1111")) return "F";
else return "";
}
string bin_str_to_hex_str4(const string& bin)
{
string hex;
for (int i = 0; i < bin.length(); i = i + 4) {
hex += bin_char_to_hex4(bin.substr(i, 4));
}
return hex;
}
const int bin_char_to_dec4(string c)
{
if (!c.compare("0000")) return 0;
else if (!c.compare("0001")) return 1;
else if (!c.compare("0010")) return 2;
else if (!c.compare("0011")) return 3;
else if (!c.compare("0100")) return 4;
else if (!c.compare("0101")) return 5;
else if (!c.compare("0110")) return 6;
else if (!c.compare("0111")) return 7;
else if (!c.compare("1000")) return 8;
else if (!c.compare("1001")) return 9;
else if (!c.compare("1010")) return 10;
else if (!c.compare("1011")) return 11;
else if (!c.compare("1100")) return 12;
else if (!c.compare("1101")) return 13;
else if (!c.compare("1110")) return 14;
else if (!c.compare("1111")) return 15;
}
string bin_str_to_dec_str(const string& bin)
{
string dec;
for (int i = 0; i < bin.length(); i = i + 4) {
dec += bin_char_to_dec4(bin);
}
return dec;
}
const int bin_char_to_dec2(string c)
{
if (!c.compare("00")) return 0;
else if (!c.compare("01")) return 1;
else if (!c.compare("10")) return 2;
else if (!c.compare("11")) return 3;
}
string bin_str_to_dec_str2(const string& bin)
{
string hex;
for (int i = 0; i < bin.length(); i = i + 4) {
hex += bin_char_to_dec2(bin);
}
return hex;
}
const char* dec_int_to_bin(int c)
{
switch (toupper(c))
{
case 0: return "0000";
case 1: return "0001";
case 2: return "0010";
case 3: return "0011";
case 4: return "0100";
case 5: return "0101";
case 6: return "0110";
case 7: return "0111";
case 8: return "1000";
case 9: return "1001";
case 10: return "1010";
case 11: return "1011";
case 12: return "1100";
case 13: return "1101";
case 14: return "1110";
case 15: return "1111";
}
}
string permutate(string text, vector <int> box) {
string textbin = hex_str_to_bin_str(text);
string textpermuatetd;
for (int i = 0; i < box.size(); i++) {
textpermuatetd += (textbin[box[i] - 1]);
}
return textpermuatetd;
}
string shiftlift(string input, int shift) {
string output;
output = output + (input.substr(shift, 28) + input.substr(0, shift));
return output;
}
string xxor(string in1, string in2) {
string output;
for (int i = 0; i < in2.length(); i++) {
if (in1[i] == in2[i]) {
output = output + "0";
}
else {
output = output + "1";
}
}
return output;
}
string s_box(string bininput) {
string osbox[8];
string row;
string column;
string result;
for (int i = 0; i < 8; i++) {
osbox[i] = (bininput).substr(i * 6, 6);
row = osbox[i].substr(0, 1) + osbox[i].substr(5, 1);
column = osbox[i].substr(1, 4);
result += (dec_int_to_bin((sbox[i][bin_char_to_dec2(row)][bin_char_to_dec4(column)])));
}
return result;
}
void encrypt(string ct, string k, int n) {
string ip; string pc1 = permutate(k, PermutationChoice1);
string L; string C = pc1.substr(0, 28);
string R; string D = pc1.substr(28, 28);
string ep; string pc2;
string F; string keyno[16];
string S;
string pf;
string result;
string iip;
if (n == 0) { cout << ct; }
for (int i = 0; i < 16; i++) {
C = shiftlift(C, LShiftRound[i]);
D = shiftlift(D, LShiftRound[i]);
pc2 = permutate(bin_str_to_hex_str4(C + D), PermutationChoice2);
keyno[i] = pc2;
}
for (int i = 0; i < n; i++) {
ip = permutate(ct, InitialPermutation);
L = ip.substr(0, 32);
R = ip.substr(32, 32);
for (int j = 0; j < 16; j++) {
ep = permutate(bin_str_to_hex_str4(R), ExpansionPermutation);
F = xxor(ep, keyno[15-j]);
S = s_box(F);
pf = permutate(bin_str_to_hex_str4(S), PermutationFunction);
result = xxor(pf, L);
L = R;
R = result;
}
iip = permutate(bin_str_to_hex_str4(R + L), InverseInitPermutation);
ct = bin_str_to_hex_str4(iip);
}
cout << bin_str_to_hex_str4(iip);
}
int main()
{
string cipherText;
string key;
int nofrounds;
cin >> key >> cipherText >> nofrounds;
encrypt(cipherText, key, nofrounds);
return 0;
} | true |
56f7f02e6b7cd3652e76a0d6f1828e43a45b0a12 | C++ | greenfox-zerda-sparta/Ak0s | /Week-08/day-4/08/08.cpp | UTF-8 | 746 | 3.484375 | 3 | [] | no_license | //============================================================================
// Name : 08.cpp
// Author : Ak0s
//============================================================================
// Given a string, compute recursively a new string where all the 'x' chars have been removed.
#include <iostream>
#include <string>
using namespace std;
string delete_all_x(string str, unsigned int char_index = 0) {
if (char_index == str.length()) {
return str;
}
if (str[char_index] == 'x') {
str.erase(str.begin()+char_index);
return delete_all_x(str, char_index);
}
else {
return delete_all_x(str, char_index + 1);
}
}
int main() {
string str = "xanax";
cout << delete_all_x(str);
return 0;
}
| true |
baa06019c27649c80d7767a8bf953655fa7ecd89 | C++ | jungsagacity/functionCombination_ | /xmill/FileParser.hpp | UTF-8 | 11,623 | 2.703125 | 3 | [] | no_license | /*
This product contains certain software code or other information
("AT&T Software") proprietary to AT&T Corp. ("AT&T"). The AT&T
Software is provided to you "AS IS". YOU ASSUME TOTAL RESPONSIBILITY
AND RISK FOR USE OF THE AT&T SOFTWARE. AT&T DOES NOT MAKE, AND
EXPRESSLY DISCLAIMS, ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND
WHATSOEVER, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, WARRANTIES OF
TITLE OR NON-INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS, ANY
WARRANTIES ARISING BY USAGE OF TRADE, COURSE OF DEALING OR COURSE OF
PERFORMANCE, OR ANY WARRANTY THAT THE AT&T SOFTWARE IS "ERROR FREE" OR
WILL MEET YOUR REQUIREMENTS.
Unless you accept a license to use the AT&T Software, you shall not
reverse compile, disassemble or otherwise reverse engineer this
product to ascertain the source code for any AT&T Software.
(c) AT&T Corp. All rights reserved. AT&T is a registered trademark of AT&T Corp.
***********************************************************************
History:
24/11/99 - initial release by Hartmut Liefke, liefke@seas.upenn.edu
Dan Suciu, suciu@research.att.com
*/
//**************************************************************************
//**************************************************************************
// This module contains a few Input file parsing routines used for
// parsing XML files. Most importantly, it keeps track of the line number
#include "Input.hpp"
class FileParser : public Input
{
unsigned curlineno; // The current line number
public:
char OpenFile(char *filename)
// Opens the file and fills the buffer
{
curlineno=1;
return Input::OpenFile(filename);
}
unsigned GetCurLineNo() { return curlineno; }
char ReadStringUntil(char **destptr,int *destlen,char stopatwspace,char c1,char c2)
// This function scans ahead in the buffer until some character c1 or c2 occurs
// If 'stopwspace=1', then we also stop at the first white space detected.
// In this case, *destptr and *destlen will contain the pointer and length
// of the buffer *with* the character c1 or c2 and the functions returns 1.
// If a white space has been detected, then the function also returns 1,
// but the white-space is *not* included in the length.
// If the function couldn't find such a character in the current buffer, we try to refill
// If it is still not found, then the function returns the current buffer in *destptr and *destlen
// and returns 0.
{
char *curptr,*ptr;
int len,i;
// Let's get as much as possible from the input buffer
len=GetCurBlockPtr(&ptr);
curptr=ptr;
i=len;
// We search for characters 'c1', 'c2', ' ', '\t' ...
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if(*curptr=='\n')
curlineno++;
if((*curptr==c1)||(*curptr==c2))
{
curptr++;
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if((stopatwspace)&&((*curptr==' ')||(*curptr=='\t')||(*curptr=='\r')||(*curptr=='\n')))
{
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
curptr++;
i--;
}
// We couldn't find characters --> Try to refill
RefillAndGetCurBlockPtr(&ptr,&len);
curptr=ptr;
i=len;
// Now we try the same thing again:
// We search for characters 'c1', 'c2', ' ', '\t' ...
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if(*curptr=='\n')
curlineno++;
if((*curptr==c1)||(*curptr==c2))
{
curptr++;
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if((stopatwspace)&&((*curptr==' ')||(*curptr=='\t')||(*curptr=='\r')||(*curptr=='\n')))
{
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
curptr++;
i--;
}
*destptr=ptr;
*destlen=len;
FastSkipData(len);
return 0;
}
char ReadStringUntil(char **destptr,int *destlen,char c1)
// This function scans ahead in the buffer until some character c1 occurs
// In this case, *destptr and *destlen will contain the pointer and length
// of the buffer *with* the character and the functions returns 0.
// If the function couldn't find such a character in the current buffer, we try to refill
// If it is still not found, then the function returns the current buffer in *destptr and *destlen
// and returns 0.
{
char *curptr,*ptr;
int len,i;
len=GetCurBlockPtr(&ptr);
curptr=ptr;
i=len;
// We search for character 'c1'.
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if(*curptr==c1)
{
curptr++;
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if(*curptr=='\n')
curlineno++;
curptr++;
i--;
}
// We couldn't find characters --> Try to refill
RefillAndGetCurBlockPtr(&ptr,&len);
curptr=ptr;
i=len;
// Now we try the same thing again:
// We search for character 'c1'.
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if(*curptr==c1)
{
curptr++;
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if(*curptr=='\n')
curlineno++;
curptr++;
i--;
}
*destptr=ptr;
*destlen=len;
FastSkipData(len);
return 0;
}
char ReadWhiteSpaces(char **destptr,int *destlen)
// This function scans ahead in the buffer over all white-spaces
// *destptr and *destlen will contain the pointer and length
// of the buffer with the white-spaces
// If the buffer got fill without reaching a non-whitespace character,
// then the function returns the current buffer in *destptr and *destlen
// and returns 1. Otherwise,
{
char *curptr,*ptr;
int len,i;
len=GetCurBlockPtr(&ptr);
curptr=ptr;
i=len;
// We search for non-white-space characters
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if((*curptr!=' ')&&(*curptr!='\t')&&(*curptr!='\r')&&(*curptr!='\n'))
// No white space?
{
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if(*curptr=='\n')
curlineno++;
curptr++;
i--;
}
// We couldn't find characters --> Try to refill
RefillAndGetCurBlockPtr(&ptr,&len);
curptr=ptr;
i=len;
// Now we try the same thing again:
// We search for non-white-space characters
// If we find such a character, then we store the pointer in 'destptr'
// and the length in 'destlen' and exit.
while(i!=0)
{
if((*curptr!=' ')&&(*curptr!='\t')&&(*curptr!='\r')&&(*curptr!='\n'))
// No white space?
{
*destptr=ptr;
*destlen=curptr-ptr;
FastSkipData(*destlen);
return 1;
}
if(*curptr=='\n')
curlineno++;
curptr++;
i--;
}
// We look through the entire buffer and couldn't find a non-white-space
// character?
*destptr=ptr;
*destlen=len;
FastSkipData(len);
return 0;
}
char ReadStringUntil(char **destptr,int *destlen,char *searchstr)
// This function scans ahead in the buffer until string 'searchstr'
// is reached. In this case, *destptr and *destlen will contain the pointer and length
// of the buffer *with* the search string at the end and the functions returns 0.
// If the function couldn't find such a character in the current buffer, we try to refill
// If it is still not found, then the function returns the current buffer in *destptr and *destlen
// and returns 1.
{
char *ptr;
int len,stringlen;
char refilled=0;
int curoffset=0,i;
char *curptr;
len=GetCurBlockPtr(&ptr);
stringlen=strlen(searchstr);
do
{
// We try to find the first character
curptr=ptr+curoffset;
i=len-curoffset;
while(i!=0)
{
if(*curptr==searchstr[0])
break;
if(*curptr=='\n')
curlineno++;
curptr++;
i--;
}
if(i==0)
// We couldn't find characters --> Try to refill
{
if(!refilled)
{
curoffset=len; // We can skip the part that we already scanned
refilled=1;
RefillAndGetCurBlockPtr(&ptr,&len);
continue;
}
else
// We couldn't find the first character in the current block --> We return current block
{
*destptr=ptr;
*destlen=len;
FastSkipData(len);
return 0;
}
}
// We found the first character at *curptr
curoffset=curptr-ptr;
if(curoffset+stringlen>len)
// There is not enough room for the search string?
{
if(!refilled) // If we didn't try refill yet, we try it now
{
refilled=1;
RefillAndGetCurBlockPtr(&ptr,&len);
}
if(curoffset+stringlen>len) // Still not enough space?
{
*destptr=ptr;
*destlen=curoffset; // We take everything up to (but excluding) the first character at *curptr
FastSkipData(curoffset);
return 0;
}
}
// Now we check whether ptr+offset is equal to the searchstring
if(memcmp(ptr+curoffset,searchstr,stringlen)==0)
// We found it !
{
*destptr=ptr;
*destlen=curoffset+stringlen;
FastSkipData(*destlen);
return 1;
}
// We didn't find it ==> We go to next character after ptr+curoffset
curoffset++;
}
while(1);
}
void SkipChar()
// Skips the next character
{
char c;
Input::GetChar(&c);
if(c=='\n')
curlineno++;
}
void GetChar(char *c)
// Reads the next character
{
Input::GetChar(c);
if(*c=='\n')
curlineno++;
}
void SkipData(int len)
// Skips 'len' characters
{
char *ptr;
int mylen;
mylen=GetCurBlockPtr(&ptr);
for(int i=0;i<len;i++)
{
if(*ptr=='\n')
curlineno++;
ptr++;
}
Input::SkipData(len);
}
};
| true |
e854b547a7d0faacaa7134e61affcc5b832e85e7 | C++ | hqsun2017/Fourier | /Fourier/Color.cpp | UTF-8 | 1,731 | 2.578125 | 3 | [] | no_license | #include "Color.h"
CColor::CColor()
{
m_bGamma=false; m_fGamma=0.6;
m_Colors[0]=RGB(0,0,0);
m_Colors[1]=RGB(0,0,255);
m_Colors[2]=RGB(102,102,102);
m_Colors[3]=RGB(0,255,0);
m_Colors[4]=RGB(153,153,153);
m_Colors[5]=RGB(255,0,0);
m_Colors[6]=RGB(204,204,204);
m_Colors[7]=RGB(0,255,255);
m_Colors[8]=RGB(255,0,255);
m_Colors[9]=RGB(255,255,0);
m_Colors[10]=RGB(255,255,255);
}
COLORREF CColor::CalcColor(double ftmp,bool bcolor)
{
//if(TOTALCOLORS<2) return;
COLORREF color1=m_Colors[0],color2=m_Colors[TOTALCOLORS-1];
if(m_fMin==m_fMax) return (bcolor ? color2 : RGB(255,255,255));
if(ftmp>=m_fMax) return (bcolor ? color2 : RGB(255,255,255));
if(ftmp<=m_fMin) return (bcolor ? color1 : RGB(0,0,0));
if(false==bcolor)
{
int ngray=int(255.0*(ftmp-m_fMin)/(m_fMax-m_fMin));
if(ngray>255) ngray=255;
if(ngray<0) ngray=0;
return RGB(ngray,ngray,ngray);
}
double ratio,offset=(m_fMax-m_fMin)/(TOTALCOLORS-1);
int order=int((ftmp-m_fMin)/offset);
if(order>=TOTALCOLORS-1) return color2;
if(order<0) return color1;
color1=m_Colors[order],color2=m_Colors[order+1];
ratio=(ftmp-m_fMin)/offset-order;//Gradient color ratio
//Gradient color
unsigned char red,green,blue;
red=(unsigned char)(GetRValue(color2)*ratio+GetRValue(color1)*(1-ratio));
green=(unsigned char)(GetGValue(color2)*ratio+GetGValue(color1)*(1-ratio));
blue=(unsigned char)(GetBValue(color2)*ratio+GetBValue(color1)*(1-ratio));
if(true==m_bGamma)
{
red=(unsigned char)(pow((double)red/255.0,m_fGamma)*255);
green=(unsigned char)(pow((double)green/255.0,m_fGamma)*255);
blue=(unsigned char)(pow((double)blue/255.0,m_fGamma)*255);
}
return RGB(red,green,blue);
}
| true |
b9e3052ae7cfc8ba4a414311f344c27eac894133 | C++ | jack23912/Selfimage-plus | /prev/gtkSelfimage/src/sort.cpp | UTF-8 | 276 | 2.640625 | 3 | [] | no_license | #include "sort.h"
bool WideStringSorter(const wchar_t *a, const wchar_t *b)
{
int l1, l2;
l1 = wcslen (a);
l2 = wcslen (b);
if (l1 > l2){
if (wmemcmp(a,b,l1) > 0)
return false;
return true;
}else{
if (wmemcmp(a,b,l2) > 0)
return false;
return true;
}
}
| true |
96fc45de4f25c79432efc25354e00edf7a9edc63 | C++ | andreyrehv/PA | /Atividades C/Exercicio 14.cpp | WINDOWS-1252 | 343 | 2.765625 | 3 | [] | no_license | #include<stdio.h>
#include<stdlib.h>
#include<locale.h>
#include<math.h>
#define PI 3.14
int main(){
setlocale(LC_ALL,"Portuguese");
float R, V;
printf("Calcule a esfera \n");
puts("Digite o raio da esfera");
scanf("%f", &R);
V=((4*PI)*(R*R*R))/3;
printf("O volume da esfera : %.2f \n", V);
system("PAUSE");
return(0);
}
| true |
a244e6e92eec4905b3b78d7f4d4ea1bb7006c982 | C++ | azell003/Algorithms | /Data Structures/FenwickTree2D.cpp | UTF-8 | 781 | 3.34375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
const int N = 105;
int max_x, max_y;
int tree[N][N];
void update(int x, int y, int val)
{
for(int i = x; i <= max_x; i += i & (-i))
for(int j = y; j <= max_y; j += j & (-j))
tree[i][j] += val;
}
int get(int x, int y)
{
int res = 0;
for(int i = x; i > 0; i -= i & (-i))
for(int j = y; j > 0; j -= j & (-j))
res += tree[i][j];
return res;
}
int rsq(int x1, int y1, int x2, int y2)
{
return get(x2, y2) - get(x2, y1 - 1) - get(x1 - 1, y2) + get(x1 - 1, y1 - 1);
}
int main()
{
max_x = max_y = 4;
update(1, 1, 1);
cout << rsq(1, 1, 4, 4) << endl;
update(3, 3, 12);
cout << rsq(3, 3, 3, 3) << endl;
cout << rsq(3, 3, 4, 4) << endl;
cout << rsq(1, 1, 3, 3) << endl;
return 0;
}
| true |
e0558e323ba33eb406a5f752522a39e6d60e78be | C++ | Clemon-R/Arcade | /games/pacman/Player.cpp | UTF-8 | 1,920 | 2.828125 | 3 | [] | no_license | //
// EPITECH PROJECT, 2018
// Player.cpp
// File description:
// Payer Class functions
//
#include "game/pacman/Player.hpp"
#include "Control.hpp"
Player::Player(std::size_t x, std::size_t y, std::vector<std::string> *map) :
_x(x),
_y(y),
_map(map),
_dead(false),
_score(0),
_killer(false)
{
}
int Player::checkValidMove(int const x, int const y)
{
if (x < _map[0][0].size() && y < _map->size() && _map[0][y][x] != '#')
return (0);
return (1);
}
void Player::move(int const x, int const y)
{
if (_killer && _pacgumTimer.getTimeS() >= 10)
_killer = false;
if (!_killer && _map[0][y][x] == 'g')
_dead = true;
else if (_map[0][y][x] == 'g')
_score += 200;
if (_map[0][y][x] == '.')
_score += 20;
if (_map[0][y][x] == 'O') {
_pacgumTimer.restart();
_killer = true;
}
_map[0][_y][_x] = ' ';
_map[0][y][x] = 'p';
_y = y;
_x = x;
}
void Player::move(int key)
{
switch (key) {
case Control::UP:
if (!checkValidMove(_x, _y - 1))
move(_x, _y - 1);
break;
case Control::DOWN:
if (!checkValidMove(_x, _y + 1))
move(_x, _y + 1);
break;
case Control::LEFT:
if (!checkValidMove(_x - 1, _y))
move(_x - 1, _y);
break;
case Control::RIGHT:
if (!checkValidMove(_x + 1, _y))
move(_x + 1, _y);
break;
}
}
int Player::tryMove(int key)
{
switch (key) {
case Control::UP:
return (checkValidMove(_x, _y - 1));
case Control::DOWN:
return (checkValidMove(_x, _y + 1));
case Control::LEFT:
return (checkValidMove(_x - 1, _y));
case Control::RIGHT:
return (checkValidMove(_x + 1, _y));
}
return (1);
}
bool const Player::getDead() const
{
return (_dead);
}
void Player::setDead(bool dead)
{
_dead = dead;
}
bool const Player::getKiller() const
{
return (_killer);
}
void Player::setKiller(bool killer)
{
_killer = killer;
}
std::size_t const Player::getScore() const
{
return (_score);
}
void Player::setScore(std::size_t score)
{
_score = score;
}
| true |
d4da18cca53c5d8ebcc434ed7669380bae502aa3 | C++ | fedesassone/tp2SO | /tiempos.cpp | UTF-8 | 8,334 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include "ConcurrentHashMap.hpp"
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <cassert>
#include <vector>
#include <queue>
#include <tuple>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <functional>
#include <ctime>
#include <chrono>
#include <limits>
#include <climits>
#include "time.h"
#include <utility>
#include <random>
#include <iostream>
#include <sstream>
#include <exception>
#define TIMESTAMP chrono::high_resolution_clock::now
#define GRANULARIDAD nanoseconds
void TiemposExp1(int cantIteraciones){
ofstream myfile;
myfile.open("TiemposExp1.csv");
list<string> l = { "8000", "2000-1", "2000-2", "2000-3", "2000-4", "2000-5", "2000-6", "2000-7", "2000-8", "2000-9" };
myfile << "Cantidad de p_archivos;";
myfile << "Sin concurrencia;";
myfile << "Con concurrencia;\n";
ParClaveApariciones p;
vector< chrono::GRANULARIDAD > tiempos(cantIteraciones);//vector donde voy poniendo los tiempos de las iteraciones para luego calcularle la mediana
for(int j=1; j<=10; j++){// j es p_archivos
cout << " Midiendo con p_archivos: " << j << endl;
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumSinConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
myfile << j << ";";
myfile << tiempos.at(tiempos.size()/2).count() << ";";//pongo la mediana de maximoConConcurrencia con p_archivos = j
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumConConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
myfile << tiempos.at(tiempos.size()/2).count() << ";\n";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
}
}
void TiemposExp2(int cantIteraciones){
ofstream myfile;
myfile.open("TiemposExp2.csv");
list<string> l = { "corpus-0", "corpus-1", "corpus-2", "corpus-3","corpus-4", "corpus-5","corpus-6", "corpus-7","corpus-8", "corpus-9", };
myfile << "Cantidad de p_archivos;";
myfile << "Sin concurrencia;";
myfile << "Con concurrencia;\n";
ParClaveApariciones p;
vector< chrono::GRANULARIDAD > tiempos(cantIteraciones);//vector donde voy poniendo los tiempos de las iteraciones para luego calcularle la mediana
for(int j=1; j<=10; j++){// j es p_archivos
cout << " Midiendo con p_archivos: " << j << endl;
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumSinConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
myfile << j << ";";
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";";
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumConConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";\n";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";\n";
}
}
void TiemposExp3(int cantIteraciones){
auto max_threads = 26;
ofstream myfile;
myfile.open("TiemposExp3.csv");
list<string> l = {"corpus-letra-0", "corpus-letra-1", "corpus-letra-2", "corpus-letra-3", "corpus-letra-4", "corpus-letra-5", "corpus-letra-6", "corpus-letra-7", "corpus-letra-8", "corpus-letra-9", "corpus-letra-10", "corpus-letra-11", "corpus-letra-12", "corpus-letra-13", "corpus-letra-14", "corpus-letra-15", "corpus-letra-16", "corpus-letra-17", "corpus-letra-18", "corpus-letra-19", "corpus-letra-20", "corpus-letra-21", "corpus-letra-22", "corpus-letra-23", "corpus-letra-24", "corpus-letra-25" };
myfile << "Cantidad de p_archivos;";
myfile << "Sin concurrencia;";
myfile << "Con concurrencia;\n";
ParClaveApariciones p;
vector< chrono::GRANULARIDAD > tiempos(cantIteraciones);//vector donde voy poniendo los tiempos de las iteraciones para luego calcularle la mediana
for(int j=1; j<=max_threads; j++){// j es p_archivos
cout << " Midiendo con p_archivos: " << j << endl;
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumSinConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
myfile << j << ";";
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";";
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumConConcurrencia(j, 10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";\n";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";\n";
}
}
void TiemposExp4(int cantIteraciones){
ofstream myfile;
myfile.open("TiemposExp4.csv");
list<string> l = { "corpus-letra-A-0","corpus-letra-A-1","corpus-letra-A-2","corpus-letra-A-3","corpus-letra-A-4","corpus-letra-A-5","corpus-letra-A-6","corpus-letra-A-7" };
myfile << "Cantidad de p_archivos;";
myfile << "Sin concurrencia;";
myfile << "Con concurrencia;\n";
ParClaveApariciones p;
vector< chrono::GRANULARIDAD > tiempos(cantIteraciones);//vector donde voy poniendo los tiempos de las iteraciones para luego calcularle la mediana
for(int j=1; j<=8; j++){// j es p_archivos
cout << " Midiendo con p_archivos: " << j << endl;
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumSinConcurrencia(j,10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
myfile << j << ";";
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";";
for(int i = 0; i<cantIteraciones ;i++){//hago 50 iteraciones para despues tomar la mediana
auto start = TIMESTAMP();
p = maximumConConcurrencia(j,10,l);
auto end = TIMESTAMP();
tiempos[i] = chrono::duration_cast<chrono::GRANULARIDAD>(end - start) ;
}
std::sort(tiempos.begin(), tiempos.end());//ordeno para saber la mediana
if(tiempos.size() % 2)
myfile << (tiempos.at(tiempos.size()/2).count() + tiempos.at(tiempos.size()/2 + 1).count()) / 2 << ";\n";//pongo la mediana de maximoSinConcurrencia con p_archivos = j
else
myfile << tiempos.at(tiempos.size()/2 + 1).count() << ";\n";
}
}
int main(){
//TiemposExp1(3);
//TiemposExp2(20);// MIDE CON 10 ARCHIVOS DEL MISMO TAMAÑO
//TiemposExp3(25);
TiemposExp4(5);
return 0;
}
| true |
dad0c0ead7711df82d4d8cc47c33b37a5277045e | C++ | Ratstail91/Emblem-of-the-Lions | /Emblem of the Lions/region.cpp | UTF-8 | 3,318 | 3.34375 | 3 | [
"Zlib"
] | permissive | #include "region.h"
#include <stdexcept>
#include <fstream>
Region::Region() {
indexX = indexY = 0;
width = height = depth = size = 0;
data = NULL;
}
Region::~Region() {
Unload();
}
void Region::Load(const char* fname) {
if (data != NULL)
Unload();
std::ifstream is(fname);
if (!is.is_open())
throw(std::runtime_error("Failed to load region data"));
//load the format data
is >> width;
is >> height;
is >> depth;
size = width * height * depth;
if (size == 0) {
is.close();
throw(std::runtime_error("No region data to load or region format is corrupted"));
}
New(width, height, depth);
//NOTE, TODO: This is probably a temporary format
//load the raw data
Region::iterator it = Begin();
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
for (int k = 0; k < depth; k++) {
it->x = i;
it->y = j;
it->z = k;
is >> it->val;
it++;
}
}
}
is.close();
}
void Region::Save(const char* fname) {
if (data == NULL)
throw(std::logic_error("No region data to save"));
std::ofstream os(fname);
if (!os.is_open())
throw(std::runtime_error("Failed to save region data"));
//save the format data
os << width << " " << height << " " << depth << std::endl;
//save the raw data
Region::iterator it = Begin();
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
for (int k = 0; k < depth; k++) {
os << it->val << " ";
it++;
}
os << "\t";
}
os << std::endl;
}
os.close();
}
void Region::New(int x, int y, int z) {
if (data != NULL)
Unload();
width = x;
height = y;
depth = z;
size = width * height * depth;
data = new Tile[size];
/* //DEBUG: test data
int i = 0;
for (Tile::iterator it = Begin(); it != End(); it++, i++) {
it->val = i;
}*/
}
void Region::Unload() {
delete[] data;
width = height = depth = size = 0;
data = NULL;
}
Tile* Region::SetTile(int x, int y, int z, int v) {
if (data == NULL)
throw(std::logic_error("No region data to set"));
//range is 0 to x - 1 inclusive, where x is the specified dimension
if (x >= width || y >= height || z >= depth || x < 0 || y < 0 || z < 0)
throw(std::out_of_range("Specified tile index is out of range"));
//NOTE: data is stored as though it were data[x][y][z]
int pos = (x * height * depth) + (y * depth) + z;
(data + pos)->val = v;
return data + pos;
}
Tile* Region::GetTile(int x, int y, int z) {
if (data == NULL)
throw(std::logic_error("No region data to retrieve"));
//range is 0 to x - 1 inclusive, where x is the specified dimension
if (x >= width || y >= height || z >= depth || x < 0 || y < 0 || z < 0)
throw(std::out_of_range("Specified tile index is out of range"));
//NOTE: data is stored as though it were data[x][y][z]
return data + (x * height * depth) + (y * depth) + z;
}
int Region::GetWidth() const {
return width;
}
int Region::GetHeight() const {
return height;
}
int Region::GetDepth() const {
return depth;
}
int Region::GetSize() const {
return size;
}
int Region::SetIndexX(int x) {
return indexX = x;
}
int Region::SetIndexY(int y) {
return indexY = y;
}
int Region::GetIndexX() const {
return indexX;
}
int Region::GetIndexY() const {
return indexY;
}
Tile* Region::Begin() const {
return data;
}
Tile* Region::End() const {
return data + size;
}
| true |
8a035fc467e482704a24c24e876a00ca0d3150b1 | C++ | MikeNkunku/Student-Recorder | /Student_Recorder/CursusManager.cpp | UTF-8 | 2,175 | 3.21875 | 3 | [] | no_license | /**
* \file CursusManager.cpp
* \brief Définition des méthodes non-inline de la classe CursusManager
* \author Hugo ROBINE-LANGLOIS
* \author Olympio BARTHELEMY
* \author Mickaël NKUNKU
* \version 1.0
* \date 10 juin 2014
*/
#include "CursusManager.h"
#include "UTProfiler.h"
/**
* @brief Constructeur de la classe.
*/
CursusManager::CursusManager(){}
/**
* @brief Initialisation de l'instance unique à 0 (Pointeur NULL).
*/
CursusManager* CursusManager::singleInstance = 0;
/**
* @return Une référence sur l'instance unique, après création si elle n'existait pas au préalable.
*/
CursusManager& CursusManager::giveInstance(){
if (!singleInstance) {
singleInstance = new CursusManager;
}
return *singleInstance;
}
/**
* @brief Suppression de l'instance unique de la classe CursusManager, qui pointe alors comme initialement sur le pointeur NULL.
*/
void CursusManager::freeInstance(){
if (singleInstance) {
delete singleInstance;
}
singleInstance = 0;
}
/**
* @brief Destructeur de la classe.
*/
CursusManager::~CursusManager(){}
/**
* @brief Ajout d'un cursus à la liste des cursus déjà suivis.
* @param code Code du cursus (ex : Génie Informatique -> GI).
* @param name Nom complet du cursus (ex : GI -> Génie Informatique).
*/
void CursusManager::addCursus(QString code, QString name){
CursusManager::l_cursus.push_back(Cursus(code, name));
}
/**
* @param code Code du cursus
* @return Le cursus s'il existe, sinon déclenche une exception.
*/
Cursus CursusManager::getCursus(QString code){
QList<Cursus>::iterator it;
for (it = l_cursus.begin(); it != l_cursus.end() && (*it).getCode() != code; ++it);
if (it != l_cursus.end()){
return *it;
}
throw UTProfilerException("Le cursus recherché n'existe pas !\n");
// À modifier IMPÉRATIVEMENT (faire un try catch)
}
/**
* @brief Suppression d'un cursus.
* @param code Code du cursus.
*/
void CursusManager::deleteCursus(QString code){
QList<Cursus>::iterator it;
for (it = l_cursus.begin(); it != l_cursus.end() && (*it).getCode() != code; ++it);
if (it != l_cursus.end()){
l_cursus.erase(it);
}
}
| true |
a61d31e89628d94e1854c9058e5fa998116366c3 | C++ | ashishc534/Codeforces | /The New Year Meeting Friends.cpp | UTF-8 | 327 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a[3]={0};
cin>>a[0]>>a[1]>>a[2];
sort(a,a+3);
int min1 = max(a[1],a[2]);
int point = min(max(a[0],a[1]),min1);
int totalDistance = (abs(a[0]-point)+abs(a[1]-point)+abs(a[2]-point));
cout<<totalDistance<<endl;
return 0;
}
| true |
b2ab3f59cab7b8565dc528187f820061c955293f | C++ | salaj/MG | /Motyl/TreeItem.h | UTF-8 | 685 | 2.609375 | 3 | [] | no_license | #pragma once
#include <windows.h>
#include <string>
enum ItemType{
ItemPoint,
ItemCurve,
ItemC2Curve,
ItemC2Interpolated,
ItemTorus,
ItemRoot,
ItemPatch,
ItemBSplinePatch,
ItemBezierSurface,
ItemBSplineSurface,
ItemGregorySurface,
ItemGregoryPatch,
ItemIntersectionCurve
};
enum Origin{
Genuine,
Copy
};
struct TreeItem
{
std::wstring text;
HTREEITEM handle;
HTREEITEM parentHandle;
HTREEITEM previousHandle;
int imageIndex;
int selectedImageIndex;
int id;
ItemType type;
Origin origin;
// init all members
TreeItem::TreeItem() : handle(0), parentHandle(0), previousHandle(0), imageIndex(0), selectedImageIndex(0), id(-1) {}
};
| true |
a71e08b7cc7b0df4ea61ef4ac0e63a9d07ffd543 | C++ | dongdong-2009/uukit | /learnLibev/test.cpp | UTF-8 | 662 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <ev.h>
ev_io stdin_watcher;
ev_timer timeout_watcher;
static void
stdin_cb(EV_P_ ev_io *w, int revents)
{
puts("stdin ready");
ev_io_stop(EV_A_ w);
ev_break(EV_A_ EVBREAK_ALL);
}
static void
timeout_cb(EV_P_ ev_timer *w, int revnts)
{
puts("time out");
ev_break(EV_A_ EVBREAK_ONE);
}
int
main(void)
{
struct ev_loop *loop = EV_DEFAULT;
ev_io_init(&stdin_watcher, stdin_cb, 0, EV_READ);
ev_io_start(loop, &stdin_watcher);
ev_timer_init(&timeout_watcher, timeout_cb, 10, 0);
ev_timer_start(loop, &timeout_watcher);
ev_run(loop, 0);
return 0;
} | true |
4f5f93ed4204f6b08ec48adc39d18b9709aab95d | C++ | luisito1295/CPP | /P6_05.cpp | UTF-8 | 1,385 | 3.40625 | 3 | [] | no_license | /*Nombre: Lopez Mendoza Luis Fernando
Grupo: 1 D ISC
Fecha: 03/10/15
Descripcion: solicitar un numero del 1 al 10 y mostrarlo en letra
*/
#include <stdio.h>
#include <conio.h>
#include <string>
using namespace std;
int num;
void letra(int numero);
main()
{
//clrscr();
printf("se mostrara en letra un numero del 1 al 10");
printf("\ningrese numero (1-10)");
scanf("%d",&num);
letra(num);
printf("\npresiona una tecla para finalizar....");
getchar();
getchar();
}
//*************** funciones
void letra(int numero)
{
string text;
{
if (num==1)
{
printf("uno");
}
if (num==2)
{
printf("Dos");
}
if (num==3)
{
printf("Tres");
}
if (num==4)
{
printf("Cuatro");
}
if (num==5)
{
printf("Cinco");
}
if (num==6)
{
printf("Seis");
}
if (num==7)
{
printf("Siete");
}
if (num==8)
{
printf("Ocho");
}
if (num==9)
{
printf("Nueve");
}
if (num==10)
{
printf("Diez");
}
}
printf("\n%d",text);
return;
}
| true |
5609510ce2526c2ffece3bae0e9627d8e0146168 | C++ | rbmauric/Triple-X | /Triple X/main.cpp | UTF-8 | 1,798 | 3.53125 | 4 | [] | no_license | //Ryan Mauricio
//Triple X
//11/23/19
#include <iostream>
#include <ctime>
const int MAX = 9;
const int TRIES = 3;
bool CheckArr(int* Arr, int N) {
int Guess;
int GuessNum = N + 1;
std::cout << "\n Enter guess " << ": ";
std::cin >> Guess;
if (N == 2) {
std::cout << " Correct. Lock has been picked.\n";
std::cin.clear();
std::cin.ignore();
return true;
}
if (Guess == Arr[N]) {
std::cout << " Correct.";
std::cin.clear();
std::cin.ignore();
return CheckArr(Arr, N + 1);
}
else {
std::cout << " Incorrect. \n";
std::cin.clear();
std::cin.ignore();
return false;
}
}
int Game(int Dif, int LockNum) {
srand(time(NULL));
if (LockNum == MAX)
std::cout << "You have reached the final vault. \n";
else
std::cout << "\n\n\tSTARTING LOCKNUM: " << LockNum + 1 << std::endl;
const int Num1 = (rand() % Dif + Dif);
const int Num2 = (rand() % Dif + Dif);
const int Num3 = (rand() % Dif + Dif);
int arr[3] = { Num1, Num2, Num3 };
std::cout << " \tHint: the numbers add to " << (Num1 + Num2 + Num3) << "\n";
std::cout << " \tHint: the numbers multiply to " << (Num1 * Num2 * Num3) << "\n";
for (int i = 0; i < TRIES; i++) {
if (CheckArr(arr, 0) == true)
return Game(Dif + 1, LockNum + 1);
else
std::cout << "\n " << "Tries left: " << (TRIES - i - 1) << "\n";
}
std::cout << "\tOUT OF TRIES. THE POLICE ARE ON THEIR WAY. \n";
return false;
}
int main() {
int Difficulty = 2;
std::cout << "WELCOME TO LOCKPICKER! \n YOU'RE MISSION: BREAK ALL THE LOCKS AND GET THE MONEY AT THE FINAL VAULT. \n";
std::cout << " Each lock has 3 possible numbers. You only have three tries before the police are alerted!\n";
if (Game(Difficulty, 0) == true)
std::cout << "CONGRATULATIONS. YOU HAVE BROKEN THE FINAL VAULT. YOU WIN!";
return 0;
} | true |
7f1c72bb2a186fbce70d29b8ce3564a5f01b7367 | C++ | peterprokop/Allocators | /Allocators/allocators.cpp | UTF-8 | 853 | 2.953125 | 3 | [] | no_license | //
// allocators.cpp
// Allocators
//
// Created by Peter Prokop on 22/10/15.
// Copyright © 2015 Peter Prokop. All rights reserved.
//
#include "allocators.hpp"
template <class P, class F>
AllocatorBlock FallbackAllocator<P, F>::allocate(size_t n) {
AllocatorBlock r = P::allocate(n);
if (!r.ptr) {
r = F::allocate(n);
}
return r;
}
template <class P, class F>
void FallbackAllocator<P, F>::deallocate(AllocatorBlock b) {
if (P::owns(b)) {
P::deallocate(b);
} else {
F::deallocate(b);
}
}
template <class P, class F>
bool FallbackAllocator<P, F>::owns(AllocatorBlock b) {
return P::owns(b) || F::owns(b);
}
size_t roundToAligned(size_t n) {
auto floor = (n / ALIGN_SIZE) * ALIGN_SIZE;
if (floor == n) {
return floor;
} else {
return floor + ALIGN_SIZE;
}
} | true |
9dd85ea17f0451bf360dc41af46fd84b8e99047b | C++ | zjsxzy/algo | /Hdoj/WHU/1003.cpp | UTF-8 | 1,719 | 2.515625 | 3 | [] | no_license | /*
* Author : Yang Zhang
*/
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define abs(x) ((x) > 0 ? (x) : -(x))
typedef long long LL;
const int maxn = 270005;
struct Node {
int l, r, sum;
}T[maxn << 2];
inline int lson(int rt)
{
return rt << 1;
}
inline int rson(int rt)
{
return rt << 1 | 1;
}
void pushUp(int rt)
{
T[rt].sum = T[lson(rt)].sum + T[rson(rt)].sum;
}
void build(int l, int r, int rt)
{
T[rt].l = l, T[rt].r = r;
if (l == r) {
T[rt].sum = 1;
return;
}
int mid = (l + r) >> 1;
build(l, mid, lson(rt));
build(mid + 1, r, rson(rt));
pushUp(rt);
}
void update(int p, int rt, int c)
{
if (T[rt].l == T[rt].r) {
T[rt].sum += c;
return;
}
int mid = (T[rt].l + T[rt].r) >> 1;
if (p <= mid) update(p, lson(rt), c);
else update(p, rson(rt), c);
pushUp(rt);
}
int query(int k, int rt)
{
if (T[rt].l == T[rt].r) {
return T[rt].l;
}
int mid = (T[rt].l + T[rt].r) >> 1;
if (k <= T[lson(rt)].sum) return query(k, lson(rt));
else return query(k - T[lson(rt)].sum, rson(rt));
}
int N, K;
int main() {
freopen("in", "r", stdin);
int Test;
scanf("%d", &Test);
for (int cas = 1; cas <= Test; cas++) {
printf("Case %d: ", cas);
scanf("%d%d", &N, &K);
build(1, N, 1);
LL ret = 0;
for (int i = 0; i < K; i++) {
int x;
scanf("%d", &x);
int tmp = query(x, 1);
ret += (long long)tmp;
update(tmp, 1, -1);
}
cout << ret << endl;
}
return 0;
}
| true |
d1b7592457b0e460cd48357c3ac14bfa9c4c7d8d | C++ | LITturtlee/Programming-Practice | /PAT/乙级/1027.cpp | UTF-8 | 625 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
char sign;
int N,biggest=1,i=1,level=1;
cin >> N >> sign;
while(biggest<=N){
i += 2;
level++;
biggest += i*2;
}
biggest = biggest - i*2;
i -= 2;
level --;
int emp;
for(int j=0;j<level*2-1;j++){
if(j<level){
emp =j;
}
else{
emp =level*2-2-j;
}
for(int m=0;m<emp;m++){
cout<<" ";
}
for(int m=0;m<i-2*emp;m++){
cout<<sign;
}
cout<<endl;
}
cout << N - biggest<<endl;
return 0;
} | true |
9562df7bac961256672a53c1f517b2738a7e87af | C++ | NicholasArnaud/Intro_To_Programming | /Operator Overloading Exercise/Operator Overloading Exercise/Source.cpp | WINDOWS-1252 | 1,169 | 3.53125 | 4 | [] | no_license | #include <iostream>
#include "PositionClass.h"
/*
Create a Position class. This should have a definition in a .h file and function bodies in a .cpp
file. It should contain the following:
a. Floats for x and y (they should be private)
b. Default constructor and a constructor which allows x and y to be initialized when the
class is instantiated
c. Interface functions to read x and y
*/
/*
Add a function which overloads the + and -operator. This allows us to conveniently add
positions and velocities together instead of needing to add the X and the Y values separately.
*/
/*
Add a function which overload the += and -= operator (you should be able to reuse the +
and functions you created earlier).
*/
/*
Overload the equivalence operator so that two Position objects can easily be compared
*/
/*
Overload the other operators in ways which you think are appropriate (be careful here, its
easy to get carried away. Remember that the whole point of operator overloading is to make
the code easier to understand!)
*/
/*
There are two minus operators to overload. Why? Overload them both.
*/
int main()
{
return 1;
} | true |
a06d775eef45c554cbd4b2389fc376087ba58e4c | C++ | WhiZTiM/coliru | /Archive2/ce/0310e457326b8b/main.cpp | UTF-8 | 668 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
// If you want to insert in the front instead, use std::deque
typedef std::vector<unsigned char> BytesContainer;
static void InsertMaskedBytes(BytesContainer& bytes, unsigned digest_value)
{
for (unsigned i = 0; i < 4; ++i)
{
unsigned mask = 0xFF000000 >> (i*8);
bytes.push_back(digest_value & mask);
}
}
int main() {
unsigned const digest_size = 5;
unsigned digest[digest_size] = {};
BytesContainer bytes;
std::for_each(
digest,
digest + digest_size,
boost::bind(&InsertMaskedBytes, boost::ref(bytes), _1)
);
return 0;
} | true |
ca84fffe3171db1bf77130c0459b19fb474ce28f | C++ | FahimCC/Problem-Solving | /Codeforces/A. Anton and Polyhedrons.cpp | UTF-8 | 382 | 3.21875 | 3 | [] | no_license | #include<iostream>
#include<map>
using namespace std;
int main()
{
map<string, int> m;
m["Tetrahedron"] = 4;
m["Cube"] = 6;
m["Octahedron"] = 8;
m["Dodecahedron"] = 12;
m["Icosahedron"] = 20;
string x;
int test, sum = 0;
cin>>test;
while(test--)
{
cin>>x;
sum = sum + m[x];
}
cout<<sum<<endl;
return 0;
}
| true |
5c483979ec6698c4a8b011741a531bc79b50ebbc | C++ | xchrdw/voxellancer | /src/display/rendering/rendermetadata.h | UTF-8 | 321 | 2.53125 | 3 | [] | no_license | #pragma once
#include "display/eyeside.h"
class Camera;
// metadata that is passed to a renderpass
class RenderMetaData {
public:
RenderMetaData(const Camera& camera, EyeSide eyeside);
const Camera& camera() const;
EyeSide eyeside() const;
private:
const Camera& m_camera;
EyeSide m_eyeside;
};
| true |
8a564b18ac85bd1cbb1faae39b39283b272c8d7a | C++ | RunOnceEx/Athena | /Athena/Injector.cpp | UTF-8 | 1,815 | 2.78125 | 3 | [] | no_license | #include "Injector.h"
void Injector::MapLocalSection(HANDLE& sectionHandle, ntdll* nt, PVOID& localSectionAddress, SIZE_T size) {
LARGE_INTEGER sectionSize = { size };
// create a memory section
nt->fNtCreateSection(§ionHandle, SECTION_MAP_READ | SECTION_MAP_WRITE | SECTION_MAP_EXECUTE, NULL, (PLARGE_INTEGER)§ionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NULL);
std::cout << " [+] sectionHandle -> " << sectionHandle << std::endl;
std::cout << " [+] size -> " << size << std::endl;
// create a view of the memory section in the local process
nt->fNtMapViewOfSection(sectionHandle, GetCurrentProcess(), &localSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_READWRITE);
std::cout << " [+] localSectionAddress -> " << localSectionAddress << std::endl;
}
void Injector::MapRemoteSection(HANDLE& sectionHandle, HANDLE& targetHandle, ntdll* nt, PVOID& remoteSectionAddress, SIZE_T size) {
nt->fNtMapViewOfSection(sectionHandle, targetHandle, &remoteSectionAddress, NULL, NULL, NULL, &size, 2, NULL, PAGE_EXECUTE_READ);
std::cout << " [+] targetHandle -> " << targetHandle << std::endl;
std::cout << " [+] remoteSectionAddress -> " << remoteSectionAddress << std::endl;
}
void Injector::StartThread(HANDLE& targetHandle, PVOID& remoteSectionAddress, ntdll* nt) {
HANDLE targetThreadHandle = NULL;
nt->fNtCreateThreadEx(&targetThreadHandle, 0x1FFFFF, NULL, targetHandle, remoteSectionAddress, NULL, true, 0, 0xffff, 0xffff, NULL);
std::cout << " [+] NtCreateThreadEx" << std::endl;
nt->fNtQueueApcThread(targetThreadHandle, remoteSectionAddress, 0, 0, 0);
std::cout << " [+] NtQueueApcThread" << std::endl;
PULONG pSuspendLong = 0;
nt->fNtAlertResumeThread(targetThreadHandle, pSuspendLong);
std::cout << " [+] NtAlertResumeThread" << std::endl;
} | true |
fb6f83f31927e861995d5486dcaab6f2c38e473f | C++ | evrenkaya/CrazyEights | /CrazyEights/Player.h | UTF-8 | 683 | 2.96875 | 3 | [
"MIT"
] | permissive | #ifndef PLAYER_H
#define PLAYER_H
#include "Deck.h"
#include "IOManager.h"
class Player
{
public:
Player(IOManager*, std::string);
virtual ~Player();
explicit Player(const Player&);
void addCard(Card*);
Card* removeCard(int);
Card* getCard(int) const;
int getNumCards() const;
void addScore(unsigned int);
int getScore() const;
std::string getName() const;
bool validCard(const Card*, const Card*);
const Deck& getHand() const;
virtual Card* playTurn(const Card*) = 0;
protected:
Deck mHand;
IOManager* mIOManager;
int mScore;
std::string mName;
};
#endif | true |
b3ce00457c2b6f5e64fe416aca5926603adff750 | C++ | mountither/vscode-remote-cpp | /iai-tute-tasks/t2-agent-program/vacuum-env.cpp | UTF-8 | 674 | 2.75 | 3 | [] | no_license | #include "coordinates.cpp"
#include <iostream>
using namespace std;
class VacuumEnv
{
private:
Coordinates fLocation;
string fFloor[4][6];
public:
VacuumEnv(string aFloor[4][6], Coordinates aLocation){
fLocation = aLocation;
fFloor = aFloor;
}
int measurePerformance(){
}
void updateLocation(Coordinates aNewLocation){
fLocation = aNewLocation;
}
Coordinates getVacuumLocation(){
return fLocation;
}
string[][] getStatusAtLocation(){
return fFloor[fLocation.getX()][fLocation.getY()];
}
}; | true |
3ac23965222e63d018f250b0a8b71693b8ec4344 | C++ | joycodex/listparser | /libs/lexer/src/char_stream.cpp | UTF-8 | 407 | 2.96875 | 3 | [] | no_license | #include "lexer/char_stream.h"
#include <cassert>
CharStream::CharStream(const std::string &input)
: input_(input)
{
if (input_.size() > 0) {
p_ = 0;
ch_ = input[0];
}
}
char CharStream::peak()
{
return ch_;
}
void CharStream::consume()
{
assert(ch_ != EOF);
p_++;
if (p_ >= input_.size()) {
ch_ = EOF;
} else {
ch_ = input_[p_];
}
}
| true |
9cef9baf4c9402c2c529918f22bcdd434eaf2118 | C++ | nanami809/TobaccoLeafStudio | /TobaccoLeafStudio/GetImages.cpp | GB18030 | 18,117 | 2.765625 | 3 | [] | no_license | #include"Header.h"
//ͼԤ
/*
//ͼƽ
Mat img_blur_R,img_blur_T;
//img_R.copyTo(img_blur_R); img_T.copyTo(img_blur_T);
BlurImage(img_R, img_T, img_blur_R, img_blur_T);
//ɫУ
Mat img_cor_R, img_cor_T;
//img_blur_R.copyTo(img_cor_R); img_blur_T.copyTo(img_cor_T);
Rect recwindow(680, 415, 130, 100);//Ԥװֵλ
ColorCorect(recwindow, img_blur_R, img_blur_T, img_cor_R, img_cor_T);
//ͼָ
Mat img_seg_R, img_seg_T;
SegmentationImage(img_cor_R, img_cor_T,img_seg_R,img_seg_T);
//Ѱװ崦
Mat white(recwindow.size(), CV_8UC3, Scalar(255, 255, 255));
Mat black(recwindow.size(), CV_8UC3, Scalar(0, 0, 0));
white.copyTo(img_seg_R(recwindow));
black.copyTo(img_seg_T(recwindow));
*/
//ͼƽ
void BlurImage(Mat &r, Mat &t, Mat &dst_r, Mat &dst_t){
bilateralFilter(r, dst_r, 15, 15 * 2, 15 / 2);//˫˲
bilateralFilter(t, dst_t, 15, 15 * 2, 15 / 2);
}
//ɫУ
void ColorCorect(Rect window, Mat &r, Mat &t, Mat &dst_r, Mat &dst_t){
r.copyTo(dst_r);
t.copyTo(dst_t);
Mat mask;//Ĥ
Mat bgModel, fgModel;//ʱΪ㷨мʹãcare
double tt = getTickCount();
// GrabCut ֶ
cv::grabCut(r, //ͼ
mask, //ֶν
window,// ǰľ
bgModel, fgModel, // ǰ
1, //
cv::GC_INIT_WITH_RECT); // þ
compare(mask, cv::GC_PR_FGD, mask, cv::CMP_EQ);// ʾװ
Mat element = getStructuringElement(MORPH_RECT, Size(9, 9));
erode(mask, mask, element);//ʴ㷨
Rect box = boundingRect(mask);//Ӿα߽
/*
//ƺ
line(img_blur_R, Point(box.x, box.y), Point(box.x + box.width, box.y), Scalar(0, 0, 255), 3);
line(img_blur_R, Point(box.x, box.y), Point(box.x, box.y + box.height), Scalar(0, 0, 255), 3);
line(img_blur_R, Point(box.x + box.width, box.y), Point(box.x + box.width, box.y + box.height), Scalar(0, 0, 255), 3);
line(img_blur_R, Point(box.x, box.y + box.height), Point(box.x + box.width, box.y + box.height), Scalar(0, 0, 255), 3);
*/
//װ塢ڰڷDZµɫ
Mat board_w = dst_r(Rect(box.x + 5, box.y + 5, box.width - 10, box.height - 10));
Mat board_b = dst_t(Rect(box.x + 5, box.y + 5, box.width - 10, box.height - 10));
double sum[3] = { 0, 0, 0 };
do{
Scalar w_rgb = mean(board_w);
for (int i = 0; i < r.rows; i++){
for (int j = 0; j < r.cols; j++){
for (int k = 0; k <= 2; k++){
//װУ
int temp1 = 255 * r.at<Vec3b>(i, j)[k] / w_rgb[k];
if (temp1 > 255) dst_r.at<Vec3b>(i, j)[k] = 255;
else dst_r.at<Vec3b>(i, j)[k] = temp1;
}
}
}
for (int k = 0; k <= 2; k++){
for (int i = 0; i < board_w.rows; i++){
for (int j = 0; j < board_w.cols; j++){
int temp1 = board_w.at<Vec3b>(i, j)[k];
int temp2 = abs(255 - temp1);
sum[k] += temp2 / temp1;
}
}
sum[k] = sum[k] / (board_w.rows*board_w.cols);
}
} while (sum[0] > 0.01 || sum[1] > 0.01 || sum[2] > 0.01);//װУЧ
sum[0] = 0; sum[1] = 0; sum[2] = 0;
do{
Scalar b_rgb = mean(board_b);
for (int i = 0; i < r.rows; i++){
for (int j = 0; j < r.cols; j++){
for (int k = 0; k <= 2; k++){
//ڰУ
int temp2 = 255 - (255 - t.at<Vec3b>(i, j)[k]) * 255 / (255 - b_rgb[k]);
if (temp2 <0) dst_t.at<Vec3b>(i, j)[k] = 0;
else dst_t.at<Vec3b>(i, j)[k] = temp2;
}
}
}
for (int k = 0; k <= 2; k++){
for (int i = 0; i < board_b.rows; i++){
for (int j = 0; j < board_b.cols; j++){
int temp1 = board_b.at<Vec3b>(i, j)[k];
int temp2 = abs(0 - temp1);
sum[k] += temp2 / (255 - temp1);
}
}
sum[k] = sum[k] / (board_b.rows*board_b.cols);
}
} while (sum[0] > 0.01 || sum[1] > 0.01 || sum[2] > 0.01);//ڰУЧ
}
//ͼָ(ķ
void SegmentationImage(Mat &r, Mat &t, Mat &dst_r, Mat &dst_t){
//ͼƬ
Mat img_R;
Mat img_T;
r.copyTo(img_R);
t.copyTo(img_T);
//ͼľ
Mat D_redblue(r.rows, r.cols, CV_8UC1);
for (int i = 0; i < t.rows; i++){
for (int j = 0; j < t.cols; j++){
Scalar temp = r.at<Vec3b>(i, j);
if (temp[2] - temp[0]<0)D_redblue.at<uchar>(i, j) = 0;
else D_redblue.at<uchar>(i, j) = (uchar)(temp[2] - temp[0]);
}
}
int t_DRB = Getthreshold_Gray(D_redblue);
//¼Եľ
Mat img_Counter1(Size(t.cols, t.rows), CV_8UC3, Scalar(0, 0, 0));
Mat img_Counter2(Size(t.cols, t.rows), CV_8UC3, Scalar(255, 255, 255));//¼Ե
//ֵͱϵֲ
Mat mean_img(Size(img_T.cols - 2, img_T.rows - 2), CV_8UC1);
Mat cv_img(Size(img_T.cols - 2, img_T.rows - 2), CV_8UC1);
vector<Mat> channels_T;
split(t, channels_T);//ͼɫֵ
for (int i = 0; i < t.rows - 2; i++){
for (int j = 0; j < t.cols - 2; j++){
Mat rect_Blue_T = channels_T[0](Rect(Point(j, i), Point(j + 3, i + 3)));//33
Mat mean_Mat, std_Mat;
meanStdDev(rect_Blue_T, mean_Mat, std_Mat);
double mean_rect = mean_Mat.at<double>(0, 0);
double std_rect = std_Mat.at<double>(0, 0);
mean_img.at<uchar>(i, j) = (uchar)mean_rect;
if (mean_rect != 0){
cv_img.at<uchar>(i, j) = (uchar)(std_rect / mean_rect / 3 * 255);
}
else cv_img.at<uchar>(i, j) = 0;
}
}
int t_mean = Getthreshold_Gray(mean_img);//ͨͼ
threshold(mean_img, mean_img, t_mean, 255, CV_THRESH_BINARY);//ƽֵָʾҶ
int t_cv = threshold(cv_img, cv_img, 0, 255, CV_THRESH_OTSU);//ϵָʾԵ
Mat white(3, 3, CV_8UC3, Scalar(255, 255, 255));
Mat black(3, 3, CV_8UC3, Scalar(0, 0, 0));
for (int i = 0; i < mean_img.rows; i++){
for (int j = 0; j < mean_img.cols; j++){
Rect window = Rect(Point(j, i), Point(j + 3, i + 3));//33Сڵɨ
if (mean_img.at<uchar>(i, j) == 0){
//Ҷ
Scalar temp = mean(r(window));
int blue = temp[0];
int red = temp[2];
if (red - blue <= t_DRB){
//ųԵ
white.copyTo(img_R(window));
black.copyTo(img_T(window));
}
}
else{
if (cv_img.at<uchar>(i, j) != 0){
//Ե
t(window).copyTo(img_Counter1(window));
t(window).copyTo(img_Counter2(window));
}
else {
//
white.copyTo(img_R(window));
black.copyTo(img_T(window));
}
}
}
}
vector<Mat> channels_C;
split(img_Counter2, channels_C);
Mat temp = channels_C[0];
int t_C = Getthreshold_Gray(temp);
//int t_C = threshold(temp, temp, 0, 255, CV_THRESH_OTSU);
threshold(temp, temp, t_C, 255, CV_THRESH_BINARY);
for (int m = 0; m < temp.rows; m++){
for (int n = 0; n < temp.cols; n++){
if (temp.at<uchar>(m, n) == 0) {
//
img_T.at<Vec3b>(m, n) = t.at<Vec3b>(m, n);
img_R.at<Vec3b>(m, n) = r.at<Vec3b>(m, n);
}
}
}
split(img_Counter1, channels_C);
temp = channels_C[0];
threshold(temp, temp, t_C, 255, CV_THRESH_BINARY);
for (int m = 0; m < temp.rows; m++){
for (int n = 0; n < temp.cols; n++){
if (temp.at<uchar>(m, n) != 0) {
//
img_T.at<Vec3b>(m, n) = { 0, 0, 0 };
img_R.at<Vec3b>(m, n) = { 255, 255, 255 };
}
}
}
img_R.copyTo(dst_r);
img_T.copyTo(dst_t);
}
//ͼָ(Ľܣ
/*
void SegmentationImage(Mat &r, Mat &t, Mat &dst_r, Mat &dst_t){
//мͼƬ
//Mat img_R(r.rows, r.cols, CV_8UC3, Scalar(255, 255, 255));
//Mat img_T(t.rows, t.cols, CV_8UC3, Scalar(0, 0, 0));
//ͼľ
//Mat D_redblue(r.rows, r.cols, CV_8UC1);
//for (int i = 0; i < t.rows; i++){
// for (int j = 0; j < t.cols; j++){
// Scalar temp = r.at<Vec3b>(i, j);
// if (temp[2] - temp[0]<0)D_redblue.at<uchar>(i, j) = 0;
// else D_redblue.at<uchar>(i, j) = (uchar)(temp[2] - temp[0]);
// }
//}
//int t_DRB = Getthreshold_Gray(D_redblue);
//¼Եľ
//Mat img_Counter1(Size(t.cols, t.rows), CV_8UC3, Scalar(255,255, 255));
//Mat img_Counter2(Size(t.cols, t.rows), CV_8UC3, Scalar(255, 255, 255));//¼Ե
//ֵͱϵֲ
Mat mean_img(Size(t.cols - 2, t.rows - 2), CV_8UC1);
Mat cv_img(Size(t.cols - 2, t.rows - 2), CV_8UC1);
vector<Mat> channels_T;
split(t, channels_T);//ͼɫֵ
for (int i = 0; i < t.rows - 2; i++){
for (int j = 0; j < t.cols - 2; j++){
Mat rect_Blue_T = channels_T[0](Rect(Point(j, i), Point(j + 3, i + 3)));//33
Mat mean_Mat, std_Mat;
meanStdDev(rect_Blue_T, mean_Mat, std_Mat);
double mean_rect = mean_Mat.at<double>(0, 0);
double std_rect = std_Mat.at<double>(0, 0);
mean_img.at<uchar>(i, j) = (uchar)mean_rect;
if (mean_rect != 0){
cv_img.at<uchar>(i, j) = (uchar)(std_rect / mean_rect / 3 * 255);
}
else cv_img.at<uchar>(i, j) = 0;
}
}
int t_mean = 0; //ȡ0 Getthreshold_Gray(mean_img);//ͨͼ
int t_cv =55; //ȡ10010мֵ threshold(cv_img, cv_img, 0, 255, CV_THRESH_OTSU);//ϵָʾԵ
threshold(mean_img, mean_img, t_mean, 255, CV_THRESH_BINARY);//ƽֵָʾҶ
threshold(cv_img, cv_img, t_cv, 255, CV_THRESH_BINARY);
for (int i = 0; i < mean_img.rows; i++){
for (int j = 0; j < mean_img.cols; j++){
Rect window = Rect(Point(j, i), Point(j + 3, i + 3));//33Сڵɨ
if (mean_img.at<uchar>(i, j) == 0){
//Ҷ
//Scalar temp = mean(r(window));
//int blue = temp[0];
//int red = temp[2];
//if (red - blue>t_DRB)
{
//ųԵ
//r(window).copyTo(img_R(window));
//t(window).copyTo(img_T(window));
}
}
else{
if (cv_img.at<uchar>(i, j) != 0){
//Ե
//t(window).copyTo(img_Counter1(window));
//t(window).copyTo(img_Counter2(window));
//r(window).copyTo(img_R(window));
//t(window).copyTo(img_T(window));
}
else {
// 255 255 255
Mat white(3, 3, CV_8UC3, Scalar( 0,0,255));
white.copyTo(r(window));
white.copyTo(t(window));
}
}
}
}
r.copyTo(dst_r);
t.copyTo(dst_t);
}
*/
//ȡҶֱͼֵͨͼ
int Getthreshold_Gray(Mat &srcImage){
int i;
//2
int hist_size = 256;
float range[] = { 0, 255 };
const float* ranges[] = { range };
MatND redHist, grayHist, blueHist;
/*
//3ֱͼļ㣨ɫ֣
calcHist(&srcImage, 1, channels_r, Mat(), //ʹĤ
redHist, 1, hist_size, ranges,
true, false);
//4ֱͼļ㣨ɫ֣
int channels_g[] = { 1 };
calcHist(&srcImage, 1, channels_g, Mat(), // do not use mask
grayHist, 1, hist_size, ranges,
true, // the histogram is uniform
false);
*/
//5ֱͼļ㣨ɫ֣
int channels_b[] = { 0 };
calcHist(&srcImage, 1, channels_b, Mat(), // do not use mask
blueHist, 1, &hist_size, ranges);
medianBlur(blueHist, blueHist, 3);
//ֵ
double maxValue_blue;
Point maxIdx_blue;
minMaxLoc(blueHist, 0, &maxValue_blue, 0, &maxIdx_blue);
if (maxIdx_blue.y == 0){
for (i = 1; i < 256; i++){
if (blueHist.at<float>(i) > blueHist.at<float>(i - 1)){
break;
}
}
}
else i = 0;
return i - 1;
}
//CVֱͼֵδã
int Getthreshold_CV(Mat &srcImage){
if (srcImage.type() != CV_8UC1)
cvtColor(srcImage, srcImage, CV_RGB2GRAY);
int i;
//2
int hist_size = 51;
float range[] = { 0, 255 };
const float* ranges[] = { range };
MatND redHist, grayHist, blueHist;
/*
//3ֱͼļ㣨ɫ֣
calcHist(&srcImage, 1, channels_r, Mat(), //ʹĤ
redHist, 1, hist_size, ranges,
true, false);
//4ֱͼļ㣨ɫ֣
int channels_g[] = { 1 };
calcHist(&srcImage, 1, channels_g, Mat(), // do not use mask
grayHist, 1, hist_size, ranges,
true, // the histogram is uniform
false);
*/
//5ֱͼļ
int channels_b[] = { 0 };
calcHist(&srcImage, 1, channels_b, Mat(), // do not use mask
blueHist, 1, &hist_size, ranges);
medianBlur(blueHist, blueHist, 3);
Mat temp = (Mat)blueHist;
//ֵ
double maxValue_blue;
Point maxIdx_blue;
minMaxLoc(blueHist, 0, &maxValue_blue, 0, &maxIdx_blue);
if (maxIdx_blue.y == 0){
for (i = 1; i < 300; i++){
if (blueHist.at<float>(i) > blueHist.at<float>(i - 1)){
break;
}
}
}
else i = 0;
return (i - 1) * 5;
}
//ֵδã
int Getthreshold_DieDai(Mat &srcImage, Mat &dst){
Mat gray, temp;
srcImage.copyTo(dst);
if (srcImage.type() != CV_8UC1)
cvtColor(srcImage, gray, CV_RGB2GRAY);
else srcImage.copyTo(gray);
//2
double minval, maxval;
int t, t1, t2, s;
minMaxLoc(gray, &minval, &maxval);
s = (minval + maxval) / 2;
do{
int n1 = 0, n2 = 0, sum1 = 0, sum2 = 0;
t = s;
threshold(gray, temp, t, 255, THRESH_BINARY);
for (int i = 0; i < temp.rows; i++)
{
for (int j = 0; j < temp.cols; j++)
{
if (temp.at<uchar>(i, j) == 0){
n1++;
sum1 += gray.at<uchar>(i, j);
}
else{
n2++;
sum2 += gray.at<uchar>(i, j);
}
}
}
t1 = sum1 / n1;
t2 = sum2 / n2;
s = (t1 + t2) / 2;
} while (s != t);
if (srcImage.type() == CV_8UC3){
// Mat white(3, 3, CV_8UC3, Scalar(255, 255, 255));
for (int i = 0; i < temp.rows; i++)
{
for (int j = 0; j < temp.cols; j++)
{
if (temp.at<uchar>(i, j) == 0){
dst.at<Vec3b>(i, j) = { 255, 255, 255 };
}
else{
}
}
}
}
return t;
}
void RotateLeaf(Mat &r, Mat &t){
Point Left, Right; bool flag = 0;
for (int j = 0; j < r.cols; j++){
if (flag) break;
for (int i = 0; i < r.rows; i++){
if (r.at<Vec3b>(i, j)[0] != 255 || r.at<Vec3b>(i, j)[1] != 255 || r.at<Vec3b>(i, j)[2] != 255){
Left.x = j;
Left.y = i;
flag = 1;
break;
}
}
}
flag = 0;
for (int j = r.cols - 1; j >= 0; j--){
if (flag) break;
for (int i = r.rows - 1; i >= 0; i--){
if (r.at<Vec3b>(i, j)[0] != 255 || r.at<Vec3b>(i, j)[1] != 255 || r.at<Vec3b>(i, j)[2] != 255){
Right.x = j;
Right.y = i;
flag = 1;
break;
}
}
}
double s = (double)(Right.y - Left.y) / (double)(Right.x - Left.x);
double angle = atan(s) * 180 / CV_PI;
Mat temp = getRotationMatrix2D(Left, angle, 1);
Mat dst;
warpAffine(r, r, temp, r.size(), INTER_NEAREST, 0, Scalar(255, 255, 255));
warpAffine(t, t, temp, r.size(), INTER_NEAREST, 0, Scalar(0, 0, 0));
//ƽ
//Point2f middle = Point2f((Left.x + Right.x) / 2, (Left.y + Right.y) / 2);
Point2f srcTriangle[3];
Point2f dstTriangle[3];
srcTriangle[0] = Left;
dstTriangle[0] = Point2f(60, 308);
srcTriangle[1] = Point2f(0, 0);
dstTriangle[1] = Point2f(60 - Left.x, 308 - Left.y);
srcTriangle[2] = Point2f(100, 100);
dstTriangle[2] = Point2f(100 + 60 - Left.x, 100 + 308 - Left.y);
Mat warpMat = getAffineTransform(srcTriangle, dstTriangle);
warpAffine(r, r, warpMat, r.size(), INTER_NEAREST, 0, Scalar(255, 255, 255));
warpAffine(t, t, warpMat, r.size(), INTER_NEAREST, 0, Scalar(0, 0, 0));
}
vector<Point> CutandRotate(Mat &r, Mat &t, Mat &dst_r, Mat &dst_t, Mat &mask){
int cutposition = 0;
Mat w = GetLeafwide(r);
medianBlur(w, w, 5);
vector<double> slopes;
double maxValue;
Point maxIdx;
minMaxLoc(w, 0, &maxValue, 0, &maxIdx);
for (int i = maxIdx.x + 20; i <r.cols; i++){
double temp = ((double)w.at<ushort>(0, i - 20) - (double)w.at<ushort>(0, i)) / 20;
slopes.push_back(temp);
}
for (int i = r.cols - 1; i >= 0; i--){
int s = i - (r.cols - slopes.size());
if (s >= 0 && w.at<ushort>(0, i) < 20 && slopes[s]< 1){
Mat white(Size(r.cols - i, r.rows), CV_8UC3, Scalar(255, 255, 255));
Mat black(Size(r.cols - i, r.rows), CV_8UC3, Scalar(0, 0, 0));
Rect window = Rect(Point(i, 0), Point(r.cols, r.rows));
white.copyTo(r(window));
black.copyTo(t(window));
}
else if (s < 0) break;
}
RotateLeaf(r, t);
r.copyTo(dst_r);
t.copyTo(dst_t);
vector<Point> points;
for (int i = 0; i < r.rows; i++){
for (int j = 0; j < r.cols; j++){
if (r.at<Vec3b>(i, j)[0] == 255 && r.at<Vec3b>(i, j)[1] == 255 && r.at<Vec3b>(i, j)[2] == 255){
mask.at<uchar>(i, j) = 0;
}
else {
points.push_back(Point(j, i));
mask.at<uchar>(i, j) = 255;
}
}
}
return points;
}
//ȫֻҶͼԱҪ
/*
Mat temp;
cvtColor(img_cor_R, temp, CV_RGB2GRAY);
int t = Getthreshold_DieDai(temp, temp);
threshold(temp, temp, t, 255, THRESH_BINARY);
for (int i = 0; i < temp.rows; i++)
{
for (int j = 0; j < temp.cols; j++)
{
if (temp.at<uchar>(i, j) == 0){
img_cor_R.at<Vec3b>(i, j) = {255, 255, 255};
}
else{
}
}
}
*/
//-----------------------Ƴɫֱͼ------------------------
/*
//
double maxValue_red, maxValue_green, maxValue_blue;
minMaxLoc(redHist, 0, &maxValue_red, 0, 0);
minMaxLoc(grayHist, 0, &maxValue_green, 0, 0);
minMaxLoc(blueHist, 0, &maxValue_blue, 0, 0);
int scale = 1;
int histHeight = 256;
Mat histImage = Mat::zeros(histHeight, bins * 3, CV_8UC3);
//ʽʼ
for (int i = 0; i<bins; i++)
{
//
float binValue_red = redHist.at<float>(i);
float binValue_green = grayHist.at<float>(i);
float binValue_blue = blueHist.at<float>(i);
int intensity_red = cvRound(binValue_red*histHeight / maxValue_red); //ҪƵĸ߶
int intensity_green = cvRound(binValue_green*histHeight / maxValue_green); //ҪƵĸ߶
int intensity_blue = cvRound(binValue_blue*histHeight / maxValue_blue); //ҪƵĸ߶
//ƺɫֱͼ
rectangle(histImage, Point(i*scale, histHeight - 1),
Point((i + 1)*scale - 1, histHeight - intensity_red),
Scalar(255, 0, 0));
//ɫֱͼ
rectangle(histImage, Point((i + bins)*scale, histHeight - 1),
Point((i + bins + 1)*scale - 1, histHeight - intensity_green),
Scalar(0, 255, 0));
//ɫֱͼ
rectangle(histImage, Point((i + bins * 2)*scale, histHeight - 1),
Point((i + bins * 2 + 1)*scale - 1, histHeight - intensity_blue),
Scalar(0, 0, 255));
}
//ڴʾƺõֱͼ
imshow("ͼRGBֱͼ", histImage);
waitKey(0);
*/
| true |
73f6fd4e480687b2e1636dddeba99a3b2e47cd32 | C++ | evanchang2399/UtPod | /Song.cpp | UTF-8 | 1,799 | 3.671875 | 4 | [] | no_license | //
// Created by Evan Chang on 2019-03-28.
//
#include "Song.h"
using namespace std;
//Default constructor
Song::Song() {
title = "";
artist = "";
size = 0;
}
//Constructor with all variables
Song::Song(string artist, string title, int size) {
this->title = title;
this->artist = artist;
this->size = size;
}
//Next three methods are all basic getters
string Song::getTitle() const{
return title;
}
string Song::getArtist() const{
return artist;
}
int Song::getSize() const{
return size;
}
//Next three methods are all setters
void Song::setTitle(string newTitle){
title = newTitle;
}
void Song::setArtist(string newArtist) {
artist = newArtist;
}
void Song::setSize(int newSize){
size = newSize;
}
//Overridden == method for Songs
bool Song::operator ==(Song const &other){
if(title != other.title){
return false;
}
if(artist != other.artist){
return false;
}
if (size != other.size){
return false;
}
return true;
}
//Overridden < method for Songs
bool Song::operator <(Song const &other) {
if (this->artist < other.artist) {
return true;
}
else if (this->artist > other.artist) {
return false;
}
if (this->title < other.title){
return true;
}
else if(this->title > other.title){
return false;
}
return (this->size < other.size);
}
//Overridden > method for Songs
bool Song::operator >(Song const &other) {
if (this->artist > other.artist) {
return true;
}
else if (this->artist < other.artist) {
return false;
}
if (this->title > other.title){
return true;
}
else if(this->title < other.title){
return false;
}
return (this->size > other.size);
}
| true |
ef59b5fa24166ae40106cb44c8746d81451d42d6 | C++ | sourgrape253/Cloth-Simulator | /Summative2/main.cpp | UTF-8 | 7,922 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include "GameScene.h"
#define BUTTON_UP 0
#define BUTTON_DOWN 1
#define MOUSE_DOWN 0
#define MOUSE_UP 1
// Mouse
#define MOUSE_LEFT 0
#define MOUSE_MIDDLE 1
#define MOUSE_RIGHT 2
unsigned char mouseState[3];
GLfloat yaw = -90.0f;
GLfloat pitch = 0.0f;
GLfloat lastX = WIDTH / 2.0;
GLfloat lastY = HEIGHT / 2.0;
bool firstMouse = true;
GameScene* rGame;
Camera* _SceneCamera;
// Picking
glm::vec3 g_RayDirection;
float g_MouseX;
float g_MouseY;
/*
* Function - Keyboard()
* Set keyboard state to key down and pass in key pressed
*/
void Keyboard(unsigned char key, int x, int y)
{
rGame->keyState[key] = BUTTON_DOWN;
_SceneCamera->keyState[key] = BUTTON_DOWN;
}
/*
* Function - Keyboard_up()
* Set keyboard state to up and pass in the key released
*/
void Keyboard_up(unsigned char key, int x, int y)
{
rGame->keyState[key] = BUTTON_UP;
_SceneCamera->keyState[key] = BUTTON_UP;
}
/*
* Function - UpdateMousePicking()
* Checks for user clicks and processes wether the mouse collided with any objects
*/
void UpdateMousePicking()
{
// screen Pos
glm::vec2 normalizedScreenPos = glm::vec2(g_MouseX, g_MouseY);
// screen pos to proj space
glm::vec4 clipCoords = glm::vec4(normalizedScreenPos.x, normalizedScreenPos.y, -1.0f, 1.0f);
//Proj space to eye space
glm::mat4 invProjMat = glm::inverse(rGame->sceneCamera->Projectionmatrix);
glm::vec4 eyeCoords = invProjMat * clipCoords;
eyeCoords = glm::vec4(eyeCoords.x, eyeCoords.y, -1.0f, 0.0f);
// eyespace to world space
glm::mat4 invViewMat = glm::inverse(rGame->view);
glm::vec4 RayWorld = invViewMat * eyeCoords;
g_RayDirection = glm::normalize(glm::vec3(RayWorld));
rGame->_RayPickDir = g_RayDirection;
}
/*
* Function - mouse()
* Check the current state of the mouse
*/
void mouse(int button, int button_state, int x, int y)
{
#define state ((button_state == GLUT_DOWN) ? MOUSE_DOWN : MOUSE_UP);
switch (button)
{
case GLUT_LEFT_BUTTON:
mouseState[MOUSE_LEFT] = state;
if (button_state == MOUSE_DOWN)
{
for (int j = 0; j < rGame->CurtainCloth->m_Cloth_Parts.size(); j++)
{
rGame->CurtainCloth->m_Cloth_Parts[j]->UpdateInteractions(g_RayDirection, _SceneCamera->m_CameraPosition);
}
rGame->Particle_Dragging = true;
}
else
{
rGame->Particle_Dragging = false;
rGame->m_PickedParticles.clear();
}
break;
case GLUT_MIDDLE_BUTTON:
mouseState[MOUSE_MIDDLE] = state;
break;
case GLUT_RIGHT_BUTTON:
mouseState[MOUSE_RIGHT] = state;
if (button_state == MOUSE_DOWN)
{
for (int j = 0; j < rGame->CurtainCloth->m_Cloth_Parts.size(); j++)
{
rGame->CurtainCloth->m_Cloth_Parts[j]->TearCloth(g_RayDirection, _SceneCamera->m_CameraPosition);
}
rGame->Particle_Dragging = true;
}
else
{
rGame->Particle_Dragging = false;
rGame->m_PickedParticles.clear();
}
break;
default:
break;
}
}
/*
* Function - UpdateMouseWhilstClicked()
* Process mouse position when clicked
*/
void UpdateMouseWhilstClicked(int x, int y)
{
// Picking
g_MouseX = (2.0f * x) / (float)WIDTH - 1.0f;
g_MouseY = 1.0f - (2.0f * y) / (float)HEIGHT;
}
/*
* Function - mousePassiveMove()
* Process the current mouse position
*/
void mousePassiveMove(int x, int y)
{
// Picking
g_MouseX = (2.0f * x) / (float)WIDTH - 1.0f;
g_MouseY = 1.0f - (2.0f * y) / (float)HEIGHT;
if (firstMouse)
{
lastX = x;
lastY = y;
firstMouse = false;
}
if (x > WIDTH - 100.0f || x < 100 || y > HEIGHT - 100.0f || y < 100) {
glutWarpPointer(400, 300);
lastX = 400;
lastY = 300;
}
GLfloat xoffset = x - lastX;
GLfloat yoffset = lastY - y; // reversed since y-co ords go from bottom to left
lastX = x;
lastY = y;
GLfloat sensitivity = 0.1;
xoffset *= sensitivity;
yoffset *= sensitivity;
yaw += xoffset;
pitch += yoffset;
// Make sure that when pitch is out of bounds, screen doesnt get flipped
if (pitch > 89.0f)
{
pitch = 89.0f;
}
if (pitch < -89.0f)
{
pitch = -89.0f;
}
glm::vec3 front;
front.x = cos(yaw * DEGTORAD) * cos(pitch * DEGTORAD);
front.y = sin(pitch * DEGTORAD);
front.z = sin(yaw * DEGTORAD) * cos(pitch * DEGTORAD);
_SceneCamera->SetCameraFront(glm::normalize(front));
}
/*
* Function - SpecialInput()
* Process special inputs (arrow keys)
*/
void SpecialInput(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_UP:
//std::cout << "KeyUp" << std::endl;
if (rGame->Selected_Attribute == CLOTHSCALE)
{
rGame->UpdateHeight(1);
}
if (rGame->Selected_Attribute == HOOKSIZE)
{
rGame->UpdateHooks(1);
}
if (rGame->Selected_Attribute == MOVEWIND)
{
rGame->MoveWind(1, false);
}
break;
case GLUT_KEY_DOWN:
//std::cout << "KeyDown" << std::endl;
if (rGame->Selected_Attribute == CLOTHSCALE)
{
rGame->UpdateHeight(-1);
}
if (rGame->Selected_Attribute == HOOKSIZE)
{
rGame->UpdateHooks(-1);
}
if (rGame->Selected_Attribute == MOVEWIND)
{
rGame->MoveWind(-1, false);
}
break;
case GLUT_KEY_LEFT:
//std::cout << "Keyleft" << std::endl;
if (rGame->Selected_Attribute == CLOTHSCALE)
{
rGame->UpdateWidth(-1);
}
if (rGame->Selected_Attribute == HOOKSIZE)
{
rGame->UpdateHooks(-1);
}
if (rGame->Selected_Attribute == MOVEHOOKS)
{
rGame->MoveHooks(false);
}
if (rGame->Selected_Attribute == CLOTHSTRUCTURE)
{
rGame->UpdateClothStructure();
}
if (rGame->Selected_Attribute == MOVEWIND)
{
rGame->MoveWind(-1, true);
}
if (rGame->Selected_Attribute == WINDSPEED)
{
rGame->UpdateWindSpeed(-1);
}
break;
case GLUT_KEY_RIGHT:
//std::cout << "Keyright" << std::endl;
if (rGame->Selected_Attribute == CLOTHSCALE)
{
rGame->UpdateWidth(1);
}
if (rGame->Selected_Attribute == HOOKSIZE)
{
rGame->UpdateHooks(1);
}
if (rGame->Selected_Attribute == MOVEHOOKS)
{
rGame->MoveHooks(true);
}
if (rGame->Selected_Attribute == CLOTHSTRUCTURE)
{
rGame->UpdateClothStructure();
}
if (rGame->Selected_Attribute == MOVEWIND)
{
rGame->MoveWind(1, true);
}
if (rGame->Selected_Attribute == WINDSPEED)
{
rGame->UpdateWindSpeed(1);
}
break;
default:
break;
}
std::cout << rGame->CurrentlySelecting << std::endl;
}
/*
* Function - init()
* Main initialise function which calls the Game world initialise to create the game
*/
void init()
{
rGame->InitGameWorld();
}
/*
* Function - render()
* Main render loop which calls the render function to render game objects
*/
void render()
{
rGame->RenderGameWorld();
}
/*
* Function - update()
* Main update loop which calls the game world update and processes all actions/entities
*/
void update()
{
glutKeyboardFunc(Keyboard);
glutKeyboardUpFunc(Keyboard_up);
rGame->UpdateCamera();
rGame->UpdateGameWorld();
UpdateMousePicking();
}
/*
* Function - main()
* Main loop to create and run the programme
*/
int main(int argc, char **argv)
{
glutInit(&argc, argv);
// make sure to include GLUT_MULTISAMPLE for anti alisaing
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA | GLUT_MULTISAMPLE);
glutInitWindowPosition(200, 200);
glutInitWindowSize(WIDTH, HEIGHT);
glutCreateWindow("Cloth Curtain Thingy");
glewInit();
// Enable Depth Test
glEnable(GL_DEPTH_TEST);
//Enable anti aliasing
glutSetOption(GLUT_MULTISAMPLE, 8);
glEnable(GL_MULTISAMPLE);
glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST);
// Enable back face culling
//glCullFace(GL_BACK);
//glEnable(GL_CULL_FACE);
rGame = &GameScene::GetInstance();
_SceneCamera = rGame->sceneCamera;
init();
glutSetCursor(GLUT_CURSOR_FULL_CROSSHAIR);
glClearColor(1.0, 0.0, 1.0, 1.0); // clear red
// Mouse
glutMouseFunc(mouse);
glutPassiveMotionFunc(mousePassiveMove);
glutMotionFunc(UpdateMouseWhilstClicked);
// special
glutSpecialFunc(SpecialInput);
// register callbacks
glutDisplayFunc(render);
glutIdleFunc(update);
glutMainLoop();
return (0);
}
| true |
5aca788c8fc9f0f4d53f4b219ab9297def0fc8e1 | C++ | emptyland/mio | /src/lexer-test.cc | UTF-8 | 8,475 | 2.640625 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #include "lexer.h"
#include "token.h"
#include "fixed-memory-input-stream.h"
#include "gtest/gtest.h"
namespace mio {
TEST(LexerTest, TestingStream) {
FixedMemoryInputStream s("abc");
ASSERT_FALSE(s.eof());
ASSERT_EQ('a', s.ReadOne());
ASSERT_FALSE(s.eof());
ASSERT_EQ('b', s.ReadOne());
ASSERT_FALSE(s.eof());
ASSERT_EQ('c', s.ReadOne());
ASSERT_TRUE(s.eof());
}
TEST(LexerTest, AssignAndEq) {
auto s = new FixedMemoryInputStream("=");
Lexer lex(s, true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ASSIGN, token.token_code());
ASSERT_EQ(0, token.position());
ASSERT_EQ(1, token.len());
ASSERT_FALSE(lex.Next(&token));
lex.PopScope();
lex.PushScope(new FixedMemoryInputStream("=="), true);
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_EQ, token.token_code());
ASSERT_EQ(0, token.position());
ASSERT_EQ(2, token.len());
}
TEST(LexerTest, IgnoreSpace) {
Lexer lex(new FixedMemoryInputStream("= = = ="), true);
TokenObject token;
int pos[4] = {0, 2, 6, 9};
for (auto i = 0; i < 4; ++i) {
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ASSIGN, token.token_code());
ASSERT_EQ(pos[i], token.position());
}
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, LineComments) {
Lexer lex(new FixedMemoryInputStream(" #abc\n"), true);
TokenObject token;
lex.set_dont_ignore_comments(true);
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_LINE_COMMENT, token.token_code());
ASSERT_EQ(1, token.position());
ASSERT_EQ(5, token.len());
ASSERT_EQ("#abc\n", token.text());
}
TEST(LexerTest, IntLiteral) {
Lexer lex(new FixedMemoryInputStream(" 123 "), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_INT_LITERAL, token.token_code());
ASSERT_EQ(123, token.int_data());
ASSERT_EQ(1, token.position());
ASSERT_EQ(3, token.len());
ASSERT_EQ("123", token.text());
}
TEST(LexerTest, IntegralSuffix) {
Lexer lex(new FixedMemoryInputStream(" 64b "), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_I8_LITERAL, token.token_code());
ASSERT_EQ(64, token.i8_data());
ASSERT_EQ(1, token.position());
ASSERT_EQ(3, token.len());
ASSERT_EQ("64b", token.text());
}
TEST(LexerTest, HexIntegral) {
Lexer lex(new FixedMemoryInputStream("0x1 0x001 0x00001"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_I8_LITERAL, token.token_code());
ASSERT_EQ(1, token.i8_data());
ASSERT_EQ(0, token.position());
ASSERT_EQ(3, token.len());
ASSERT_EQ("0x1", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_I16_LITERAL, token.token_code());
ASSERT_EQ(1, token.i8_data());
ASSERT_EQ(4, token.position());
ASSERT_EQ(5, token.len());
ASSERT_EQ("0x001", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_I32_LITERAL, token.token_code());
ASSERT_EQ(1, token.i8_data());
ASSERT_EQ(10, token.position());
ASSERT_EQ(7, token.len());
ASSERT_EQ("0x00001", token.text());
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, IDParsing) {
Lexer lex(new FixedMemoryInputStream("$1 _1 name"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ID, token.token_code());
ASSERT_EQ(0, token.position());
ASSERT_EQ(2, token.len());
ASSERT_EQ("$1", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ID, token.token_code());
ASSERT_EQ(3, token.position());
ASSERT_EQ(2, token.len());
ASSERT_EQ("_1", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ID, token.token_code());
ASSERT_EQ(6, token.position());
ASSERT_EQ(4, token.len());
ASSERT_EQ("name", token.text());
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, IDKeywordParsing) {
Lexer lex(new FixedMemoryInputStream("i8 and $1"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_I8, token.token_code());
ASSERT_EQ(0, token.position());
ASSERT_EQ(2, token.len());
ASSERT_EQ("i8", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_AND, token.token_code());
ASSERT_EQ(3, token.position());
ASSERT_EQ(3, token.len());
ASSERT_EQ("and", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_ID, token.token_code());
ASSERT_EQ(7, token.position());
ASSERT_EQ(2, token.len());
ASSERT_EQ("$1", token.text());
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, StringLiteral) {
Lexer lex(new FixedMemoryInputStream("\'\' \'abc\'"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_STRING_LITERAL, token.token_code());
ASSERT_EQ(0, token.position());
ASSERT_EQ(2, token.len());
ASSERT_EQ("", token.text());
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_STRING_LITERAL, token.token_code());
ASSERT_EQ(3, token.position());
ASSERT_EQ(5, token.len());
ASSERT_EQ("abc", token.text());
}
TEST(LexerTest, StringLiteralHexEscape) {
Lexer lex(new FixedMemoryInputStream("\'\\x00\\x01\'"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_STRING_LITERAL, token.token_code()) << token.text();
ASSERT_EQ(0, token.position());
ASSERT_EQ(10, token.len());
EXPECT_EQ(0x00, token.text()[0]);
EXPECT_EQ(0x01, token.text()[1]);
}
TEST(LexerTest, StringLiteralSpecEscape) {
Lexer lex(new FixedMemoryInputStream("\'\\r \\n \\t'"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
ASSERT_EQ(TOKEN_STRING_LITERAL, token.token_code()) << token.text();
ASSERT_EQ(0, token.position());
ASSERT_EQ(10, token.len());
EXPECT_EQ("\r \n \t", token.text());
}
TEST(LexerTest, Operators1) {
Lexer lex(new FixedMemoryInputStream("< << <= <>"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_LT, token.token_code()) << token.text();
EXPECT_EQ(0, token.position());
EXPECT_EQ(1, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_LSHIFT, token.token_code()) << token.text();
EXPECT_EQ(2, token.position());
EXPECT_EQ(2, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_LE, token.token_code()) << token.text();
EXPECT_EQ(5, token.position());
EXPECT_EQ(2, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_NE, token.token_code()) << token.text();
EXPECT_EQ(8, token.position());
EXPECT_EQ(2, token.len());
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, Operators2) {
Lexer lex(new FixedMemoryInputStream("> |> >> >="), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_GT, token.token_code()) << token.text();
EXPECT_EQ(0, token.position());
EXPECT_EQ(1, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_RSHIFT_L, token.token_code()) << token.text();
EXPECT_EQ(2, token.position());
EXPECT_EQ(2, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_RSHIFT_A, token.token_code()) << token.text();
EXPECT_EQ(5, token.position());
EXPECT_EQ(2, token.len());
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_GE, token.token_code()) << token.text();
EXPECT_EQ(8, token.position());
EXPECT_EQ(2, token.len());
ASSERT_FALSE(lex.Next(&token));
}
TEST(LexerTest, FloatingLiteral) {
Lexer lex(new FixedMemoryInputStream("0.1"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_F32_LITERAL, token.token_code()) << token.text();
EXPECT_EQ(0, token.position());
EXPECT_EQ(3, token.len());
EXPECT_NEAR(0.1f, token.f32_data(), 0.0000001f);
}
TEST(LexerTest, FloatingLiteralWithStuffix) {
Lexer lex(new FixedMemoryInputStream("0.1D 0.22F"), true);
TokenObject token;
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_F64_LITERAL, token.token_code()) << token.text();
EXPECT_EQ(0, token.position());
EXPECT_EQ(4, token.len());
EXPECT_NEAR(0.1f, token.f64_data(), 0.01f);
ASSERT_TRUE(lex.Next(&token));
EXPECT_EQ(TOKEN_F32_LITERAL, token.token_code()) << token.text();
EXPECT_EQ(5, token.position());
EXPECT_EQ(5, token.len());
EXPECT_NEAR(0.22f, token.f32_data(), 0.001f);
}
} // namespace mio
| true |
89b309f67d6afa452b80bb520d4ee3de1832da78 | C++ | BubagraJamatia2001/Coding-Ninjas-Data-Structures-Algo-with-Cpp | /Binary Trees/Balanced.cpp | UTF-8 | 2,613 | 3.9375 | 4 | [] | no_license | /*
Balanced
Given a binary tree, check if its balanced i.e. depth of left and right subtrees of every node differ by at max 1. Return true if given binary tree is balanced, false otherwise.
Input format :
Elements in level order form (separated by space). If any node does not have left or right child, take -1 in its place.
Sample Input 1 :
5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1
Sample Output 1 :
false
Sample Input 2 :
1 2 3 -1 -1 -1 -1
Sample Output 2 :
true
*/
#include <iostream>
#include <queue>
template <typename T>
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
using namespace std;
#include "solution.h"
BinaryTreeNode<int>* takeInput() {
int rootData;
//cout << "Enter root data : ";
cin >> rootData;
if(rootData == -1) {
return NULL;
}
BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData);
queue<BinaryTreeNode<int>*> q;
q.push(root);
while(!q.empty()) {
BinaryTreeNode<int> *currentNode = q.front();
q.pop();
int leftChild, rightChild;
//cout << "Enter left child of " << currentNode -> data << " : ";
cin >> leftChild;
if(leftChild != -1) {
BinaryTreeNode<int>* leftNode = new BinaryTreeNode<int>(leftChild);
currentNode -> left =leftNode;
q.push(leftNode);
}
//cout << "Enter right child of " << currentNode -> data << " : ";
cin >> rightChild;
if(rightChild != -1) {
BinaryTreeNode<int>* rightNode = new BinaryTreeNode<int>(rightChild);
currentNode -> right =rightNode;
q.push(rightNode);
}
}
return root;
}
//code
#include<cmath>
#include<algorithm>
class Pair {
public:
bool b;
int Height;
};
Pair Balanced(BinaryTreeNode<int> *root) {
if(root==NULL) {
Pair P;
P.b=true;
P.Height=0;
return P;
}
Pair P,P1,P2;
P1=Balanced(root->left);
P2=Balanced(root->right);
P.Height=max(P1.Height,P2.Height)+1;
if(P1.b == false || P2.b == false) {
P.b=false;
return P;
}
if(abs(P1.Height-P2.Height)<=1) {
P.b=true;
return P;
}
P.b=false;
return P;
}
bool isBalanced(BinaryTreeNode<int> *root) {
Pair P = Balanced(root);
return P.b;
}
int main() {
BinaryTreeNode<int>* root = takeInput();
if(isBalanced(root))
cout << "true" << endl;
else
cout << "false" << endl;
}
| true |
106bcab6439f6c24778f6f5db5d1eaa1d52f9a41 | C++ | yippp/CSC3002_Assignment | /hw3/src/p2.cpp | UTF-8 | 1,818 | 3.265625 | 3 | [] | no_license | /*
* File: p2.cpp
* --------------------------
* This is used to test the answer to question 2 of assignmet 3 of CSC 3002 at CUHKSZ
* Done by Shuqian Ye, 115010269
*/
#include "pqueue_list.h"
using namespace std;
/*
* Function: q2
* Usage: q2();
* ------------------------
* Test the code for question 2.
*/
void p2() {
cout << "PriorityQueue<string> q;" << endl;
PriorityQueue<string> q;
cout << "enqueue A" << endl;
q.enqueue("A", 5);
cout << "enqueue B" << endl;
q.enqueue("B", 2);
cout << "enqueue C" << endl;
q.enqueue("C", 9);
cout << "enqueue D" << endl;
q.enqueue("D", 2);
cout << "enqueue E" << endl;
q.enqueue("E", 7);
cout << "size:" << q.size() << endl;
cout << "isempty:" << q.isEmpty() << endl;
double priority;
cout << "q.dequeue" << endl;
cout << q.dequeue(priority) << priority << endl;
cout << q.dequeue(priority) << priority << endl;
cout << q.dequeue(priority) << priority << endl;
cout << q.dequeue(priority) << priority << endl;
cout << q.dequeue(priority) << priority << endl;
cout << "size:" << q.size() << endl;
cout << endl << "enqueue A" << endl;
q.enqueue("A", 5);
cout << "enqueue E" << endl;
q.enqueue("E", 7);
cout << endl << "PriorityQueue<string> copy = q;" << endl;
PriorityQueue<string> copy = q;
cout << "copy.peek: "<<copy.peek(priority) << priority << endl;
cout << endl << "PriorityQueue<string> copy2(q);" << endl;
PriorityQueue<string> copy2(q);
cout << "copy2.size: "<< copy2.size() << endl;
cout << endl << "q.clear();" << endl;
q.clear();
cout << "q.isempty:" << q.isEmpty() << endl;
cout << endl << "copy.~PriorityQueue();" << endl;
copy.~PriorityQueue();
cout << "copy.isempty:" << copy.isEmpty() << endl;
}
| true |
80052e08b2ae7a530ca6d9e9765b2d8416b12751 | C++ | JakeKandell/rubiks-cube-teacher | /colors.cpp | UTF-8 | 7,099 | 2.65625 | 3 | [] | no_license | #include "colors.h"
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
using namespace cv;
using namespace std;
// compare function used to sort by x coordinate
bool xCmp(Point a, Point b) {
return a.x < b.x;
}
// compare function used to sort by y coordinate
bool yCmp(Point a, Point b) {
return a.y < b.y;
}
void sortPieces(vector<Point>& pieceLocations) {
// sorts pieces by y coordinate
sort(pieceLocations.begin(), pieceLocations.end(), yCmp);
// sorts pieces in first row by x coordinates
sort(pieceLocations.begin(), pieceLocations.begin()+3, xCmp);
// sorts pieces in second row by x coordinates
sort(pieceLocations.begin()+3, pieceLocations.begin()+6, xCmp);
// sorts pieces in third row by x coordinates
sort(pieceLocations.begin()+6, pieceLocations.end(), xCmp);
}
void thresholdOneColor(Mat& frameHSV, Mat& frameContours, Scalar lowThresh, Scalar highThresh, vector<vector<Point>>& allContours, vector<Point>& piecesOnly, vector<string>& colorsOnly, string color, Scalar drawColor) {
Mat frameThreshold;
// theshold image for specific color
inRange(frameHSV, lowThresh, highThresh, frameThreshold);
// debug code used to show orig image with threshold view
// while (true) {
// imshow("Saved Image", frameContours);
// imshow("Saved Threshold", frameThreshold);
//
// char key = (char) waitKey(30);
// if (key == 'q' || key == 27)
// {
// break;
// }
// }
// kernels used for morphology operations
Mat kernelOpen = getStructuringElement(0, Size(5, 5), Point(-1, -1));
Mat kernelClose = getStructuringElement(0, Size(5, 5), Point(-1, -1));
// opening operation to remove small noise
morphologyEx(frameThreshold, frameThreshold, 2, kernelOpen);
// closing operation to fill in holes
morphologyEx(frameThreshold, frameThreshold, 3, kernelClose);
// debug code to show before and after morphological operations
// while (true) {
// imshow("Updated Threshold", frameThreshold);
//
// char key = (char) waitKey(30);
// if (key == 'q' || key == 27)
// {
// break;
// }
// }
// use canny edge detection
Mat cannyOutput;
Canny(frameThreshold, cannyOutput, 100, 200);
vector<vector<Point>> tempContours;
vector<Vec4i> tempHierarchy;
// find countours of threshold
findContours(cannyOutput, tempContours, tempHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);
// picks a random color to draw countours
// Scalar randColor = Scalar(rand()&255, rand()&255, rand()&255);
// draws countours onto image
for(size_t i = 0; i< tempContours.size(); i++) {
drawContours(frameContours, tempContours, (int)i, drawColor, 2, LINE_8, tempHierarchy, 0);
}
destroyAllWindows();
vector<vector<Point>> noDupes;
for (unsigned int i=0; i < tempContours.size(); i += 2) {
// removes duplicates that are next to each other
noDupes.push_back(tempContours[i]);
Rect boundingRectangle = boundingRect(tempContours[i]);
Point topLeft = boundingRectangle.tl();
// pushes back point and color into two vectors
piecesOnly.push_back(topLeft);
colorsOnly.push_back(color);
}
allContours.insert(allContours.end(), noDupes.begin(), noDupes.end());
}
bool thresholdColors(Mat frame, vector<string>& fullSide) {
// seed for random colors for contours
srand(time(NULL));
Mat origFrame = frame.clone();
Mat frameContours = frame;
Mat frameHSV;
// Convert from BGR to HSV colorspace
cvtColor(frame, frameHSV, COLOR_BGR2HSV);
// initalizing contour vector
vector<vector<Point>> allContours;
// indexes correlate with each other
vector<Point> piecesOnly;
vector<string> colorsOnly;
// thresholds red
thresholdOneColor(frameHSV, frameContours, Scalar(0, 223, 162), Scalar(180, 255, 200), allContours, piecesOnly, colorsOnly, "red", Scalar(96, 108, 240));
// thresholds orange
thresholdOneColor(frameHSV, frameContours, Scalar(0, 183, 220), Scalar(23, 255, 255), allContours, piecesOnly, colorsOnly, "orange", Scalar(153, 214, 255));
// thresholds yellow
thresholdOneColor(frameHSV, frameContours, Scalar(21, 90, 212), Scalar(40, 206, 255), allContours, piecesOnly, colorsOnly, "yellow", Scalar(12, 179, 175));
// thresholds green
thresholdOneColor(frameHSV, frameContours, Scalar(43, 61, 156), Scalar(68, 125, 238), allContours, piecesOnly, colorsOnly, "green", Scalar(3, 145, 5));
// thresholds blue
thresholdOneColor(frameHSV, frameContours, Scalar(89, 105, 103), Scalar(129, 235, 191), allContours, piecesOnly, colorsOnly, "blue", Scalar(237, 151, 64));
// thresholds white
thresholdOneColor(frameHSV, frameContours, Scalar(0, 0, 236), Scalar(36, 40, 255), allContours, piecesOnly, colorsOnly, "white", Scalar(165, 165, 165));
cout << "Have all pieces been correctly identified on this side?" << endl;
cout << "Press 'y' for yes and 'n' for no." << endl;
cout << endl;
// shows image of cube with contours drawn around identified pieces
while (true) {
// imshow("Original Image", origFrame);
imshow("Identified Pieces", frameContours);
char key = (char) waitKey(30);
// case if image looks fine
if (key == 'y')
{
break;
}
// case if user recognizes an error in the processing
else if (key == 'n') {
cout << "Failed to properly identify pieces. Try taking another picture." << endl;
return false;
}
}
// failed to find proper number of squares
if (allContours.size() != 9) {
cout << "Incorrect number of squares identified. Try taking another picture." << endl;
return false;
}
vector<Point> pieceLocations;
// loops through each countour and pushes back top left point into new vector
for (unsigned int i=0; i < allContours.size(); i++) {
Rect boundingRectangle = boundingRect(allContours[i]);
Point topLeft = boundingRectangle.tl();
pieceLocations.push_back(topLeft);
}
// sorts pieces into 1-9 order
sortPieces(pieceLocations);
cout << endl;
// loops through sorted pieces in order from top left to bottom right
for (unsigned int i = 0; i < pieceLocations.size(); i++) {
Point currentPoint = pieceLocations[i];
// looks for point in vector of only pieces
vector<Point>::iterator it = find(piecesOnly.begin(), piecesOnly.end(), currentPoint);
int index = -1;
// if point is found gets index of point
if (it != piecesOnly.end()){
index = distance(piecesOnly.begin(), it);
}
// uses index to get corresponding color of piece at that point
fullSide.push_back(colorsOnly[index]);
}
// side identification has succeeded if we have reached here
return true;
}
| true |
4eb7a7c415f540c934b2cb8711369c2bf9d90769 | C++ | Dong-wook94/KNU-AlgorithmStudy | /programmers/[2020카카오공채] 블록 이동하기/명훈/60063.cpp | UHC | 3,704 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <cmath>
using namespace std;
#define MAX 100
struct robot {
int y, x; // y, x position
int dir; // if dir is 1 horizontal. else vertical
int cnt; // cnt
robot(int t_y, int t_x, bool t_dir, int t_count) {
y = t_y; x = t_x; dir = t_dir; cnt = t_count;
}
};
pair<int, int> turnDir[4] = { {-1, 0}, {0, 0}, {-1, 1}, {0, 1} }; // horizontal <y, x>. vertical <x, y>
pair<int, int> safeTurn[4] = { {0, 1}, {1, 1}, {0, -1}, {1, -1} }; // horizontal <y, x>. vertical <x, y>
pair<int, int> goDir[4] = { {0, -1}, {-1, 0}, {0, 1}, {1, 0} };
bool visited[MAX][MAX][2];
int N;
bool isSafeTurn(vector<vector<int>> board, int y, int x, int dir, int i) {
if (dir)
return (board[y + safeTurn[i].first][x + safeTurn[i].second] == 1) ? false : true;
else
return (board[y + safeTurn[i].second][x + safeTurn[i].first] == 1) ? false : true;
}
int bfs(vector<vector<int>> board, int y, int x) {
queue<robot> q; // queue
robot t(0, 0, 1, 0);
q.push(t);
visited[0][0][1] = true;
while (!q.empty()) {
int curY = q.front().y; int curX = q.front().x;
int curDir = q.front().dir; int curCnt = q.front().cnt;
q.pop();
// end state
if (curDir) { //
if (curY == N - 1 && (curX + 1) == N - 1)
return curCnt;
}
else { //
if ((curY + 1) == N - 1 && curX == N - 1)
return curCnt;
}
// turn case (ȸ)
for (int i = 0; i < 4; i++) {
if (curDir == 1) { // ->
int nextY = curY + turnDir[i].first;
int nextX = curX + turnDir[i].second;
int nextDir = (curDir == 0) ? 1 : 0;
if (0 <= nextY && nextY < N - 1 && 0 <= nextX && nextX < N)
if (!board[nextY][nextX] && !board[nextY + 1][nextX] && !visited[nextY][nextX][nextDir])
if (isSafeTurn(board, nextY, nextX, curDir, i)) {
robot tmp(nextY, nextX, nextDir, curCnt + 1);
q.push(tmp);
visited[nextY][nextX][nextDir] = true;
}
}
else { // ->
int nextY = curY + turnDir[i].second;
int nextX = curX + turnDir[i].first;
int nextDir = (curDir == 0) ? 1 : 0;
if (0 <= nextY && nextY < N && 0 <= nextX && nextX < N - 1)
if (!board[nextY][nextX] && !board[nextY][nextX + 1] && !visited[nextY][nextX][nextDir])
if (isSafeTurn(board, nextY, nextX, curDir, i)) {
robot tmp(nextY, nextX, nextDir, curCnt + 1);
q.push(tmp);
visited[nextY][nextX][nextDir] = true;
}
}
}
// go back case (յڷ Դٰϴ )
for (int i = 0; i < 4; i++) {
if (curDir) { // ->
int nextY = curY + goDir[i].first;
int nextX = curX + goDir[i].second;
if (0 <= nextY && nextY < N && 0 <= nextX && nextX < N - 1) {
if (!board[nextY][nextX] && !board[nextY][nextX + 1] && !visited[nextY][nextX][curDir]) {
robot tmp(nextY, nextX, curDir, curCnt + 1);
q.push(tmp);
visited[nextY][nextX][curDir] = true;
}
}
}
else { // ->
int nextY = curY + goDir[i].first;
int nextX = curX + goDir[i].second;
if (0 <= nextY && nextY < N - 1 && 0 <= nextX && nextX < N) {
if (!board[nextY][nextX] && !board[nextY + 1][nextX] && !visited[nextY][nextX][curDir]) {
robot tmp(nextY, nextX, curDir, curCnt + 1);
q.push(tmp);
visited[nextY][nextX][curDir] = true;
}
}
}
}
}
return -1; // error code
}
int solution(vector<vector<int>> board) {
N = board.size();
int answer = bfs(board, 0, 0);
return answer;
}
int main() {
vector<vector<int>> board = { {0, 0, 0, 1, 1}, {0, 0, 0, 1, 0}, {0, 1, 0, 1, 1}, {1, 1, 0, 0, 1}, {0, 0, 0, 0, 0} };
cout << solution(board) << "\n";
}
| true |
dbc9d73d7953a99a537010a5752ee714c73c6063 | C++ | poul250/SlimeGame | /SlimeGame/State.cpp | UTF-8 | 731 | 2.890625 | 3 | [] | no_license | #include "State.hpp"
State::State()
: nextState(nullptr)
, stateCond(STATE_GOOD)
{ }
State::~State()
{ }
void State::init(int & progress)
{
progress = 100;
}
void State::lostFocus()
{ }
void State::gainedFocus()
{ }
void State::enterState()
{ }
void State::leaveState()
{ }
void State::setStateCond(StateCond cond, StatePtr next)
{
stateCond = cond;
nextState = next;
}
void State::stayState()
{
stateCond = STATE_GOOD;
nextState = nullptr;
}
void State::addState(StatePtr state)
{
stateCond = ADD_STATE;
nextState = state;
}
void State::removeState()
{
stateCond = REMOVE_STATE;
}
void State::replaceState(StatePtr state)
{
stateCond = REPLACE_STATE;
nextState = state;
}
| true |
b140e1ca5ba2ab6801aed1db32dfc788ede4da60 | C++ | kmyk/rsk0315-library | /utility/action/add_sum.cpp | UTF-8 | 459 | 2.765625 | 3 | [
"MIT"
] | permissive | #ifndef H_action_add_sum
#define H_action_add_sum
/**
* @brief 区間和・区間加算用のヘルパークラス
* @author えびちゃん
*/
#include "utility/monoid/length.cpp"
template <typename Tp>
struct action_add_to_sum {
using operand_type = length_monoid<Tp>;
using action_type = Tp;
static void act(operand_type& op, action_type const& a) {
op += operand_type(a * op.length(), 0);
}
};
#endif /* !defined(H_action_add_sum) */
| true |
9386af5e2326be7cf7c23da5e85bdac17bd9eb6c | C++ | 260058433/LeetCode | /src/224_BasicCalculator.cpp | UTF-8 | 2,815 | 3.375 | 3 | [] | no_license | #include <string>
#include <stack>
using std::string;
using std::stack;
class BasicCalculator {
public:
int calculate(string s) {
/*
stack<int> operands;
stack<char> operators;
int i = 0, n = s.size();
while (i < n) {
if (s[i] == ' ') {
++i;
continue;
} else if (s[i] >= '0' && s[i] <= '9') {
int a = 0;
while (i < n && s[i] >= '0' && s[i] <= '9')
a = a * 10 + s[i++] - '0';
operands.push(a);
} else {
if (s[i] == '(') {
operators.push(s[i]);
continue;
}
while (!operators.empty() && operators.top() != '(') {
int b = operands.top();
operands.pop();
int a = operands.top();
operands.pop();
switch (operators.top()) {
case '+' : operands.push(a + b); break;
case '-' : operands.push(a - b); break;
}
operators.pop();
}
if (s[i] == ')')
operators.pop();
else
operators.push(s[i]);
++i;
}
}
while (!operators.empty()) {
int b = operands.top();
operands.pop();
int a = operands.top();
operands.pop();
switch (operators.top()) {
case '+' : operands.push(a + b); break;
case '-' : operands.push(a - b); break;
}
operators.pop();
}
return operands.top();
*/
int result = 0, sign = 1;
stack<int> tmp;
int i = 0, n = s.size();
while (i < n) {
if (s[i] >= '0' && s[i] <= '9') {
int num = 0;
while (i < n && s[i] >= '0' && s[i] <= '9')
num = num * 10 + s[i++] - '0';
result += sign * num;
} else {
if (s[i] == '+') {
sign = 1;
} else if (s[i] == '-') {
sign = -1;
} else if (s[i] == '(') {
tmp.push(result);
tmp.push(sign);
result = 0;
sign = 1;
} else if (s[i] == ')') {
int num = result;
sign = tmp.top();
tmp.pop();
result = tmp.top();
tmp.pop();
result += num * sign;
}
++i;
}
}
return result;
}
};
| true |
69559456b0fbbfec831727ae261c71675c2927b8 | C++ | kasataku777/atcoder_solution | /ABC149/D/D.cpp | UTF-8 | 1,330 | 2.984375 | 3 | [] | no_license | // D.cpp : このファイルには 'main' 関数が含まれています。プログラム実行の開始と終了がそこで行われます。
//
#include <iostream>
#include<string>
using namespace std;
int main()
{
int n, k, r, s, p;
string t;
cin >> n >> k;
cin >> r >> s >> p;
cin >> t;
int sum = 0;
int flag[100000];
for (int i = 0; i < n; i++) {
flag[i] = 0;
}
for (int i = 0; i < t.size(); i++) {
if (i < k) {
if (t[i] == 'r') {
sum += p;
flag[i] = 1;
}
else if (t[i] == 's') {
sum += r;
flag[i] = 1;
}
else {
sum += s;
flag[i] = 1;
}
}
else {
if (t[i] == t[i - k] && flag[i - k] == 1) {
continue;
}
else {
if (t[i] == 'r') {
sum += p;
flag[i] = 1;
}
else if (t[i] == 's') {
sum += r;
flag[i] = 1;
}
else {
sum += s;
flag[i] = 1;
}
}
}
}
cout << sum << endl;
return 0;
}
| true |
a52ffee6553dc3331d532edb1e29d4898e94f625 | C++ | acimadamore/iot-garden | /board/iot_garden/iot_garden.ino | UTF-8 | 7,717 | 2.875 | 3 | [] | no_license | #include <ArduinoJson.h>
#include <DHT_U.h>
#include <DHT.h>
class WateringStation
{
int uid;
byte waterPumpPin;
byte soilHumiditySensorPin;
int lowSoilHumidity;
int highSoilHumidity;
int wateringTime;
public:
String name;
WateringStation(){
this->lowSoilHumidity = 30;
this->highSoilHumidity = 85;
this->wateringTime = 1000;
}
WateringStation(int uid, byte waterPumpPin, byte soilHumiditySensorPin)
{
this->uid = uid;
this->waterPumpPin = waterPumpPin;
this->soilHumiditySensorPin = soilHumiditySensorPin;
this->lowSoilHumidity = 30;
this->highSoilHumidity = 85;
this->wateringTime = 1000;
}
void init() {
pinMode(waterPumpPin, OUTPUT);
pinMode(soilHumiditySensorPin, INPUT);
}
void configure(String name, int lowSoilHumidity, int highSoilHumidity, int wateringTime) {
this->name = name;
this->lowSoilHumidity = lowSoilHumidity;
this->highSoilHumidity = highSoilHumidity;
this->wateringTime = wateringTime;
this->log("water-station-configuration-changed", "Changed water station's configuration.");
}
void check(){
if(this->readSoilHumidity() < this->lowSoilHumidity){
this->water();
}
}
int readSoilHumidity(){
int value = 100 - map(analogRead(this->soilHumiditySensorPin), 0, 1023, 0, 100);
this->log("water-station-checked", "Water station's soil humidity checked.", value);
return value;
}
void water(){
digitalWrite(this->waterPumpPin, HIGH);
delay(this->wateringTime);
digitalWrite(this->waterPumpPin, LOW);
this->log("water-station-watered", "Water station watered.");
}
void waterForPrecautionIfPossible(){
if(this->readSoilHumidity() < this->highSoilHumidity){
this->water();
}
}
private:
void log(String event, String message, int soilHumidity = -1){
const int capacity = JSON_OBJECT_SIZE(16);
StaticJsonBuffer<capacity> jb;
JsonObject& obj = jb.createObject();
obj["event"] = event;
obj["message"] = message;
obj["stationId"] = this->uid;
if(soilHumidity != -1){
obj["soilHumidity"] = soilHumidity;
}
obj.printTo(Serial);
}
};
class EnvironmentStation
{
int normalAmbientHumidity;
int highAmbientTemperature;
int maxAmbientTemperature;
DHT *dhtSensor;
public:
EnvironmentStation(){
this->normalAmbientHumidity = 40;
this->highAmbientTemperature = 30;
this->maxAmbientTemperature = 30;
}
EnvironmentStation(byte pin) {
this->dhtSensor = new DHT(pin, DHT22);
}
void init() {
(*this->dhtSensor).begin();
}
void configure(int normalAmbientHumidity, int highAmbientTemperature, int maxAmbientTemperature) {
this->normalAmbientHumidity = normalAmbientHumidity;
this->highAmbientTemperature = highAmbientTemperature;
this->maxAmbientTemperature = maxAmbientTemperature;
}
float readTemperature(){
return (*this->dhtSensor).readTemperature();
}
float readHumidity(){
return (*this->dhtSensor).readHumidity();
}
bool checkForHostileEnvironment(){
float humidity = this->readHumidity();
float temperature = this->readTemperature();
if(isnan(humidity) || isnan(temperature)){
return false;
}
log(humidity, temperature);
return humidity < this->normalAmbientHumidity && temperature > this->highAmbientTemperature
|| humidity > this->normalAmbientHumidity && temperature > this->maxAmbientTemperature;
}
private:
void log(float humidity, float temperature){
const int capacity = JSON_OBJECT_SIZE(16);
StaticJsonBuffer<capacity> jb;
JsonObject& obj = jb.createObject();
obj["event"] = "environment-station-checked";
obj["message"] = "Environment temperature and humidity checked.";
obj["temperature"] = temperature;
obj["humidity"] = humidity;
obj.printTo(Serial);
}
};
class IoTGarden
{
bool isTurnOn;
int wateringStationsCount;
WateringStation wateringStations[2];
EnvironmentStation environmentStation;
int checkStationsDelay;
public:
IoTGarden() {
this->isTurnOn = false;
this->wateringStationsCount = 0;
this->checkStationsDelay = 10000;
}
void init(){
for(int i=0; i < this->wateringStationsCount; i++){
wateringStations[i].init();
}
this->environmentStation.init();
}
void work(){
if (isTurnOn) {
if(this->environmentStation.checkForHostileEnvironment()){
for(int i=0; i < this->wateringStationsCount; i++){
this->wateringStations[i].waterForPrecautionIfPossible();
}
}
for(int i=0; i < this->wateringStationsCount; i++){
this->wateringStations[i].check();
}
delay(this->checkStationsDelay);
}
}
void setEnvironmentStationAt(byte pin){
this->environmentStation = EnvironmentStation(pin);
}
void addWateringStationAt(byte waterPumpPin, byte soilSensorPin){
this->wateringStations[this->wateringStationsCount] = WateringStation(this->wateringStationsCount, waterPumpPin, soilSensorPin);
this->wateringStationsCount++;
}
void handleSerialEvent(){
const int capacity = JSON_OBJECT_SIZE(16);
StaticJsonBuffer<capacity> jb;
JsonObject& obj = jb.parseObject(Serial);
if(obj.success()){
if(obj["type"] == "turn-on"){
this->turnOn();
this->log("turned-on", "IoT Garden turn on!");
}
if(obj["type"] == "turn-off"){
this->turnOff();
this->log("turned-off", "IoT Garden turn off :(");
}
if(obj["type"] == "water-station"){
this->wateringStations[(int)obj["stationId"]].water();
}
if(obj["type"] == "configure-water-station"){
this->wateringStations[(int)obj["stationId"]].configure(obj["name"], obj["minHumidity"], obj["maxHumidity"], obj["watering"]);
}
if(obj["type"] == "configure-environment"){
this->environmentStation.configure((int)obj["humidity"], (int)obj["temperature"], (int)obj["maxTemperature"]);
this->log("environment-station-configuration-changed", "Changed environment station's configuration.");
}
if(obj["type"] == "configure-system"){
this->configure((int)obj["checkStationsDelay"]);
this->log("system-configuration-changed", "Changed system's configuration.");
}
}
}
private:
void log(String event, String message){
const int capacity = JSON_OBJECT_SIZE(16);
StaticJsonBuffer<capacity> jb;
JsonObject& obj = jb.createObject();
obj["event"] = event;
obj["message"] = message;
obj.printTo(Serial);
}
void configure(int checkStationsDelay){
this->checkStationsDelay = checkStationsDelay;
}
void turnOn(){
this->isTurnOn = true;
}
void turnOff(){
this->isTurnOn = false;
}
};
IoTGarden wateringSystem;
void setup() {
Serial.begin(9600);
wateringSystem.addWateringStationAt(2, A2);
wateringSystem.addWateringStationAt(4, A4);
wateringSystem.setEnvironmentStationAt(8);
wateringSystem.init();
}
void loop() {
wateringSystem.work();
}
void serialEvent() {
wateringSystem.handleSerialEvent();
}
| true |
57051a0883f673ce4e086cf7532f8401f55e8798 | C++ | ShiboYao/Leetcode_cpp | /0125_valid_palindrome.cpp | UTF-8 | 975 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <cctype>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
if (s.empty() || s.size() == 1)
return true;
int i = 0, j = s.size()-1;
int move = 0;
while (i < j){
while (i < j && !isalnum(s[i])){
i++;
move++;
}
while (i < j && !isalnum(s[j])){
j--;
move++;
}
while (i < j && tolower(s[i]) == tolower(s[j])){
i++;
j--;
move++;
}
if (move == 0)
break;
move = 0;
}
return i<j?false:true;
}
};
int main(int argc, char** argv){
if (argc < 2){
cout << "Specify string!" << endl;
exit(1);
}
string str = argv[1];
Solution s;
bool r = s.isPalindrome(str);
cout << r << endl;
return 0;
}
| true |
8754c43c3954a93b182e8bf363523942f8bbff8f | C++ | Hillosanation/TetrisReverseSolve | /IO/StorageDataTransfer.cpp | UTF-8 | 8,552 | 2.625 | 3 | [] | no_license | #include <fstream>
#include <sstream>
#include <iostream>
#include <filesystem>
#include <chrono>
#include "../SettingsData.h"
#include "./StorageDataTransfer.h"
#include "../Misc/CommonFunctions.h"
void StorageDataTransfer::OutputPresentPiece(PresentPieces PPiece, std::ofstream& os) {
for (auto Piece : PPiece) {
os << Piece;
}
}
//void StorageDataTransfer::TestIO() {
// StorageDataTransfer DataAccess; //I/O test
// Merger merge;
// std::vector<FuSol> FileInput = DataAccess.ReadInputFile();
// /*for (auto i : FileInput) { //print out what was read
// std::cout << "Fumen: " << i.Fumen << " | ";
// std::cout << "Solves: ";
// for (auto j : i.Solves) {
// std::cout << j << " ";
// }
// std::cout << std::endl;
// }*/
// FileInput = merge.MergeDuplicates(FileInput);
// DataAccess.WriteOutputFile(FileInput);
//}
//std::vector<StrSol> StorageDataTransfer::ReadInputCSV(std::string InputName) { //parses stored csv //this version assumes solutions come in the form of numbers
// std::ifstream fs;
// fs.open("../" + InputName, std::fstream::in);
// std::string line;
// bool FirstLine = true;
//
// std::vector<StrSol> tmpStrSols;
//
// while (std::getline(fs, line)) { //reads a line from fs
// if (FirstLine) { //has column names, ignore them
// FirstLine = !FirstLine;
// continue;
// }
// StrSol tmpStrSol;
// std::stringstream linestream(line); //a stream but data is like a string
// std::string value;
// bool FieldPart = true;
// while (std::getline(linestream, value, ',')) { //reads a value from linestream
// if (FieldPart) {
// tmpStrSol.Str = value;
// FieldPart = !FieldPart;
// continue;
// }
// if (value == "") continue; //failsafe: annoying artifacts when editing csv from excel
// PresentPieces tmpSol = StringToSol(value);
// tmpStrSol.Solves.push_back(tmpSol);
// //std::cout << value << " ";
// }
// if (tmpStrSol.Solves.size() == 0) { //no previous entries, add empty entry
// tmpStrSol.Solves.push_back({});
// }
// tmpStrSols.push_back(tmpStrSol);
// //std::cout << std::endl;
// };
// fs.close();
//
// return tmpStrSols;
//}
std::vector<StrFieldStrPiece> StorageDataTransfer::ReadInputCSV(std::string InputName) { //parses stored csv
std::ifstream fs;
fs.open(PathPrefix + InputName, std::fstream::in);
std::string line;
bool FirstLine = true;
std::vector<StrFieldStrPiece> tmpSFieldSPieces;
while (std::getline(fs, line)) { //reads a line from fs
if (FirstLine) { //has column names, ignore them
FirstLine = !FirstLine;
continue;
}
StrFieldStrPiece tmpSFieldSPiece;
std::stringstream linestream(line); //a stream but data is like a string
std::string value;
bool FieldPart = true;
while (std::getline(linestream, value, ',')) { //reads a value from linestream
if (FieldPart) {
tmpSFieldSPiece.Field = value;
FieldPart = !FieldPart;
continue;
}
if (value == "") continue; //failsafe: annoying artifacts when editing csv from excel
tmpSFieldSPiece.Solves.push_back(value);
//std::cout << value << " ";
}
if (tmpSFieldSPiece.Solves.size() == 0) { //no previous entries, add empty entry
tmpSFieldSPiece.Solves.push_back("");
}
tmpSFieldSPieces.push_back(tmpSFieldSPiece);
//std::cout << std::endl;
};
fs.close();
return tmpSFieldSPieces;
}
//void StorageDataTransfer::WriteOutputCSV(std::vector<StrSol> SSols, std::string OutputName) { //converts into the
// std::ofstream os;
// os.open("../" + OutputName, std::fstream::trunc);
// if (!os) { //doesn't exist, make new
// std::ofstream file("../" + OutputName);
// os.open("../" + OutputName, std::fstream::trunc);
// }
// os << "fumen code, solution pieces" << std::endl;
// for (auto i : SSols) {
// os << i.Str << ",";
// for (size_t j = 0; j < i.Solves.size(); j++) {
// if (j == i.Solves.size() - 1) { //last value
// OutputPresentPiece(i.Solves.at(j), os);
// break;
// }
// OutputPresentPiece(i.Solves.at(j), os);
// os << ",";
// }
// os << std::endl;
// }
//}
void StorageDataTransfer::WriteOutputCSV(std::vector<StrFieldStrPiece> SFieldSPieces, std::string OutputName) {
std::ofstream os;
std::string path = PathPrefix + OutputName;
os.open(path, std::fstream::trunc);
if (!os) { //doesn't exist, make new
std::ofstream file(path);
os.open(path, std::fstream::trunc);
}
os << "fumen code, solution pieces" << std::endl;
for (auto SFieldSPiece : SFieldSPieces) {
std::string buffer;
buffer += SFieldSPiece.Field + ",";
for (auto Sol : SFieldSPiece.Solves) {
buffer += Sol + ",";
}
buffer.pop_back(); //remove last ,
os << buffer << "\n";
}
}
void StorageDataTransfer::ReadSettings(const std::string& SettingsName, SettingsData& Settings) {
std::ifstream fs;
fs.open(PathPrefix + SettingsName, std::fstream::in);
std::string line;
int enumIndex = 0;
while (std::getline(fs, line) and enumIndex < Settings.SearchData.size()) { //reads a line from fs
SettingsData::SearchItem MatchItem = Settings.SearchData[enumIndex];
auto ItToSearch = line.find("=");
if (ItToSearch == std::string::npos) continue; //couldn't find the setting in this line, skipping
ItToSearch += 1; //move iterator to the value part of line
std::string ValueInputted(line.begin() + ItToSearch, line.end());
if (!(IsInteger(ValueInputted) xor IsInteger(MatchItem.Value))) { //if either or both are integers
Settings.SearchData[enumIndex].Value = ValueInputted;
}
enumIndex++;
};
fs.close();
}
std::vector<PFFSol> StorageDataTransfer::DecodeCSVFormat(std::vector<StrFieldStrPiece> SFieldSPieces, SettingsData& Settings) {
auto StartTime = std::chrono::system_clock::now();
std::vector<StrSol> StrSols;
//converts string input -> sol
if (std::stoi(Settings.GetValue(SettingsData::SettingsEnum::INPUT_FORMAT)) / 2 == 0) { //index of pieces
for (const auto& SFieldSPiece : SFieldSPieces) {
StrSol tmp;
tmp.Str = SFieldSPiece.Field;
tmp.Solves = StringsToSols(SFieldSPiece.Solves);
StrSols.push_back(tmp);
}
}
else { //tetrominos
for (const auto& SFieldSPiece : SFieldSPieces) {
StrSol tmp;
tmp.Str = SFieldSPiece.Field;
tmp.Solves = TetrominossToSols(SFieldSPiece.Solves);
StrSols.push_back(tmp);
}
}
std::vector<PFFSol> PFFSols;
PFFSols.reserve(StrSols.size());
//converts string input -> PFF
if (std::stoi(Settings.GetValue(SettingsData::SettingsEnum::INPUT_FORMAT)) % 2 == 0) { //PFF String Representation
PFFSols = PFFStrRepsToPFFSols(StrSols);
}
else { //Fumen
int height = std::stoi(Settings.GetValue(SettingsData::SettingsEnum::FIELD_HEIGHT));
int width = std::stoi(Settings.GetValue(SettingsData::SettingsEnum::FIELD_WIDTH));
std::vector<FuSol> tmp = StrSolsToFuSols(StrSols);
PFFSols = FuSolsToPFFSols(tmp, height, width);
}
auto EndTime = std::chrono::system_clock::now();
std::cout << "Time taken for decoding: " << std::chrono::duration_cast<std::chrono::microseconds>(EndTime - StartTime).count() / 1000.0 << "ms\n";
return PFFSols;
}
std::vector<StrFieldStrPiece> StorageDataTransfer::EncodeCSVFormat(std::vector<PFFSol> PFFSols, SettingsData& Settings) {
auto StartTime = std::chrono::system_clock::now();
std::vector<StrFieldStrPiece> SFieldSPieces;
std::vector<StrSol> StrSols;
//make format of field
if (std::stoi(Settings.GetValue(SettingsData::SettingsEnum::OUTPUT_FORMAT)) % 2 == 0) { //PFF String Representation
StrSols = PFFSolsToPFFSStrReps(PFFSols);
}
else { //Fumen
std::vector<FuSol> tmp = PFFSolsToFuSols(PFFSols);
StrSols = FuSolsToStrSols(tmp);
}
//make format of solutions
SFieldSPieces.clear();
if (std::stoi(Settings.GetValue(SettingsData::SettingsEnum::OUTPUT_FORMAT)) / 2 == 0) { //index of pieces
for (const auto& StrSolItem : StrSols) {
StrFieldStrPiece tmp;
tmp.Field = StrSolItem.Str;
tmp.Solves = SolsToStrings(StrSolItem.Solves);
SFieldSPieces.push_back(tmp);
}
}
else { //tetrominos
for (const auto& StrSolItem : StrSols) {
StrFieldStrPiece tmp;
tmp.Field = StrSolItem.Str;
tmp.Solves = SolsToTetrominoss(StrSolItem.Solves);
SFieldSPieces.push_back(tmp);
}
}
auto EndTime = std::chrono::system_clock::now();
std::cout << "Time taken for encoding: " << std::chrono::duration_cast<std::chrono::microseconds>(EndTime - StartTime).count() / 1000.0 << "ms\n";
return SFieldSPieces;
}
| true |
35709a2c90666653330fc5c3befeab2f954dd3e4 | C++ | Arihant1467/rookie-cplusplus | /HackerEarth_1/main.cpp | UTF-8 | 1,315 | 2.75 | 3 | [] | no_license | #include <iostream>
#include<vector>
#include<algorithm>
#include<stdio.h>
using namespace std;
int main()
{
int test_cases=0,boys=0,girls=0,t,s,i=0;
vector<int> boys_height;
vector<int> girls_height;
bool con=true;
cin>>test_cases;
while(test_cases--)
{
cin>>boys;
cin>>girls;
if(boys<=girls)
{
for( i=0;i<boys;++i)
{
cin>>t;
boys_height.push_back(t);
}
t=0;
for(i=0;i<girls;++i)
{
cin>>t;
girls_height.push_back(t);
}
sort(boys_height.begin(),boys_height.end());
sort(girls_height.begin(),girls_height.end());
for(i=0;i<boys;++i)
{
if(boys_height[i]<=girls_height[i])
{
con=false;
break;
}
}
if(!con)
{
cout<<"YES\n";
}
else
{
cout<<"NO\n";
}
}
else
{
s=boys+girls;
while(s--)
{
cin>>t;
}
cout<<"NO\n";
t=0;
}
}
return 0;
}
| true |
25d7dc459ad0ac432c4cc8c1bbfa5e671430df9d | C++ | Ethan136/LeetCode | /Medium/[437] Path Sum III/437_Iteration.cpp | UTF-8 | 2,964 | 3.140625 | 3 | [] | no_license | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
struct TNodeInfo {
TreeNode* pNode;
int nSumFromRoot;
TNodeInfo( TreeNode *pNode, int nSumFromRoot ) : nSumFromRoot( nSumFromRoot ), pNode( pNode ) {}
};
#define NUM_OF_PSEUDO_HEAD ( 1 )
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
// the count of satisfied path
int nPathNum = 0;
// make a head "before" root, i.e. pseudo-head
TreeNode PseudoHeadNode( 0, root, nullptr );
vector<TNodeInfo> Branch( 1, TNodeInfo( &PseudoHeadNode, PseudoHeadNode.val ) );
int nBranchBodyLength = 0;
while( true ) {
// find a head to tail list, go left only
while( root ) {
if( NUM_OF_PSEUDO_HEAD + nBranchBodyLength >= Branch.size() ) {
Branch.push_back( TNodeInfo( nullptr, 0 ) );
}
nBranchBodyLength++;
Branch[ nBranchBodyLength ].pNode = root;
Branch[ nBranchBodyLength ].nSumFromRoot = Branch[ nBranchBodyLength - 1 ].nSumFromRoot + root->val;
root = root->left;
}
// calculate the number of the satisfied sub-path which includes "tail"
// the sub-path here is "left-linked single path"
while( nBranchBodyLength > 0 ) {
// if the right of current tail exist -> the current tail is not a real tail
if( Branch[ nBranchBodyLength ].pNode->right != nullptr ) {
break;
}
// sum to the current tail
int nSumToTail = Branch[ nBranchBodyLength ].nSumFromRoot;
// take out the nodes from pseudo-head to "node before the tail"
for( int i = 0; i < nBranchBodyLength; i++ ) {
nSumToTail -= Branch[ i ].pNode->val;
nPathNum += ( nSumToTail == sum );
}
// take out the tail
nBranchBodyLength--;
}
// if the branch has been totally popped out
if( nBranchBodyLength <= 0 ) {
break;
}
// move the "right side" divergent path of the tail of branch to "left side"
Branch[ nBranchBodyLength ].pNode->left = Branch[ nBranchBodyLength ].pNode->right;
Branch[ nBranchBodyLength ].pNode->right = nullptr;
// update the root with the node linked to left of tail
root = Branch[ nBranchBodyLength ].pNode->left;
}
return nPathNum;
}
}; | true |
632a866c90390662cfeb92ed892383eb850ed606 | C++ | GuyGoldenberg/HrmlParser | /hrml_token.cpp | UTF-8 | 5,082 | 3.078125 | 3 | [] | no_license | //
// Created by guy on 9/10/17.
//
#include <utility>
#include <stdexcept>
#include <memory>
#include <sstream>
#include <unordered_map>
#include "hrml_token.h"
#include "utils.h"
#include "validator.h"
bool HrmlToken::is_close_token() {
return this->closing_scope_token;
}
void HrmlToken::parse_token(std::stringstream &tokens_stream) {
tokens_stream >> std::ws;
if(tokens_stream.get() != ControlChars::TAG_START)
throw std::invalid_argument(std::string("A tag must begin with ") + static_cast<char>(ControlChars::TAG_START));
tokens_stream >> std::noskipws;
while(true)
{
char tmp;
if(tokens_stream.peek() == ControlChars::TAG_END)
{
this->current_token_ended = true;
break;
}
tokens_stream >> tmp;
if(tmp == ControlChars::SPACE)
break;
this->m_token_name += tmp;
}
if(this->m_token_name.length() < MIN_TAG_NAME_LENGTH)
throw std::invalid_argument("Tag name is to short at index " + std::to_string(tokens_stream.tellg()));
// Check if this is a closing tag
if(this->m_token_name[0] == ControlChars::TAG_CLOSE)
{
// Make sure the token was closed with no remaining
if(!this->current_token_ended)
{
tokens_stream >> std::ws;
if(tokens_stream.peek() != ControlChars::TAG_END)
throw std::invalid_argument("Closing tag must only contain the tag name");
}
// Skip the slash and remove the '>'
this->m_token_name = this->m_token_name.substr(1);
this->closing_scope_token = true;
tokens_stream.ignore();
}
if(!Validator::validate_keyword(this->m_token_name))
throw std::invalid_argument("Tag name is not a keyword!" + std::to_string(tokens_stream.tellg()));
// If this is an end token, validate the token and exit
if(this->closing_scope_token)
return;
// Parse the current token attributes
this->parse_token_attributes(tokens_stream);
// Skip over the token end '>'
tokens_stream.ignore();
while(true)
{
std::shared_ptr<HrmlToken> child_token = std::make_shared<HrmlToken>();
child_token->parse_token(tokens_stream);
if(child_token->is_close_token())
{
if(child_token->get_token_name() != this->m_token_name)
throw std::invalid_argument("Closing tag doesn't match opening tag name: " + std::to_string(tokens_stream.tellg()));
break;
}
this->add_child(child_token);
}
}
void HrmlToken::add_attribute(std::string name, std::string value) {
if(!m_attributes.insert(std::make_pair(name, value)).second)
{
throw std::invalid_argument("Attribute " + name + " already exists in " + this->m_token_name);
}
}
void HrmlToken::add_child(std::shared_ptr<HrmlToken> token) {
if(!m_children.insert(std::make_pair(token->get_token_name(), token)).second)
{
throw std::invalid_argument("Child tag " + token->get_token_name() + " already exists in " + this->m_token_name);
}
}
void HrmlToken::parse_token_attributes(std::stringstream &token_stream) {
while(token_stream.peek() != ControlChars::TAG_END)
{
// Skip whitespaces
token_stream >> std::ws;
// Get the attribute name
std::string tmp_attribute_name;
std::getline(token_stream >> std::ws, tmp_attribute_name, static_cast<char>(ControlChars::ATTR_EQU));
if(tmp_attribute_name.length() < MIN_ATTR_NAME_LENGTH)
throw std::invalid_argument(
"Tag attribute name is to short at index " + std::to_string(this->m_token_name.length()) + " in tag " + this->m_token_name);
// Trim any spaces after the attribute name
right_trim(tmp_attribute_name);
if(!Validator::validate_keyword(tmp_attribute_name))
throw std::invalid_argument("Attribute name must a keyword: " + std::to_string(token_stream.tellg()));
// Skip whitespaces
token_stream >> std::ws;
if(token_stream.get() != ControlChars::ATTR_VALUE_Q)
throw std::invalid_argument("Attribute value must be a string. index " + std::to_string(token_stream.tellg()));
// We don't support escaping
std::string tmp_attribute_value;
std::getline(token_stream, tmp_attribute_value, static_cast<char>(ControlChars::ATTR_VALUE_Q));
this->add_attribute(tmp_attribute_name, tmp_attribute_value);
}
}
std::string HrmlToken::get_token_name() const {
return this->m_token_name;
}
std::shared_ptr<HrmlToken> HrmlToken::get_child_by_name(std::string name) {
auto tmp_token = this->m_children.find(name);
if (tmp_token == this->m_children.end())
return nullptr;
return this->m_children.at(name);
}
std::string HrmlToken::get_attribute_by_name(const std::string &attr_name) {
auto attr = this->m_attributes.find(attr_name);
if(attr == this->m_attributes.end())
return "Not Found!";
return attr->second;
}
| true |