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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
dd464c74ed2338d6f06ec1c79d8f29d728a5c4e0 | C++ | 0xF6/CWCPP | /CWC++/File.h | UTF-8 | 1,832 | 2.84375 | 3 | [] | no_license | #pragma once
#include "CString.h"
#include "CWString.h"
#pragma region File
class FileStream;
class File {
friend FileStream;
LPVOID Data;
LARGE_INTEGER size_L;
DWORD size_D;
bool large;
bool null;
bool string;
public:
File(CString &str);
File(LPVOID Data, LARGE_INTEGER size);
File(LPVOID Data, DWORD size);
File(unsigned int null);
File(File &f);
File(const FileStream &fs);
~File();
LPVOID GetData();
DWORD GetSize_D();
LARGE_INTEGER GetSize_L();
void GetStringData(CString *str);
bool IsLarge();
void Release();
bool operator!();
File *operator=(File &obj);
void Load(LPVOID Data, LARGE_INTEGER size);
void Load(LPVOID Data, DWORD size);
};
#pragma endregion
#pragma region FileStream
enum StreamMode {
FSM_NULL, FSM_READ, FSM_WRITE, FSM_ALL
};
class FileStream {
friend class WindAPI;
HANDLE file;
size_t _pos;
size_t _size;
StreamMode mode;
bool do_not_close;
FileStream *new_stream;
FileStream *copy() const;
public:
FileStream();
FileStream(const FileStream &stream);
__forceinline ~FileStream()
{
Close();
}
__forceinline void SetPos(size_t pos)
{
this->_pos = pos;
}
__forceinline size_t GetPos()
{
return _pos;
}
__forceinline size_t GetSize()
{
return _size;
}
void WriteData(const CString &data, bool wait = false);
void WriteData(const char *data, size_t data_size, bool wait = false);
CString ReadData(size_t size = 0);
CString ReadLine();
void put(char sym);
char get();
__forceinline void Close()
{
if (!do_not_close)
{
CloseHandle(file);
file = NULL;
}
}
__forceinline operator File() const
{
return this->operator=(*this);
}
File operator=(const FileStream &s) const;
__forceinline bool operator!()
{
return (!file);
}
__forceinline bool end()
{
return (this->_size - 1 <= this->_pos);
}
};
#pragma endregion | true |
a2f28c5bfbda1a70bb733122de00cfc6b205d28c | C++ | pbeata/WriteSciSW | /ch5.cpp | UTF-8 | 2,888 | 3.34375 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
void prob2();
void prob3();
void prob4();
double compute_radius(double x, double y);
double get_rand();
void print_quadratic_roots(double a, double b, double c);
int main()
{
/*
// investigating overflow
int e;
int my_exp[5] = {10, 100, 1000, 1020, 1023};
double x, de, base;
base = 2.0;
for (int i = 0; i < 5; i++)
{
e = my_exp[i];
x = pow(base, e);
printf("%.6e\n", x);
}
// more examples reaching the limit for overflow...
de = 1023.9;
printf("%.6e\n", pow(base, de));
de = 1023.9999;
printf("%.6e\n", pow(base, de));
e = 1024;
printf("%.6e\n", pow(base, e));
*/
// prob3();
prob4();
return 0;
}
void prob2()
{
int k, n;
double x, y, roe, limit;
limit = 0.5;
n = 17;
for (k = 0; k < n; k++)
{
x = pow(10.0, -k);
y = (1.0 - cos(x)) / (x * x);
roe = limit - y;
printf("%d \t %.18f \t %.18f \t %.18f \n", k, cos(x), y, roe);
}
}
void prob3()
{
double x, y;
x = 10.0;
y = 10.0;
printf("%e\n", compute_radius(x, y));
// x = 1.0 * pow(10.0, 6);
// y = 1.0 * pow(10.0, 6);
// printf("%e\n", compute_radius(x, y));
// x = 1.0 * pow(10.0, 8);
// y = 2.0 * pow(10.0, 8);
// printf("%e\n", compute_radius(x, y));
// x = 1.0 * pow(10.0, 11);
// y = 1.0 * pow(10.0, 10);
// printf("%e\n", compute_radius(x, y));
// x = 1.0 * pow(10.0, 200);
// y = 1.0 * pow(10.0, 198);
// printf("%e\n", compute_radius(x, y));
}
/*
This type of problem for computing the root of a quadratic
equation is discussed in Goldberg's 1991 paper on floating-
point arithmetic. See equations (4-5) in that document to
learn how this problem is handled more completely.
How can we test this problem to make sure it is computing
the proper roots?
*/
void prob4()
{
srand(42);
double a = get_rand();
double b = get_rand();
double c = get_rand();
int n = 30;
for (int i = 0; i < n; i++)
{
print_quadratic_roots(a, b, c);
b = b * get_rand();
}
}
double compute_radius(double x, double y)
{
double r, c;
if (x > y)
{
c = y / x;
r = abs(x) * sqrt( 1.0 + (c * c) );
}
else
{
c = x / y;
r = abs(y) * sqrt( 1.0 + (c * c) );
}
return r;
}
double get_rand()
{
int a = 1;
int b = 100;
return ( (double)rand() / RAND_MAX ) * (b - a) + a;
}
void print_quadratic_roots(double a, double b, double c)
{
double x_neg, x_pos;
double ratio, check;
double tol = pow(10.0, -8);
check = b * b - 4.0 * a * c;
if (abs(a) > tol && check >= 0.0)
{
ratio = c / a;
x_neg = (-b - sqrt(check)) / (2.0 * a);
x_pos = ratio * (1.0 / x_neg);
printf("Roots of the quadratic: (%.6e, %.6e) \n", x_neg, x_pos);
}
else
{
printf("\n*error: nearing divide by zero, check input 'a'\n");
printf("OR argument inside sqrt is < zero \n\n");
}
} | true |
b4227620675b0a14ed3cc14219d4729e93abb51b | C++ | RiscadoA/Magma-Lib | /src/Magma/Streams/IOStream.cpp | UTF-8 | 1,198 | 2.984375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "IOStream.hpp"
#include "..\String.hpp"
#include <cstdio>
bool Magma::STDOutStreamBuffer::Overflow(char32_t character)
{
// Put UTF-8 character on STDOUT
char chr[4];
auto chrSize = UTF8::FromUnicode(character, chr);
for (size_t i = 0; i < chrSize; ++i)
if (fputc(chr[i], stdout) == EOF) // Check for EOF
return false;
return true;
}
Magma::STDOutStreamBuffer::STDOutStreamBuffer(char32_t * buffer, size_t bufferSize)
: StreamBuffer(buffer, bufferSize)
{
}
bool Magma::STDOutStreamBuffer::Sync()
{
bool ret = StreamBuffer::Sync();
if (ret == false)
return false;
fflush(stdout);
return true;
}
Magma::STDInStreamBuffer::STDInStreamBuffer(char32_t * buffer, size_t bufferSize)
: StreamBuffer(buffer, bufferSize)
{
}
char32_t Magma::STDInStreamBuffer::Underflow()
{
// Get UTF-8 character from STDIN
char chr[4];
int get = '\0';
get = fgetc(stdin);
if (get == EOF) // Check for EOF
return StreamBuffer::EndOfFile;
chr[0] = get;
auto chrSize = UTF8::GetCharSize(chr);
for (size_t i = 1; i < chrSize; ++i)
{
get = fgetc(stdin);
if (get == EOF) // Check for EOF
return StreamBuffer::EndOfFile;
chr[i] = get;
}
return UTF8::ToUnicode(chr);
}
| true |
b3f769502d2f791f0635b3007b13f60a8564fde9 | C++ | Shubham2157/Important-Cplus-plus | /inheritanceQues/main.cpp | UTF-8 | 894 | 3.578125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class data
{
public:
int x,y,z;
void accept()
{
cout<<"Input Three integer";
cin>>x;
cin>>y;
cin>>z;
}
};
class largest : public data
{
public:
void big()
{
int lar 0;
if(x>y&&x>>z)
lar=x;
else if(y>>x&&y>>z)
lar=y;
else
lar = z;
cout<<"The Largest among three : "<<lar;
}
};
class smallest : public data
{
public:
void small()
{
int lar 0;
if(x<<y&&x<<z)
lar=x;
else if(y<<x&&y<<z)
lar=y;
else
lar = z;
cout<<"The smallest among three : "<<lar;
}
};
int main()
{
data a;
a.accept();
largest b;
b.big();
smallest c;
c.small();
return 0;
}
| true |
a97963993b67cdaf4461041782bf2edd6a021aaa | C++ | LucaJiang/Homework-of-Data-Structures | /Graph/邻接矩阵/directedGraphMain.cpp | UTF-8 | 1,752 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | //
//基于有向图(有权重)的邻接矩阵实现图的各种算法;
//最后修改2019-06-06
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include "directedGraph.cpp"
using namespace std;
int main()
{//Init
int numV;
int arc[MAXV*MAXV];
//read data
fstream fin;
cout << "Open file:";
string filename;
cin >> filename;
fin.open(filename);
if (!fin.is_open())
{
cout << "Can not open file:"<<filename;
cout << " Now, open file:datasp.txt\n";
filename = "datasp.txt";
fin.open(filename);
}
if (!fin.fail())
{
cout << "Reading file:"<<filename<<"...\n";
fin >> numV;
for (int i = 0; i < numV*numV; i++)
fin >> arc[i];
}
else
throw"can not open file";
string name[MAXV];
if (fin.get()!=-1)
{
for (int i = 0; i < numV ; i++)
fin >> name[i];
}
else
{
char tempname[2] = {'0','\0'};
for (int i = 0; i < numV ; i++)
{
tempname[0] = 'A' + i;
name[i] = tempname;
}
}
directedGraph<string, int>mygraph(numV, name, arc);
fin.close();
if(!mygraph.isCity())
{
mygraph.Info();
cout << "DFS:";
mygraph.Traverse(0, 1);
cout << "BFS:";
mygraph.Traverse(0, 0);
cout << "D&BFS:";
mygraph.Traverse(0, 0.4);
// cout << "DFS_Tree:\n";
mygraph.DFS_T(0);
// }
cout << "Prim:\n";
mygraph.Prim();
cout << "Kruskal:\n";
mygraph.Kruskal();
cout << "another method of MST\n";
// mygraph.BreakCycle();
// //上面这个函数把邻接矩阵改为最小生成树的邻接矩阵
// cout << "Approximate TSP:\n";
// mygraph.Traverse(0, 1);
cout << "Dijkstra:\n";
mygraph.Dijkstra(1);
cout << "\nFloyd:\n";
mygraph.Floyd();
system("pause");
return 0;
}
| true |
041082765f6585a70f34e703871ff8d0ea860059 | C++ | ThatMathsyBardGuy/CubeMarchTerrain | /Renderer.h | UTF-8 | 767 | 2.65625 | 3 | [] | no_license | #pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <vector>
#include "Camera.h"
#include "RenderObject.h"
#include "Shader.h"
namespace rendering {
class Renderer
{
public:
Renderer(GLFWwindow& parent, Shader* shader = new Shader());
~Renderer();
Camera* GetCamera() { return m_Camera; }
void SetCamera(Camera* camera) { m_Camera = camera; }
void SetCurrentShader(Shader* shader) { m_Shader = shader; }
void AddObject(RenderObject* object);
bool RemoveObject(RenderObject* object);
void RenderObjects();
protected:
void SortObjectsByDepth();
Camera* m_Camera;
std::vector<RenderObject*> m_Objects;
GLFWwindow* m_Parent;
Shader* m_Shader;
glm::mat4 m_ViewMatrix;
glm::mat4 m_ProjectionMatrix;
};
}
| true |
2ccff565ca1176b855a921837ba6e67f2e325f96 | C++ | negarrahmati/muticore-project-regex-parser | /Hill_climbing/Dictionary.h | UTF-8 | 2,165 | 3.03125 | 3 | [] | no_license | #ifndef __DICTIONARY__
#define __DICTIONARY__
#include <list>
#include <iostream>
#include <vector>
#include <string.h>
#include <string>
#include <set>
#include <map>
#include "Dictionary_Tree.h"
#define ALPHABET_SIZE 26
#define MAX_WORD_LENGTH 30
#define MIN_WORD_LENGTH 2
using namespace std;
struct Position_Index {
int alphabet_indexs[ALPHABET_SIZE+1];
};
struct Size_Index {
Position_Index positions[MAX_WORD_LENGTH];
};
class Dictionary{
public:
// containing all words in a sorted way
vector<string> words;
map<int , string> id_to_string;
int min_word_length;
int max_word_length;
set<int> word_sizes;
// B-Tree data structure
Dictionary_Tree dictionary_tree;
// index data structure
Size_Index size_index [MAX_WORD_LENGTH - MIN_WORD_LENGTH + 1];
int *word_indexes;
int total_word_size_position;
map<string , int> word_id_map;
void sort_words();
void sort_words_according_to_position(vector<string> & , int pos );
public:
Dictionary();
Dictionary(list<string> words);
~Dictionary();
void set_words(list<string> words);
void set_id_to_string();
void create_index();
void create_dictionary_tree();
void create_word_id_map();
void print_words();
string get_random_word_by_size(int size);
// it returns possible chars that comes after this string and have word in dictionry for them
vector<char> get_possible_chars ( string str , int max_remaining_alphabets=-1 );
void get_words_by_chars_position ( vector<string> &all_possible_words , vector<char> &possible_chars , int word_size , int pos );
int get_words_by_char_position (vector<string>& , char alphabet , int word_size , int position );
bool search_word ( string word );
bool has_word_size(int size);
void set_min_word_length ( int min_word_length){
this->min_word_length = min_word_length;
}
void set_max_word_length ( int max_word_length){
this->max_word_length = max_word_length;
}
int get_min_word_length(){
return min_word_length;
}
int get_max_word_length(){
return max_word_length;
}
};
#endif
| true |
c9d8d562c23dac42a3951c0d1a9e3ccd8da076a8 | C++ | having11/packetMsgSend | /src/InputManager.cpp | UTF-8 | 727 | 2.53125 | 3 | [] | no_license | #include "InputManager.h"
void InputManager::init()
{
pinMode(PAIR_BTN_PIN, INPUT_PULLUP);
pinMode(DRAW_BTN_PIN, INPUT_PULLUP);
pinMode(SEND_BTN_PIN, INPUT_PULLUP);
pinMode(JOYSTICK_X_PIN, INPUT);
pinMode(JOYSTICK_Y_PIN, INPUT);
}
bool InputManager::pairBtnPressed()
{
return !digitalRead(PAIR_BTN_PIN);
}
bool InputManager::drawBtnPressed()
{
return !digitalRead(DRAW_BTN_PIN);
}
bool InputManager::sendBtnPressed()
{
return !digitalRead(SEND_BTN_PIN);
}
int8_t InputManager::getXAxis()
{
return map(analogRead(JOYSTICK_X_PIN), 0, 1023, JOYSTICK_MIN, JOYSTICK_MAX);
}
int8_t InputManager::getYAxis()
{
return map(analogRead(JOYSTICK_Y_PIN), 0, 1023, JOYSTICK_MIN, JOYSTICK_MAX);
} | true |
7de07b8616067ca8c71e179902f354cd4a61d174 | C++ | nDy/EscapeMadness | /EscapeMadness/lib/windows/Story.h | UTF-8 | 3,969 | 2.609375 | 3 | [] | no_license | #ifndef STORY_H_
#define STORY_H_
#include <SDL/SDL.h>
#include "Event.h"
#include "../common/Structure.h"
#include "../common/TextBubble.h"
#include "../common/Button.h"
#include <SDL/SDL_mixer.h>
class Story: public Event {
private:
SDL_Surface* Background;
TextBubble* tb;
int Current;
Mix_Music *music;
bool playFirst;
int currentTb;
public:
Story(int id) {
Current = id;
playFirst = false;
currentTb = 0;
}
bool Init() {
Background = Surface::Load("./res/Fondos/white.jpg");
tb = new TextBubble((char *) "Te sientes bien?", 1024 / 2, 0, 20);
if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 4096) == -1) {
return false;
}
music = Mix_LoadMUS("./res/OST/09 The Nurse Who Loved Me.wav");
if (Background == NULL) {
return false;
}
return true;
}
int Loop() {
if (Current != Structure::STORY) {
this->Cleanup();
}
if (playFirst == false) {
Mix_PlayMusic(music, -1);
playFirst = true;
}
return Current;
}
void Render(SDL_Surface* Display, float camera = 0) {
if (isNull()) {
this->Init();
}
Surface::Draw(Display, Background, 0, 0);
tb->render(Display);
}
bool isNull() {
if (Background == NULL) {
return true;
}
return false;
}
void Cleanup() {
SDL_FreeSurface(Background);
Background = NULL;
}
//Events
void OnInputFocus() {
}
void OnInputBlur() {
}
void OnKeyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
if (sym == SDLK_SPACE)
switch (currentTb) {
case 0:
this->tb->switchText((char*) "*Balbucea*");
this->tb->switchPos(0, 768/2);
this->currentTb++;
break;
case 1:
this->tb->switchText((char*) "No puedo verte asi");
this->tb->switchPos(1024/2, 0);
this->currentTb++;
break;
case 2:
this->tb->switchText((char*) "Que sucede?");
this->tb->switchPos(0, 768/2);
this->currentTb++;
break;
case 3:
this->tb->switchText((char*) "Necesitas salir de aqui");
this->tb->switchPos(1024/2, 0);
this->currentTb++;
break;
case 4:
this->tb->switchText((char*) "Pero...");
this->tb->switchPos(0, 768/2);
this->currentTb++;
break;
case 5:
this->tb->switchText((char*) "No, No hay tiempo para esto...");
this->tb->switchPos(1024/2, 0);
this->currentTb++;
break;
case 6:
this->tb->switchText((char*) "Que pretendes hacer con eso?");
this->tb->switchPos(0, 768/2);
this->currentTb++;
break;
case 7:
this->tb->switchText((char*) "No puedo estar aqui cuando despiertes");
this->tb->switchPos(1024/2, 0);
this->currentTb++;
break;
case 8:
this->tb->switchText((char*) "Por que?");
this->tb->switchPos(0, 768/2);
this->currentTb++;
break;
case 9:
this->tb->switchText((char*) "No es seguro... Para mi...");
this->tb->switchPos(1024/2, 0);
this->currentTb++;
break;
case 10:
Current = Structure::INGAME;
break;
}
}
void OnKeyUp(SDLKey sym, SDLMod mod, Uint16 unicode) {
}
void OnMouseFocus() {
}
void OnMouseBlur() {
}
void OnMouseMove(int mX, int mY, int relX, int relY, bool Left, bool Right,
bool Middle) {
}
void OnMouseWheel(bool Up, bool Down) {
} //Not implemented
void OnLButtonDown(int mX, int mY) {
}
void OnLButtonUp(int mX, int mY) {
}
void OnRButtonDown(int mX, int mY) {
}
void OnRButtonUp(int mX, int mY) {
}
void OnMButtonDown(int mX, int mY) {
}
void OnMButtonUp(int mX, int mY) {
}
void OnJoyAxis(Uint8 which, Uint8 axis, Sint16 value) {
}
void OnJoyButtonDown(Uint8 which, Uint8 button) {
}
void OnJoyButtonUp(Uint8 which, Uint8 button) {
}
void OnJoyHat(Uint8 which, Uint8 hat, Uint8 value) {
}
void OnJoyBall(Uint8 which, Uint8 ball, Sint16 xrel, Sint16 yrel) {
}
void OnMinimize() {
}
void OnRestore() {
}
void OnResize(int w, int h) {
}
void OnExpose() {
}
void OnExit() {
}
void OnUser(Uint8 type, int code, void* data1, void* data2) {
}
};
#endif /* STORY_H_ */
| true |
dd842cb00a17a53abb64c1cb6372c89e54655c03 | C++ | Mrhuangyi/leetcode-Solutions | /Cpp/Medium/151. 翻转字符串里的单词.cpp | UTF-8 | 3,603 | 3.890625 | 4 | [] | no_license | /*
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: "the sky is blue",
输出: "blue is sky the".
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
进阶: 请选用C语言的用户尝试使用 O(1) 空间复杂度的原地解法。
*/
class Solution {
public:
string reverseWords(string s) {
string res,temp;
reverse(s.begin(), s.end());
int len = s.size();
int j = 0;
while(j < len) {
while(s[j] == ' ') {
j++;
}
while(s[len-1] == ' ') {
len--;
}
if(s[j] != ' ' && s[len-1] != ' ') {
break;
}
}
for(int i = j; i < len; i++) {
while(s[i] != ' ' && i < len) {
temp += s[i];
i++;
}
if(s[i] == ' ' && i != len) {
reverse(temp.begin(), temp.end());
res += temp;
res += " ";
temp = "";
while(s[i+1] == ' ') {
i++;
}
}
}
reverse(temp.begin(), temp.end());
res += temp;
return res;
}
};
class Solution {
public:
void reverseWords(string &s) {
string res = "";
int i = s.length() - 1;
while(i >= 0) {
while(i >= 0 && s[i] == ' ') {
i--;
}
if(i < 0) {
break;
}
if(res.length() != 0) {
res.push_back(' ');
}
string temp = "";
while(i >= 0 && s[i] != ' ') {
temp = s[i] + temp;
i--;
}
res.append(temp);
}
s = res;
}
};
class Solution {
public:
void reverseWords(string &s) {
//string res = "";
int n = s.size();
int i = 0, j = 0, start = 0;
while(i < n) {
while(i < n && s[i] == ' ') {
i++;
}
if(i < n && j > 0) {
s[j++] = ' ';
}
start = j;
while(i < n && s[i] != ' ') {
s[j++] = s[i++];
}
reverse(s.begin() + start, s.begin() + j);
}
s.resize(j);
reverse(s.begin(), s.end());
}
};
//C language
void reverse(char *start,char *end)
{
while(end > start)
{
char temp = *start;
*start = *end;
*end = temp;
start++,end--;
}
}
void trim(char *S)
{
int count = 0;
int N = strlen(S);
int flag = 1;
for(int i=0;i<N;i++)
{
if(S[i] != ' ')
{
S[count++] = S[i];
flag = 0;
}
else
{
if(!flag)
{
S[count++] = S[i];
flag = 1;
}
}
}
if(count >= 1 && S[count-1] == ' ')
S[count-1] = '\0';
else
S[count] = '\0';
}
void reverseWords(char *S)
{
trim(S);
char *temp = S,*prev = S;
while(*temp)
{
temp++;
if(*temp == ' ')
{
reverse(prev,temp-1);
prev = temp+1;
}
else if(*temp == '\0')
{
reverse(prev,temp-1);
}
}
reverse(S,temp-1);
}
| true |
6cf2093e8885adb712d9e2eb046a4e5dfb06992b | C++ | nafisa11bd/My-Codeforces-AC-submissions | /i_am_miss_nobody/492B.cpp | UTF-8 | 547 | 2.53125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,l;
double d=0,f=0,g=0;
cin>>n>>l;
int p[n+1];
for(int i=0;i<n;i++)
{
cin>>p[i];
}
sort(p,p+n);
for(int i=0;i<n-1;i++)
{
if(abs(p[i]-p[i+1])>d)
{
d=abs(p[i]-p[i+1]);
}
}
//cout<<(float)d/2<<endl;
// if(p[0]!=0)
f=p[0]-0;
//if(p[n-1]!=l)
g=l-p[n-1];
//cout<<f<<" "<<g<<endl;
cout<<std::fixed << std::setprecision(9)<<(double)max(d/2,max(f,g))<<endl;
} | true |
4cc204f66dbef1e768a61a8879350cada444da48 | C++ | GaisaiYuno/My-OI-Code-1 | /1比赛题目/18.5.5专题训练/C.cpp | GB18030 | 905 | 2.84375 | 3 | [] | no_license | #include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#define maxn 100005
using namespace std;
int len[maxn];
void init(){
len[0]=0;
len[1]=1;
for(int i=2;i<maxn;i++){
len[i]=len[i-1]+log10(i)+1;
//iӴȵi-1ӴһiiijΪlog10(i)+1,Ҳ˵iӴȵi-1Ӵijȳlog10(i)+1
}
}
int t,n;
int main(){
init();
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int i=1;
while(n>0){
n-=len[i++];
}
i--;
if(n==0){
printf("%d\n",i%10);
continue;
}
n+=len[i];
int tmp=n;
for(i=1;i<=tmp;i++){
n-=(int)(log10(i)+1);
if(n<=0) break;
}
if(n==0){
printf("%d\n",i%10);
continue;
}
n+=log10(i)+1;
int digit[20];
memset(digit,0,sizeof(digit));
int ptr=0;
while(i>0){//iÿһλ
digit[ptr++]=i%10;
i/=10;
}
printf("%d\n",digit[ptr-n]);
}
}
| true |
5808a483b735323cf41adb0d188bd1bc76a8a923 | C++ | Harrix/Harrix-MathLibrary | /src/Оптимизация - свалка алгоритмов/HML_BinaryGeneticAlgorithmTwiceGenerations.cpp | UTF-8 | 18,511 | 2.59375 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | int HML_BinaryGeneticAlgorithmTwiceGenerations(int *Parameters, double (*FitnessFunction)(int*,int), int *VHML_ResultVector, double *VHML_Result)
{
/*
Генетический алгоритм с двойным количеством поколений для решения задач на бинарных строках.
На четных поколениях целевая функция высчитывается как среднеарифметическое родителей.
https://github.com/Harrix/HarrixOptimizationAlgorithms
Алгоритм оптимизации. Ищет максимум целевой функции FitnessFunction.
Входные параметры:
Parameters - Вектор параметров генетического алгоритма. Каждый элемент обозначает свой параметр:
[0] - длина бинарной хромосомы (определяется задачей оптимизации, что мы решаем);
[1] - число вычислений целевой функции (CountOfFitness);
[2] - тип селекции (TypeOfSel):
0 - ProportionalSelection (Пропорциональная селекция);
1 - RankSelection (Ранговая селекция);
2 - TournamentSelection (Турнирная селекция).
[3] - тип скрещивания (TypeOfCros):
0 - SinglepointCrossover (Одноточечное скрещивание);
1 - TwopointCrossover (Двухточечное скрещивание);
2 - UniformCrossover (Равномерное скрещивание).
[4] - тип мутации (TypeOfMutation):
0 - Weak (Слабая мутация);
1 - Average (Средняя мутация);
2 - Strong (Сильная мутация).
[5] - тип формирования нового поколения (TypeOfForm):
0 - OnlyOffspringGenerationForming (Только потомки);
1 - OnlyOffspringWithBestGenerationForming (Только потомки и копия лучшего индивида).
FitnessFunction - указатель на целевую функцию (если решается задача условной оптимизации, то учет ограничений должен быть включен в эту функцию);
VHML_ResultVector - найденное решение (бинарный вектор);
VHML_Result - значение целевой функции в точке, определенной вектором VHML_ResultVector.
Возвращаемое значение:
1 - завершил работу без ошибок. Всё хорошо.
0 - возникли при работе ошибки. Скорее всего в этом случае в VHML_ResultVector и в VHML_Result не содержится решение задачи.
Пример значений рабочего вектора Parameters:
Parameters[0]=50;
Parameters[1]=100*100;
Parameters[2]=2;
Parameters[3]=2;
Parameters[4]=1;
Parameters[5]=1;
*/
//Считываем из Parameters параметры алгоритма
int ChromosomeLength=Parameters[0];//Длина хромосомы
int CountOfFitness=Parameters[1];//Число вычислений целевой функции
int TypeOfSel=Parameters[2];//Тип селекции
int TypeOfCros=Parameters[3];//Тип скрещивания
int TypeOfMutation=Parameters[4];//Тип мутации
int TypeOfForm=Parameters[5];//Тип формирования нового поколения
//Проверим данные
if (ChromosomeLength<1) return 0;//Слишком маленькая длина хромосомы
if (CountOfFitness<1) return 0;//Слишком маленькое число вычислений целевой функции
if (!((TypeOfSel==0)||(TypeOfSel==1)||(TypeOfSel==2))) return 0;//Тип селекции указан не верно
if (!((TypeOfCros==0)||(TypeOfCros==1)||(TypeOfCros==2))) return 0;//Тип скрещивания указан не верно
if (!((TypeOfMutation==0)||(TypeOfMutation==1)||(TypeOfMutation==2))) return 0;//Тип мутации указан не верно
if (!((TypeOfForm==0)||(TypeOfForm==1))) return 0;//Тип формирования нового поколения указан не верно
//Теперь определим остальные параметры алгоритма, исходя из полученной информации
//Размер популяции и число поколений должны быть приблизительно равны (насколько это возможно)
int NumberOfGenerations=int(sqrt(double(CountOfFitness)));//Число поколений
int PopulationSize=int(CountOfFitness/NumberOfGenerations);//Размер популяции
int SizeOfTournament=2;//В стандартном генетическом алгоритме на бинарных строках размер турнира равен 2
//Переменные
int I,i,j;//Счетчики
int NumberOfMaximumFitness;//Номер лучшего индивида в текущей популяции
double MaximumFitness;//Значение целевой функции лучшего индивида в текущей популяции
double BestFitness;//Значение целевой функции лучшего индивида за всё время работы алгоритма
int NumberOfParent1;//Номер первого выбранного родителя
int NumberOfParent2;//Номер второго выбранного родителя
double ProbabilityOfMutation;//Вероятность мутации
//Для выполнения алгоритма требуются некоторые дополнительные массивы. Создадим их.
//Популяция индивидов
int **Population;
Population=new int*[PopulationSize];
for (i=0;i<PopulationSize;i++) Population[i]=new int[ChromosomeLength];
//Популяция потомков
int **ChildrenPopulation;
ChildrenPopulation=new int*[PopulationSize];
for (i=0;i<PopulationSize;i++) ChildrenPopulation[i]=new int[ChromosomeLength];
//Массив значений целевой функции индивидов
double *Fitness;
Fitness=new double[PopulationSize];
//Массив значений целевой функции потомков
double *ChildrenFitness;
ChildrenFitness=new double[PopulationSize];
//Массив для хранения произвольного индивида
int *TempIndividual;
TempIndividual=new int[ChromosomeLength];
//Массив для хранения лучшего индивида за всё время работы алгоритма
int *BestIndividual;
BestIndividual=new int[ChromosomeLength];
//Для пропорциональной и ранговой селекции нужен массив вероятностей выбора индивидов
double *VectorOfProbability;
VectorOfProbability=new double[PopulationSize];
//Для ранговой селекции нужен массив рангов индивидов
double *Rank;
Rank=new double[PopulationSize];
//Для турнирной селекции нужен служебный массив, содержащий информация о том, в турнире или нет индивид;
int *Taken;
Taken=new int[PopulationSize];
//Массив для хранения первого родителя
int *Parent1;
Parent1=new int[ChromosomeLength];
//Массив для хранения второго родителя
int *Parent2;
Parent2=new int[ChromosomeLength];
//Массив для хранения потомка от скрещивания двух родителей
int *Child;
Child=new int[ChromosomeLength];
//Массивы для сохранения информации, кто родитель у потомка
int *MemoryFirstParent;
MemoryFirstParent=new int[PopulationSize];
int *MemorySecondParent;
MemorySecondParent=new int[PopulationSize];
//Массивы для сохранения информации, какая пригодность была у родителей
double *MemoryFitnessFirstParent;
MemoryFitnessFirstParent=new double[PopulationSize];
double *MemoryFitnessSecondParent;
MemoryFitnessSecondParent=new double[PopulationSize];
//Инициализация начальной популяции
HML_RandomBinaryMatrix(Population,PopulationSize,ChromosomeLength);
//Вычислим значение целевой функции для каждого индивида
for (i=0;i<PopulationSize;i++)
{
//Копируем индивида во временного индивида, так как целевая функция работает с вектором, а не матрицей
HML_MatrixToRow(Population,TempIndividual,i,ChromosomeLength);
try
{
Fitness[i]=FitnessFunction(TempIndividual,ChromosomeLength);
}
catch(...)
{
return 0;//Генетический алгоритм не смог посчитать значение целевая функции индивида
}
}
//Определим наилучшего индивида и запомним его
NumberOfMaximumFitness=HML_NumberOfMaximumOfVector(Fitness,PopulationSize);
MaximumFitness=HML_MaximumOfVector(Fitness,PopulationSize);
HML_MatrixToRow(Population,BestIndividual,NumberOfMaximumFitness,ChromosomeLength);//Запоминаем индивида
BestFitness=MaximumFitness;//Запоминаем его значение целевой функции
for (I=1;I<NumberOfGenerations*2-1;I++)
{//////////////////// ГЛАВНЫЙ ЦИКЛ ///////////////////////
//Подготовка массивов для оператора селекции
if (TypeOfSel==1)
{
//Для ранговой селекции нужен массив рангов индивидов
HML_MakeVectorOfRankForRankSelection(Fitness,Rank,PopulationSize);
//Для ранговой селекции нужен массив вероятностей выбора индивидов из рангов
HML_MakeVectorOfProbabilityForRanklSelection(Rank,VectorOfProbability,PopulationSize);
}
if (TypeOfSel==0)//Для пропорциональной нужен массив вероятностей выбора индивидов
HML_MakeVectorOfProbabilityForProportionalSelectionV2(Fitness,VectorOfProbability,PopulationSize);
for (j=0;j<PopulationSize;j++)
{//Формирование популяции потомков
if (TypeOfSel==0)//Пропорциональная селекция
{
//Выбираем двух родителей (точнее их номера)
NumberOfParent1=HML_ProportionalSelectionV2(VectorOfProbability,PopulationSize);
NumberOfParent2=HML_ProportionalSelectionV2(VectorOfProbability,PopulationSize);
}
if (TypeOfSel==1)//Ранговая селекция
{
//Выбираем двух родителей (точнее их номера)
NumberOfParent1=HML_RankSelection(VectorOfProbability,PopulationSize);
NumberOfParent2=HML_RankSelection(VectorOfProbability,PopulationSize);
}
if (TypeOfSel==2)//Турнирная селекция
{
//Выбираем двух родителей (точнее их номера)
NumberOfParent1=HML_TournamentSelection(Fitness,SizeOfTournament,Taken,PopulationSize);
NumberOfParent2=HML_TournamentSelection(Fitness,SizeOfTournament,Taken,PopulationSize);
}
//Сохраняем информацию кто родитель у потомка
MemoryFirstParent[j]=NumberOfParent1;
MemorySecondParent[j]=NumberOfParent2;
//Сохраняем информацию пригодностей родителей
MemoryFitnessFirstParent[j]=Fitness[NumberOfParent1];
MemoryFitnessSecondParent[j]=Fitness[NumberOfParent2];
//Копируем родителей из популяции
HML_MatrixToRow(Population,Parent1,NumberOfParent1,ChromosomeLength);//Первого родителя
HML_MatrixToRow(Population,Parent2,NumberOfParent2,ChromosomeLength);//Второго родителя
//Теперь путем скрещивания получаем потомка
if (TypeOfCros==0)//Одноточечное скрещивание
HML_SinglepointCrossover(Parent1,Parent2,Child,ChromosomeLength);
if (TypeOfCros==1)//Двухточечное скрещивание
HML_TwopointCrossover(Parent1,Parent2,Child,ChromosomeLength);
if (TypeOfCros==2)//Равномерное скрещивание
HML_UniformCrossover(Parent1,Parent2,Child,ChromosomeLength);
//Переместим потомка в массив потомков
HML_RowToMatrix(ChildrenPopulation,Child,j,ChromosomeLength);
}//Формирование популяции потомков
//Мутируем получившуюся популяцию потомков
//Но вначале определим вероятность мутации
if (TypeOfMutation==0)//Слабая
ProbabilityOfMutation=1./(3.*double(ChromosomeLength));
if (TypeOfMutation==1)//Средняя
ProbabilityOfMutation=1./double(ChromosomeLength);
if (TypeOfMutation==2)//Сильняя
ProbabilityOfMutation=HML_Min(3./double(ChromosomeLength),1.);
HML_MutationBinaryMatrix(ChildrenPopulation,ProbabilityOfMutation,PopulationSize,ChromosomeLength);//Мутируем
if (I%2==0)
{
//Вычислим значение целевой функции для каждого потомка
for (i=0;i<PopulationSize;i++)
{
//Копируем потомка во временного индивида, так как целевой функция работает с вектором, а не матрицей
HML_MatrixToRow(ChildrenPopulation,TempIndividual,i,ChromosomeLength);
try
{
ChildrenFitness[i]=FitnessFunction(TempIndividual,ChromosomeLength);
}
catch(...)
{
return 0;//Генетический алгоритм не смог посчитать значение целевой функции потомка
}
}
//Определим наилучшего потомка и запомним его
MaximumFitness=HML_MaximumOfVector(ChildrenFitness,PopulationSize);
//Является ли лучшее решение на данном поколении лучше лучшего решения за всё время работы алгоритма
if (MaximumFitness>BestFitness)
{
//Если всё-таки лучше
NumberOfMaximumFitness=HML_NumberOfMaximumOfVector(ChildrenFitness,PopulationSize);
HML_MatrixToRow(ChildrenPopulation,BestIndividual,NumberOfMaximumFitness,ChromosomeLength);//Запоминаем индивида
BestFitness=MaximumFitness;//Запоминаем его значение целевой функции
}
}
else
{
//Вычислим значение целевой функции для каждого потомка
for (i=0;i<PopulationSize;i++)
{
ChildrenFitness[i]=(MemoryFitnessFirstParent[i]+MemoryFitnessSecondParent[i])/2.;
}
}
//Теперь сформируем новое поколение
if (TypeOfForm==0)//Только потомки
{
HML_MatrixToMatrix(ChildrenPopulation,Population,PopulationSize,ChromosomeLength);
HML_VectorToVector(ChildrenFitness,Fitness,PopulationSize);
}
if (TypeOfForm==1)//Только потомки и копия лучшего индивида
{
HML_MatrixToMatrix(ChildrenPopulation,Population,PopulationSize,ChromosomeLength);
HML_RowToMatrix(Population,BestIndividual,0,ChromosomeLength);
HML_VectorToVector(ChildrenFitness,Fitness,PopulationSize);
Fitness[0]=BestFitness;
}
}//////////////////// ГЛАВНЫЙ ЦИКЛ ///////////////////////
//Генетический алгоритм закончил свою работу
//Выдадим найденное лучшее решение за время запуска алгоритма и его значение целевой функции
HML_VectorToVector(BestIndividual,VHML_ResultVector,ChromosomeLength);
*VHML_Result=BestFitness;
//Удалим все дополнительные массивы
for (i=0;i<PopulationSize;i++) delete [] Population[i];
delete [] Population;
for (i=0;i<PopulationSize;i++) delete [] ChildrenPopulation[i];
delete [] ChildrenPopulation;
delete [] Fitness;
delete [] ChildrenFitness;
delete [] TempIndividual;
delete [] BestIndividual;
delete [] VectorOfProbability;
delete [] Rank;
delete [] Taken;
delete [] Parent1;
delete [] Parent2;
delete [] Child;
delete [] MemoryFirstParent;
delete [] MemorySecondParent;
delete [] MemoryFitnessFirstParent;
delete [] MemoryFitnessSecondParent;
return 1;//Всё успешно
} | true |
3c9f855a92aabf9cf87c1d92d1d02d668d59cfd5 | C++ | BlakeJordan/Compilers_p3 | /symbol_table.cpp | UTF-8 | 1,993 | 3.234375 | 3 | [] | no_license | #include "symbol_table.hpp"
namespace lake{
ScopeTable::ScopeTable(){
symbols = new HashMap<std::string, SemSymbol *>();
}
bool ScopeTable::LookUp(std::string id) {
return(symbols->count(id) > 0);
}
std::string ScopeTable::GetType(std::string id) {
return symbols->find(id)->second->GetType();
}
bool ScopeTable::AddSymbol(std::string id, SemSymbol * symbol) {
if (!LookUp(id)) {
symbols->insert({{id, symbol}});
return true;
}
else {
return false;
}
}
SymbolTable::SymbolTable(){
//TODO: implement the list of hashtables approach
// to building a symbol table:
// Upon entry to a scope a new scope table will be
// entered into the front of the chain and upon exit the
// latest scope table will be removed from the front of
// the chain.
scopeTableChain = new std::list<ScopeTable *>();
}
void SymbolTable::AddScope() {
scopeTableChain->push_front(new ScopeTable());
}
void SymbolTable::DropScope() {
scopeTableChain->pop_front();
}
bool SymbolTable::LookUp(std::string id) {
int tables = scopeTableChain->size();
for(ScopeTable * scopeTable: * scopeTableChain) {
if(scopeTable->LookUp(id)) {
return true;
}
}
return false;
}
std::string SymbolTable::GetType(std::string id) {
return GetTable(id)->GetType(id);
}
bool SymbolTable::AddSymbol(std::string id, SemSymbol * symbol) {
return scopeTableChain->front()->AddSymbol(id, symbol);
}
ScopeTable * SymbolTable::GetTable(std::string id) {
for(auto table: *scopeTableChain) {
if(table->LookUp(id)) {
return table;
}
}
return nullptr;
}
SemSymbol::SemSymbol(){}
void SemSymbol::SetId(std::string id) {
m_id = id;
}
std::string SemSymbol::GetId() {
return m_id;
}
void SemSymbol::SetType(std::string type) {
m_type = type;
}
std::string SemSymbol::GetType() {
return m_type;
}
void SemSymbol::SetKind(std::string kind) {
m_kind = kind;
}
std::string SemSymbol::GetKind() {
return m_kind;
}
}
| true |
0acc532cad99b8b73e6f1ee981c8581e58ee089d | C++ | Maigo/gea | /gea/libs/gea_core/src/gea/core/pattern/delegate_base.inl | UTF-8 | 1,953 | 2.59375 | 3 | [] | no_license | #pragma once
// header include
#include "delegate_base.h"
namespace gea {
// ------------------------------------------------------------------------- //
// delegate_base //
// ------------------------------------------------------------------------- //
template <typename RET, typename... ARGS>
inline delegate_base<RET(ARGS...)>::function_data::function_data() : self(0), function(nullptr) {}
template <typename RET, typename... ARGS>
inline delegate_base<RET(ARGS...)>::function_data::function_data(const function_data& other) : self(other.self), function(other.function) {}
template <typename RET, typename... ARGS>
inline delegate_base<RET(ARGS...)>::function_data::function_data(const uintptr_t other_self, function_t other_function) : self(other_self), function(other_function) {}
template <typename RET, typename... ARGS>
inline void delegate_base<RET(ARGS...)>::function_data::assign(const function_data& other) {
self = other.self;
function = other.function;
}
template <typename RET, typename... ARGS>
inline void delegate_base<RET(ARGS...)>::function_data::assign(const uintptr_t other_self, function_t other_function) {
self = other_self;
function = other_function;
}
template <typename RET, typename... ARGS>
inline const bool delegate_base<RET(ARGS...)>::function_data::is_empty() const { return (function == nullptr); }
template <typename RET, typename... ARGS>
inline const bool delegate_base<RET(ARGS...)>::function_data::operator== (function_data& other) const {
return (self == other.self) && (function == other.function);
}
template <typename RET, typename... ARGS>
inline const bool delegate_base<RET(ARGS...)>::function_data::operator!= (function_data& other) const {
return (self != other.self) || (function != other.function);
}
// ------------------------------------------------------------------------- //
} // namespace gea //
| true |
6cc61524073f241c9a58a8e120d09b4898236ed7 | C++ | Lawrenceh/AC_Monster | /LeetCode/Swap Nodes in Pairs.cpp | UTF-8 | 1,643 | 3.4375 | 3 | [] | no_license | // recursive version
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if(!head||!head->next) return head;
ListNode *reverse_head = head->next;
ListNode *next_pair_head = reverse_head->next;
reverse_head->next = head;
head->next = swapPairs(next_pair_head);
return reverse_head;
}
};
// non-recursive version BF
ListNode *swapPairs(ListNode *head) {
if(head == nullptr)
return nullptr;
ListNode *base = head->next != nullptr ? head->next : head;
ListNode *currPairFirst = head, *currPairSecond = head->next, *prevPairSecond = nullptr;
while(currPairFirst != nullptr && currPairSecond != nullptr) {
ListNode *nextPairFirst = currPairSecond->next;
currPairSecond->next = currPairFirst;
currPairFirst->next = nextPairFirst;
if(prevPairSecond != nullptr)
prevPairSecond->next = currPairSecond;
prevPairSecond = currPairFirst;
if(nextPairFirst == nullptr)
break;
currPairFirst = nextPairFirst;
currPairSecond = nextPairFirst->next;
}
return base;
}
// non-recursive version DOUBLE POINTER
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
ListNode **p = &head;
while (*p && (*p)->next) {
ListNode *t = (*p)->next;
(*p)->next = t->next;
t->next = *p;
*p = t; // adjust the temporary wrong pointer
p = &(*p)->next->next; // make p point the pointer to the unprocessed first node! (just like pointing to the head node)
}
return head;
}
};
| true |
e571afada4efd820810306863f7870282846e5be | C++ | OSgoodYZ/algorithm_practice | /gcdlcm.cpp | UHC | 1,254 | 3.6875 | 4 | [] | no_license | #include<vector>
#include<iostream>
using namespace std;
//ִ ִ ϴ¹
vector<int> gcdlcm(int a, int b)
{
vector<int> answer;
int small=a, big=b;
int sol1=1, sol2=a*b;
answer.resize(2);
if (a > b)
{
small = b;
big = a;
}
else if(a == b)
{
sol1 = a;
sol2 = a;
}
else
{
small = a;
big = b;
}
sol1 = 1;
sol2 = a*b;
for (int i = small ; i>1; i--)
{
if (small%i == 0)
{
if (big%i == 0)
{
sol1 = i;
break;
}
}
}
sol2 = (small / sol1)*(big / sol1)*sol1;
answer[0] = sol1;
answer[1] = sol2;
return answer;
}
int main()
{
int a = 3, b = 12;
vector<int> testAnswer = gcdlcm(a, b);
cout << testAnswer[0] << " " << testAnswer[1];
}
/*
//ٸǮ
#include<vector>
#include<iostream>
using namespace std;
vector<int> gcdlcm(int a,int b)
{
int temp = a;
if(a > b){
a = b;
b = temp;
}
vector<int> answer;
for(int i = a; i > 0; i--){
if(((a%i) == 0) && ((b%i) == 0)){
answer.push_back(i);
answer.push_back((a*b)/i);
break;
}
}
return answer;
}
int main()
{
int a=3, b=12;
vector<int> testAnswer = gcdlcm(a,b);
cout<<testAnswer[0]<<" "<<testAnswer[1];
}
*/ | true |
f7a747a02b3e79a29e62b31498a4279197ddaea6 | C++ | hanifwihananto/ksn-p | /ksn-p_2021/b3.cpp | UTF-8 | 367 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
// N : jumlah vitamin
// M : jumlah uang
int N, M;
cin >> N >> M;
// H : Harga
// K : kandungan
// D : dosis
int H, K, D;
int tinggi, rendah;
// D = 1; Tinggi
// D = 0; Rendah
if(D == 1){
D = tinggi;
} else {
D = rendah;
}
int i, j;
for(i = 0; i <= N; i++){
cout << i;
}
}
| true |
80c4613e868ae2b050e28cabaea4eafb075541db | C++ | HururuekChapChap/Winter_Algorithm | /Cut_Lan_Line-1654/Cut_Lan_Line-1654/main.cpp | UTF-8 | 1,832 | 3.21875 | 3 | [] | no_license | //
// main.cpp
// Cut_Lan_Line-1654
//
// Created by yoon tae soo on 2020/02/07.
// Copyright © 2020 yoon tae soo. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/*
이분 탐색 문제였다. 오늘은 정말 아무 생각도 하기 싫어서 잘 풀지 못했는데,
아이디어에서 다소 차이가 있었고 별로 문제 풀고 싶은 마음이 없었다.
오늘은 좀 슬럼프가 심한 날이다 ㅎㅎㅎ
방법은 간단하다.
1 부터 가장 높은 숫자에서 쭉 탐색해주는 방식인데,
내가 이분탐색에 대해서 연습을 많이 하지 않아, 다소 체감이 어려웠고, 깊게 생각하고 싶은 마음이 별로 없었다.
다시 이분 탐색에 대해서 공부해 보면서 지식을 늘려가야 겠다.
*/
vector<int> v;
long long int Bineary_Search(long long int start , long long int end, int K){
long long int mid = 0;
long long int total = 0;
long long int anw = 0;
while(start <= end){
//cout << start << " start " << end << endl;
mid = (start + end)/2;
total = 0;
for(int i =0; i<v.size(); i++){
total += v[i]/mid;
}
if(total >= K){
start = mid +1;
if(anw < mid){
anw = mid;
}
}
else if(total <K){
end = mid-1;
}
}
return anw;
}
int main(int argc, const char * argv[]) {
int N, K;
cin >> N >> K;
for(int i = 0; i<N; i++){
int item;
cin >> item;
v.push_back(item);
}
sort(v.begin(), v.end());
long long int low = 1;
long long int hight = v[N-1];
cout << Bineary_Search(low,hight,K);
return 0;
}
| true |
697c5c9440c07ef15e45cbea904ce0bc19b4f3b1 | C++ | Yozer/SatSolvers | /solvers/riss/classifier-src/FeaturesWriter.h | UTF-8 | 758 | 2.5625 | 3 | [
"LicenseRef-scancode-other-permissive"
] | permissive | /*
* FeaturesWriter.h
*
* Created on: Jan 4, 2014
* Author: gardero
*/
#include <ostream>
#include <string>
#ifndef FEATURESWRITER_H_
#define FEATURESWRITER_H_
using namespace std;
class FeaturesWriter {
private:
ostream& output;
int featuresNumber;
int featuresCount;
int timeout;
public:
FeaturesWriter(int afeaturesNumber, int atimeout, ostream& aoutput);
virtual ~FeaturesWriter();
const ostream& getOutput() const {
return output;
}
void writeFeature(double value);
void fillWithUnknown();
void close();
int getFeaturesNumber() const {
return featuresNumber;
}
void setFeaturesNumber(int featuresNumber) {
this->featuresNumber = featuresNumber;
}
string getTimeoutDefinition();
};
#endif /* FEATURESWRITER_H_ */
| true |
adba7bbbc5baf21e07db3e93c36a7494329e05a1 | C++ | usman-tahir/rooks-guide-c-plus-plus | /rooks-guide-tutorials/chapter_10_exercises.cpp | UTF-8 | 483 | 3.921875 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int input_one, input_two;
cout << "Enter a number: ";
cin >> input_one;
cout << "\nEnter a number: ";
cin >> input_two;
if (input_one > input_two) {
cout << input_one << " is greater than " << input_two << endl;
} else if (input_one < input_two) {
cout << input_two << " is greater than " << input_one << endl;
} else {
cout << input_one << " is equal to " << input_two << endl;
}
return 0;
} | true |
2d91cc3a41984b1d8b2e90e77f0ecc519b4fda0d | C++ | singhdharmveer311/PepCoding | /Level-1/14. LinkedList/Reverse-in-size-of-K-Groups.cpp | UTF-8 | 6,148 | 3.359375 | 3 | [
"Apache-2.0"
] | permissive | #include <bits/stdc++.h>
using namespace std;
class node{
public:
int val;
node* next;
};
void insert_at_tail(node *&head,int val){
if(head==NULL){
node *newnode = new node;
newnode->val=val;
newnode->next=NULL;
head=newnode;
}
else{
node *newnode = new node;
newnode->val=val;
newnode->next=NULL;
node *temp = head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next = newnode;
}
}
void insertion_at_head(node* &head,int val){
node *newnode = new node;
newnode->val=val;
newnode->next=NULL;
if(head==NULL){
head=newnode;
}
else{
newnode ->next =head;
head = newnode;
}
}
void print (node* &head){
node *temp =head;
if(head==NULL){
cout << endl;
return;
}
else{
while(temp!=NULL){
cout<<temp->val<<" ";
temp=temp->next;
}
cout << endl;
}
}
void deletion_at_head(node* &head){
if(head==NULL) return;
node *temp=head;
head=head->next;
delete temp;
}
void deletion_at_tail(node*& head){
if(head==NULL) return;
node* previous=NULL;
node* temp=head;
while(temp->next!=NULL){
previous=temp;
temp=temp->next;
}
previous->next = NULL;
delete temp;
}
void last(node* &head){
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
cout << temp->val << endl;
}
int size(node* &head){
int cnt=0;
node* temp=head;
while(temp!=NULL){
temp=temp->next;
cnt++;
}
return cnt;
}
int first(node* &head){
if(head==NULL){
return -1;
}
return head->val;
}
void getAt(node* &head,int p){
if(head==NULL){
cout << "List is Empty" << endl;
return;
}
int cnt=0;
node* temp=head;
while(cnt < p){
cnt++;
temp=temp->next;
}
cout << temp->val << endl;
}
void addAt(node* &head,int pos,int data){
if(pos==0){
insertion_at_head(head,data);
return;
}
node* newnode=new node;
newnode->val=data;
int cnt=0;
node* temp=head;
while(cnt<pos-1){
cnt++;
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
// }
}
void removeAt(node* &head,int p){
if(head==NULL){
cout << "List is empty" << endl;
return;
}
else if(p==0){
deletion_at_head(head);
}
else{
node* temp=head;
int cnt=0;
while(cnt<p-1){
temp=temp->next;
cnt++;
}
node* t=temp->next;
temp->next=t->next;
free(t);
return;
}
}
void mid(node* &head){
if(head==NULL){
return;
}
else{
node*temp1=head;
node*temp2=head;
while(temp2->next!=NULL && temp2->next->next!=NULL){
temp2=temp2->next->next;
// if(temp2==NULL){
// break;
// }
temp1=temp1->next;
}
cout << temp1->val << endl;
}
}
int kthNodefromLast(node* &head,int k){
node *temp1=head;
node *temp2=head;
for(int i=0;i<k;i++){
temp2=temp2->next;
}
while(temp2->next!=nullptr){
temp2=temp2->next;
temp1=temp1->next;
}
return temp1->val;
}
void removeDuplicates(node* &head){
node* temp1=head;
node* temp2=head;
map<int,int> mp;
while(temp2!=nullptr){
mp[temp2->val]++;
if(mp[temp2->val]>1){
temp1->next=temp2->next;
temp2=temp2->next;
}
else{
temp1=temp2;
temp2=temp2->next;
}
}
}
void displayReverse(node* &head){
if(!head){
return;
}
displayReverse(head->next);
cout << head->val << " ";
}
void oddEven(node* &head){
node* odd=NULL,*even=NULL;
node* temp=head;
while(temp!=NULL){
if(temp->val%2==0){
if(even==NULL){
node* nn=new node();
nn->val= temp->val;
nn->next=NULL;
even=nn;
}
else{
node* nn=new node();
nn->val= temp->val;
nn->next=NULL;
node*te=even;
while(te->next!=NULL){
te=te->next;
}
te->next=nn;
}
}
else{
if(odd==NULL){
node* nn=new node();
nn->val= temp->val;
nn->next=NULL;
odd=nn;
}
else{
node* nn=new node();
nn->val= temp->val;
nn->next=NULL;
node*te=odd;
while(te->next!=NULL){
te=te->next;
}
te->next=nn;
}
}
deletion_at_head(temp);
}
if(odd!=NULL){
head=odd;
node* tt=odd;
while(tt->next!=NULL){
tt=tt->next;
}
tt->next=even;
}
else{
head=even;
}
print(head);
}
node* kreverse(node* &head,int k){
node* curr=head,*prev=NULL,*nex=NULL;
node* tem=head;
int len=0;
while(tem!=NULL){
tem=tem->next;
len++;
}
if(k>=len){
return head;
}
int count=0;
while(curr!=NULL & count<k){
nex=curr->next;
curr->next=prev;
prev=curr;
curr=nex;
count++;
}
if(nex!=NULL){
head->next=kreverse(nex,k);
}
return prev;
}
int main(){
node* head=NULL;
int n;
cin >> n;
for(int i=0;i<n;i++){
int x;
cin >> x;
insert_at_tail(head ,x);
}
int k,a,b;
cin >>k>> a >> b;
if(head!=NULL){
print(head);
}
node* point=kreverse(head,k);
//cout <<"";
print(point);
insert_at_tail(point,b);
insertion_at_head(point,a);
print(point);
} | true |
edef1171c0cbc72552a8f3b342892d434ec89ec1 | C++ | Anubhav12345678/competitive-programming | /EVENARRAYCODEFORCESVVVVVVVVVVVVVVVVVVVVVIMP.cpp | UTF-8 | 1,402 | 3.28125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#include<vector>
/*
You are given an array a[0…n−1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0≤i≤n−1) the equality imod2=a[i]mod2 holds, where xmod2 is the remainder of dividing x by 2.
For example, the arrays [0,5,2,1] and [0,17,0,3] are good, and the array [2,4,6,7] is bad, because for i=1, the parities of i and a[i] are different: imod2=1mod2=1, but a[i]mod2=4mod2=0.
In one move, you can take any two elements of the array and swap them (these elements are not necessarily adjacent).
Find the minimum number of moves in which you can make the array a good, or say that this is not possible.
*/
ll solve(vector<ll> &v)
{
ll i,j,k,l,n=v.size();
if(n==1)
{
if(v[0]%2==0)
return 0;
return -1;
}
vector<ll> e,o;
for(i=0;i<n;i++)
{
// cout<<"i = "<<i<<" v["<<i<<"] = "<<v[i]<<endl;
if(i%2==0&&v[i]%2==1) e.push_back(v[i]);
if(i%2==1&&v[i]%2==0) o.push_back(v[i]);
}
if(o.size()!=e.size()) return -1;
return o.size();
}
int main() {
ll i,j,k,l,n,t;
cin>>t;
while(t--)
{
cin>>n;
vector<ll> v(n);
for(i=0;i<n;i++) cin>>v[i];
cout<<solve(v)<<endl;
}
// your code goes here
return 0;
} | true |
03eadefb323aee97f77c4df3c5a2ef950d325bc1 | C++ | Dir-MaGaSe/Portafolio_ManuelGallardo | /Portafolio 2 - Ejercicio 16.cpp | ISO-8859-1 | 896 | 3.640625 | 4 | [] | no_license | //Nombre: Manuel Sebastin Gallardo Vsquez
//Canet: GV100520
#include<iostream>
#include<string>
using namespace std;
const string Autor = "Manuel Sebastian Gallardo Vasquez";
const string Carnet = "GV100520";
void imprimirArreglo(int array[], int size){
for(int i=0; i<size; ++i){
cout<<" | "<<array[i];
}
cout<<" | \n";
}
void ordenamientoBurbuja(int array[], int size){
for(int paso=0; paso<size-1; ++paso){
for(int i=0; i<size-paso-1; ++i){
if(array[i]> array[i+1]){
int temporal = array[i];
array[i] = array[i+1];
array[i+1] = temporal;
}
}
}
}
int main(){
int data[] = {-3,41,0,15,-9,7,5,55};
int size = sizeof(data)/sizeof(data[0]);
cout<<"Arreglo inicial:\n";
imprimirArreglo(data, size);
ordenamientoBurbuja(data, size);
cout<<"Arreglo ordenado de forma ascendente:\n";
imprimirArreglo(data, size);
cout<<"\nAutor: "<<Autor<<"\tCarnet: "<<Carnet<<endl;
return 0;
}
| true |
9d581f39fc7269f9664bd7bc1e31fa56179ffb2b | C++ | TimKingNF/leetcode | /editor/CodingInterviewGuide/CIG_1_2003.hpp | UTF-8 | 1,284 | 3.140625 | 3 | [] | no_license | //
// Created by timking.nf@foxmail.com on 2021/2/2.
//
#ifndef LEETCODE_CIG_1_2003_HPP
#define LEETCODE_CIG_1_2003_HPP
#include "header.h"
namespace CIG_1_2003 {
struct ListNode {
int val;
ListNode *prev;
ListNode *next;
ListNode() : val(0), prev(nullptr), next(nullptr) {}
ListNode(int x) : val(x), prev(nullptr), next(nullptr) {}
ListNode(int x, ListNode *prev, ListNode *next) : val(x), prev(prev), next(next) {}
};
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (!head || n < 1) return nullptr; // 无效参数
ListNode *cur = head;
while (cur) {
cur = cur->next;
--n;
}
if (n > 0) return head; // 说明链表不够长, 没有倒数第 n 个节点
if (n == 0) return head->next; // 刚好就是头结点
cur = head;
while (++n != 0) {
cur = cur->next;
}
// 此时 cur 就是要删除节点的前一个节点
// 倒数第 n 个节点的前一个节点是正数 len-n 节点, 第一次遍历后 n = n - len < 0
// 第二次遍历 ++n, 直到 n == 0, 此时会停在 len-n 节点
ListNode *deleted = cur->next;
if (deleted->next) {
deleted->next->prev = cur;
}
cur->next = deleted->next;
return head;
}
};
};
#endif // LEETCODE_CIG_1_2003_HPP | true |
d1573504920584b1c14d814cf0b47b6e27b32cd8 | C++ | WShabti-Team/WShabtiPict | /wshabtilib/oracle-generator/oracle-generator.h | UTF-8 | 1,338 | 3.1875 | 3 | [
"MIT"
] | permissive | #ifndef __ORACLE_GENERATOR_H__
#define __ORACLE_GENERATOR_H__
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Takes a vector of oracles to check if AT LEAST one oracle is expressed as interval (e.g 11.0:0.12)
*
* INPUT:
* vector of string (oracles)
*
* OUTPUT:
* TRUE (FALSE): there's at least one (there's no) oracle expressed as interval
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
bool check_interval(std::vector<std::string> oracle);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Takes a csv input file with oracles (some could be specified as intervals) (e.g parameter1, parameter2, parameter3)
* Creates a new output file containing appending oracle FOR EACH ROW (and delta if interval is specified) (e.g parameter1, parameter2, parameter3, oracle, (delta) )
* (
* e.g row:1,3 oracle 4 -> 1,3,4
* row:1,3 oracle 4:5 -> 1,3,4,5
* )
*
* INPUT:
*
* OUTPUT:
*
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////////
void append_oracle_to_csv(std::vector<std::string> oracle, std::string input_file_path, std::string output_file_path);
#endif | true |
bae30ec34456705ff04f5b92768548acf1797130 | C++ | antifork/awgn | /codes++/probe.hh | UTF-8 | 2,348 | 2.625 | 3 | [] | no_license | /* $Id$ */
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <bonelli@antifork.org> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Nicola Bonelli
* ----------------------------------------------------------------------------
*/
#ifndef PROBE_HH
#define PROBE_HH
#include <iostream>
namespace generic
{
#define probe_dump(x) std::cout << x << " :" << this << ": " << __PRETTY_FUNCTION__ << '\n'
struct probe
{
probe()
{
probe_dump("[C]");
}
probe(const probe &)
{
probe_dump("[!]");
}
probe &operator=(const probe &)
{
probe_dump("[!]");
return *this;
}
template <typename T1>
probe(const T1 &)
{
probe_dump("[c]");
}
template <typename T1, typename T2>
probe(const T1 &, const T2 &)
{
probe_dump("[c]");
}
template <typename T1, typename T2, typename T3>
probe(const T1 &, const T2 &, const T3 &)
{
probe_dump("[c]");
}
template <typename T1, typename T2, typename T3,
typename T4>
probe(const T1 &, const T2 &, const T3 &,
const T4 &)
{
probe_dump("[c]");
}
template <typename T1, typename T2, typename T3,
typename T4, typename T5>
probe(const T1 &, const T2 &, const T3 &,
const T4 &, const T5 &)
{
probe_dump("[c]");
}
template <typename T1, typename T2, typename T3,
typename T4, typename T5, typename T6>
probe(const T1 &, const T2 &, const T3 &,
const T4 &, const T5 &, const T6 &)
{
probe_dump("[c]");
}
~probe()
{
probe_dump("[d]");
}
friend std::ostream &
operator<<(std::ostream &o, const probe &that)
{
o << "<<probe:" << &that << ">>";
return o;
}
};
} // namespace generic
#endif /* PROBE_HH */
| true |
fd9abf57d88e4b01abd1f01c62e5f59c8191e042 | C++ | deepakantony/competitive_programming | /project_euler/p1_to_p67/p38_pandigital_max_concat.cpp | UTF-8 | 1,317 | 3.515625 | 4 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <bitset>
using namespace std;
int reverse(int n) {
int rev = 0;
while(n > 0) {
rev = rev*10+n%10;
n /= 10;
}
return rev;
}
int get_pandigital(int num, int n) {
int pandigital = 0;
for(int i = 1; i <= n; i++) {
int prod = reverse(num*i);
do {
pandigital = pandigital*10 + (prod%10);
}while((prod=prod/10)>0);
}
return pandigital;
}
void display_pandigital(int num, int n, int pandigital) {
for(int i = 1; i <= n; i++)
cout << num << " x " << i <<"\t" << ": " << num*i << endl;
cout << "Pandigital: " << pandigital << endl;
}
int pandigital_product(int n) {
bitset<9> digit_cov;
int tot_digits = 0;
int i = 1;
while(tot_digits < 9) {
int prod = i * n;
while(prod > 0) {
int dig = prod%10;
if(dig == 0) return 0;
if(digit_cov[dig-1]) return 0;
else {
digit_cov.set(dig-1);
}
tot_digits++;
prod = prod/10;
}
i++;
}
return i-1;
}
int main(int argc, char **argv) {
int largest_p = 0;
int largest_n = 0;
int largest_num = 0;
for(int i = 1; i <= 9999; i++) {
int n = pandigital_product(i);
int p = get_pandigital(i,n);
if(n>0 && largest_p < p) {
largest_p = p;
largest_n = n;
largest_num = i;
}
}
display_pandigital(largest_num, largest_n, largest_p);
return 0;
}
| true |
55c72bb0397cf6f97820ccb93188cffe23d9ca7f | C++ | TechAoba/OJ-code | /洛谷/P1219 八皇后.cpp | UTF-8 | 635 | 2.796875 | 3 | [] | no_license | #include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int A[20], N, ans = 0;
bool vis[20], vis1[20], vis2[20];
void print() {
for(int i=1;i<=N;i++) {
printf("%d%c", A[i], i==N?'\n':' ');
}
}
void dfs(int step) {
if(step>N) {
ans++;
if(ans<=3) print();
return;
}
for(int i=1;i<=N;i++) {
if(vis[i] || vis1[i+step] || vis2[N+i-step]) continue;
A[step] = i;
vis[i] = true;
vis1[i+step] = true;
vis2[N+i-step] = true;
dfs(step+1);
vis2[N+i-step] = false;
vis1[i+step] = false;
vis[i] = false;
}
}
int main()
{
memset(A, 0, sizeof(A));
cin>>N;
dfs(1);
cout<<ans<<endl;
return 0;
}
| true |
94b42e07c93fa12225a6257ed363badcda162c7f | C++ | bmag52/vehicle_energy_consumption_estimator | /PTC_xcode/PTC_xcode/data_management/Node.cpp | UTF-8 | 530 | 2.5625 | 3 | [] | no_license | /*
* Node.cpp
*
* Created on: Apr 8, 2016
* Author: vagrant
*/
#include "Node.h"
namespace PredictivePowertrain {
Node::Node() {
}
Node::Node(double lat, double lon, float ele, long int id) {
this->lat = lat;
this->lon = lon;
this->ele = ele;
this->id = id;
}
double Node::getLat() {
return this->lat;
}
double Node::getLon() {
return this->lon;
}
long int Node::getID() {
return this->id;
}
float Node::getEle() {
return this->ele;
}
void Node::setEle(float newEle)
{
this->ele = newEle;
}
}
| true |
b08b9aac6af69fea576428d9ca1bd6ec9c0a9dc1 | C++ | solovyov-private/train-cpp | /Accelerated_CPP/10.1.grades/median.h | UTF-8 | 545 | 3.1875 | 3 | [] | no_license | #ifndef GUARD_median_h
#define GUARD_median_h
#include <algorithm>
#include <stdexcept>
#include <vector>
using std::domain_error;
using std::sort;
using std::vector;
template<class T>
T median(vector<T> vec)
{
typedef typename vector<T>::size_type vec_sz;
vec_sz size = vec.size();
if (size == 0) {
throw domain_error("Median of empty vector.");
}
sort(vec.begin(), vec.end());
vec_sz mid = size / 2;
return size % 2 == 0 ? (vec[mid] + vec[mid - 1]) / 2
: vec[mid];
}
#endif
| true |
30a61aa900a25f79550ef8a5552181fe91f432f3 | C++ | petru-d/leetcode-solutions-reboot | /problems/p1198.h | UTF-8 | 883 | 3.140625 | 3 | [] | no_license | #pragma once
#include <algorithm>
#include <vector>
namespace p1198
{
class Solution
{
public:
int smallestCommonElement(std::vector<std::vector<int>>& mat)
{
auto R = mat.size();
auto C = mat.front().size();
if (R == 0 || C == 0)
return -1;
for (auto col = 0; col < C; ++col)
{
auto curr = mat[0][col];
bool found_everywhere = true;
for (auto row = 1; row < R; ++row)
{
found_everywhere = found_everywhere && std::binary_search(mat[row].begin(), mat[row].end(), curr);
if (!found_everywhere)
break;
}
if (found_everywhere)
return curr;
}
return -1;
}
};
}
| true |
7f11fd758b59bfcf5cb108b2aae68dc4b742a25f | C++ | 200439/LAB_3 | /prj/kolejka.hh | UTF-8 | 641 | 2.890625 | 3 | [] | no_license | #ifndef KOLEJKA_HH
#define KOLEJKA_HH
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
/*!
* \file
* \brief Definicja klasy kolejka
*
*/
struct element_k {
int liczba;
element_k *nastepny;
};
/*! \brief Definicja klasy kolejka
*
*/
class Kolejka {
element_k *pierwszy;
element_k *ostatni;
int ilosc;
public:
Kolejka(){ pierwszy = ostatni = NULL; ilosc = 0; }
~Kolejka(){
while(pierwszy) {
element_k *temp;
pierwszy = pierwszy->nastepny;
delete temp;
}
}
void enqueue(int x);
void dequeue();
int size();
void wyswietl();
bool isEmpty();
};
#endif
| true |
d977927957e458a5325d71d354a83373624dde42 | C++ | kouya-marino/OOPs-programming | /default value in constructors/main.cpp | UTF-8 | 637 | 3.703125 | 4 | [] | no_license | #include <iostream>
using namespace std;
class Human{
private:
string name;
int age;
public:
/*Human(){
cout<<"default constructor"<<endl;
name="unknown";
age=0;
}*/
Human(string iname="unknown",int iage=0){ // default parameter constructor
cout<<"overloaded constructor"<<endl;
name=iname;
age=iage;
}
void speakup(){
cout<<name<<" "<<age<<endl;
}
};
int main()
{
Human obj1("prashant",25);
obj1.speakup();
Human obj2("rawat");
obj2.speakup();
Human obj3; // default parameter constructor called
obj3.speakup();
}
| true |
c9fd64022ebc66ace144b9228e8dce933ca2b7ad | C++ | Eric-Souza/sorting-algorithms | /include/SortingAlgorithms.h | UTF-8 | 5,756 | 3.765625 | 4 | [] | no_license | #include <string>
#include <iostream>
#include <math.h>
using namespace std;
// Class for both names and binary digits
class NamesAndBinaryDigits {
public:
NamesAndBinaryDigits(const string name, const int binaryDigits) {
this -> name = name;
this -> binaryDigits = binaryDigits;
}
~NamesAndBinaryDigits() {}
void print() const {
printf("%s %08d\n", this -> name.c_str(), this -> binaryDigits);
}
string name;
int binaryDigits;
};
// Runs list separating elements according to the pivot, necessary for quicksort method
void partArray(int leftHead, int rightHead, int *i, int *j, NamesAndBinaryDigits **A) {
NamesAndBinaryDigits* x;
NamesAndBinaryDigits* w;
*i = leftHead;
*j = rightHead;
// pivot
x = A[(*i + *j) / 2];
do {
while (x -> name > A[*i] -> name) (*i)++;
while (x -> name < A[*j] -> name) (*j)--;
// If not yet crossed
if (*i <= *j) {
w = A[*i];
A[*i] = A[*j];
A[*j] = w;
// After exchange, sum the values
(*i)++;
(*j)--;
}
} while (*i <= *j);
}
// Implements "divide and conquer" logic
void orderArray(int leftHead, int rightHead, NamesAndBinaryDigits **A) {
int i, j;
partArray(leftHead, rightHead, &i, &j, A);
if (leftHead < j) orderArray(leftHead, j, A);
if (i < rightHead) orderArray(i, rightHead, A);
}
// Orders entire array
void quickSort(NamesAndBinaryDigits **A, int n) {
orderArray(0, n - 1, A);
}
// Merges sub arrays
void merge(NamesAndBinaryDigits **array, int leftHead, int arrayMiddle, int rightHead) {
int const firstSubArray = arrayMiddle - leftHead + 1;
int const secondSubArray = rightHead - arrayMiddle;
// Creates temporary arrays
NamesAndBinaryDigits **leftArray = new NamesAndBinaryDigits*[firstSubArray], **rightArray = new NamesAndBinaryDigits*[secondSubArray];
// Copies data
for (int i = 0; i < firstSubArray; i++)
leftArray[i] = array[leftHead + i];
for (int j = 0; j < secondSubArray; j++)
rightArray[j] = array[arrayMiddle + 1 + j];
// Initial index of first and second sub arrays
auto firstSubArrayIndex = 0, secondSubArrayIndex = 0;
// Initial index of merged array
int mergedArrayIndex = leftHead;
// Merge the temporary arrays back into original array[left ... right]
while (firstSubArrayIndex < firstSubArray && secondSubArrayIndex < secondSubArray) {
if (leftArray[firstSubArrayIndex] -> name <= rightArray[secondSubArrayIndex] -> name) {
array[mergedArrayIndex] = leftArray[firstSubArrayIndex];
firstSubArrayIndex++;
}
else {
array[mergedArrayIndex] = rightArray[secondSubArrayIndex];
secondSubArrayIndex++;
}
mergedArrayIndex++;
}
// Copies remaining elements from left head
while (firstSubArrayIndex < firstSubArray) {
array[mergedArrayIndex] = leftArray[firstSubArrayIndex];
firstSubArrayIndex++;
mergedArrayIndex++;
}
// Copies remaining elements from right head
while (secondSubArrayIndex < secondSubArray) {
array[mergedArrayIndex] = rightArray[secondSubArrayIndex];
secondSubArrayIndex++;
mergedArrayIndex++;
}
}
// Main mergesort function
template<class T = string>
void mergeSort(T *array, int arrayStart, int arrayEnd) {
if (arrayStart >= arrayEnd) return; // Returns using recursive logic
int middle = arrayStart + (arrayEnd - arrayStart) / 2;
mergeSort(array, arrayStart, middle);
mergeSort(array, middle + 1, arrayEnd);
merge(array, arrayStart, middle, arrayEnd);
}
// Remakes a heap (tree), allocations biggest and smallest in 2n and 2n + 1 indexes
void heap(NamesAndBinaryDigits **array, int n, int i) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is bigger than parent
if (l < n && array[l] -> binaryDigits > array[largest] -> binaryDigits) largest = l;
// If right child is bigger than parent
if (r < n && array[r] -> binaryDigits > array[largest] -> binaryDigits) largest = r;
// If largest is not index
if (largest != i) {
swap(array[i], array[largest]);
// Recursively rearranges heap with bigger children
heap(array, n, largest);
}
}
// Main heapsort function
void heapSort(NamesAndBinaryDigits **array, int n) {
// Constructs or rearranges heap
for (int i = n / 2 - 1; i >= 0; i--)
heap(array, n, i);
// Extracts each heap element
for (int i = n - 1; i > 0; i--) {
// Moves current root to array end
swap(array[0], array[i]);
heap(array, i, 0);
}
}
// Gets an integer's n bit
int digit(NamesAndBinaryDigits *x, int n) {
int b = (x -> binaryDigits / (int) pow(2, n)) % 2;
return b;
}
// Implements quicksort logic to sort using radix (bit by bit)
void radixQuickSort(NamesAndBinaryDigits **a, int l, int r, int w) {
int i = l, j = r;
// Calls default case
if (r <= l || w < 0) return;
while(j != i) {
while(digit(a[i], w) == 0 && (i < j)) i++;
while(digit(a[j], w) == 1 && (j > i)) j--;
swap(a[i], a[j]);
}
if (digit(a[r], w) == 0) j++;
radixQuickSort(a, l, j-1, w-1);
radixQuickSort(a, j, r, w-1);
}
void sort(NamesAndBinaryDigits **a, int l, int r) {
radixQuickSort(a, l, r, 31);
}
// Prints array elements
void printArray(NamesAndBinaryDigits **array, int n) {
for (int i = 0; i < n; ++i)
array[i] -> print();
cout << "\n";
} | true |
e2915d9483c5b3f8116ec7cba0296c09ab17212e | C++ | Pedro-Mendes/competitiveProgramming | /leetcode/problems/medium/208-implementPrefixTrie.cpp | UTF-8 | 1,197 | 3.4375 | 3 | [] | no_license | /*https://leetcode.com/problems/implement-trie-prefix-tree
git@Pedro-Mendes*/
/*Map search insertion and delete: O(logn)
So if word size is M, O(M*Logn) for all of them for time complexity
Space complexity = O(M) for insert*/
class Trie {
private:
map<char, Trie*> letters = {};
bool isWord = false;
bool searchImproved(string word, bool prefixSearch) {
Trie* child = this;
for (int i = 0; i < word.length(); i++) {
if (child->letters[word[i]]) {
child = child->letters[word[i]];
} else {
return false;
}
}
return child->isWord || prefixSearch;
}
public:
Trie() {}
void insert(string word) {
Trie* child = this;
for (int i = 0; i < word.length(); i++) {
if (!child->letters[word[i]]) {
child->letters[word[i]] = new Trie ();
}
child = child->letters[word[i]];
}
child->isWord = true;
}
bool search(string word) { return searchImproved(word, false); }
bool startsWith(string word) { return searchImproved(word, true); }
}; | true |
4bbad395ec08844dcd7b28176ff264eaae3afd6e | C++ | steventfan/CS100 | /Lab 4/VectorContainer.cpp | UTF-8 | 1,503 | 3.546875 | 4 | [
"BSD-3-Clause"
] | permissive | #include "container.h"
#include "strategy.h"
/* Pure Virtual Functions */
// insert the top pointer of the tree into the container
void VectorContainer::add_element(Base* element)
{
vectorContainer.push_back(element);
}
// iterate through the trees and output values
void VectorContainer::print()
{
for(unsigned i = 0; i < vectorContainer.size(); i++)
{
std::cout << vectorContainer.at(i)->evaluate() << std::endl;
}
}
// calls on the previously set sorting-algorithm.
// Check if sort_function is not null, throw exception if is null
void VectorContainer::sort()
{ //NEED TO IMPLEMENT THIS FUNCTION
try {
if(sort_function == NULL)
{
throw std::runtime_error("Sorting algorithm has not been chosen");
}
sort_function->sort(this);
}
catch (std::runtime_error& except)
{
std::cout << except.what() << std::endl;
}
//implement
}
/* Essentially the only functions needed to sort */
// switch tree locations
void VectorContainer::swap(int i,int j)
{
Base* temp = vectorContainer.at(i);
vectorContainer.at(i) = vectorContainer.at(j);
vectorContainer.at(j) = temp;
}
// get top pointer of tree at index i
Base* VectorContainer::at(int i)
{
return vectorContainer.at(i);
}
// return container size;
int VectorContainer::size()
{
return vectorContainer.size();
}
| true |
d0869ee4f4e9f1bd160ac5e54705f394c414316c | C++ | professordutta/arduino | /sach/sach.ino | UTF-8 | 549 | 2.546875 | 3 | [] | no_license | int s1;
int s2;
char temp;
void setup()
{
Serial.begin(9600);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
digitalWrite(3,LOW);
digitalWrite(4,LOW);
}
void loop()
{
s1=analogRead(A0);
s2=analogRead(A1);
if(s1> 200 && s2>200)
{
Serial.println("Hi");
delay(500);
}
if(Serial.available()>0)
{
temp=Serial.read();
if(temp=='1')
{
digitalWrite(3,HIGH);
delay(1000);
digitalWrite(3,LOW);
digitalWrite(4,HIGH);
delay(1000);
digitalWrite(4,LOW);
}
}
}
| true |
daed70fe00ea7fdaeed6344136fee17976314760 | C++ | maximechoulika/My42Cursus | /piscine_cpp/project/source/Menu.cpp | UTF-8 | 4,423 | 2.6875 | 3 | [] | no_license | #include "Menu.hpp"
#include "Vars.hpp"
#include <SFML/Window/Event.hpp>
Menu::Menu(unsigned char escAction) : m_escAction(escAction), m_viewPos(window.getView().getCenter() - window.getView().getSize() / 2.f)
{
m_vertices.setPrimitiveType(sf::Quads);
}
bool Menu::updateMenu()
{
bool buttonClicked = false;
for(sf::Event event; window.pollEvent(event);)
{
switch(event.type)
{
case sf::Event::KeyPressed:
if(event.key.code == sf::Keyboard::Down || event.key.code == sf::Keyboard::Up)
{
signed char newSelected = m_selected + (event.key.code == sf::Keyboard::Down) * 2 - 1;
if(newSelected != -1 && newSelected != m_buttonsCount)
{
highlightUpdate(newSelected);
}
}
else if(event.key.code == sf::Keyboard::Return)
{
buttonClicked = true;
}
else if(event.key.code == sf::Keyboard::Escape)
{
m_selected = m_escAction;
buttonClicked = true;
}
break;
case sf::Event::JoystickMoved:
if(event.joystickMove.axis == sf::Joystick::Y)
{
if(abs(sf::Joystick::getAxisPosition(0, sf::Joystick::Y)) > 30)
{
if(!m_joystickHigh)
{
m_joystickHigh = true;
signed char newSelected = m_selected + (sf::Joystick::getAxisPosition(0, sf::Joystick::Y) > 0) * 2 - 1;
if(newSelected != -1 && newSelected != m_buttonsCount)
{
highlightUpdate(newSelected);
}
}
}
else if(m_joystickHigh)
{
m_joystickHigh = false;
}
}
break;
case sf::Event::JoystickButtonPressed:
if(event.joystickButton.button == 0)
{
buttonClicked = true;
}
break;
case sf::Event::Resized:
game->resizeWindow();
break;
case sf::Event::Closed:
game->isRunning = false;
break;
}
}
if(buttonClicked)
{
audioManager->playSound("menuClick");
return true;
}
return false;
}
void Menu::newText(const std::string& content, const sf::Vector2u& position, unsigned int characterSize, bool centered)
{
m_texts.push_back(sf::Text(content, game->font, characterSize));
unsigned int index = m_texts.size() - 1;
m_texts[index].setPosition(sf::Vector2f(position.x * WINDOW_RATIO_X + m_viewPos.x, position.y * WINDOW_RATIO_Y + m_viewPos.y));
if(centered)
{
m_texts[index].move(- m_texts[index].getGlobalBounds().width / 2, 0);
}
}
void Menu::newButton(const std::string& content, const sf::Vector2u& position, unsigned int characterSize, bool centered)
{
newText(content, position, characterSize, centered);
if(++m_buttonsCount == 1)
{
m_texts[0].setColor(sf::Color::Red);
}
}
void Menu::newRectangle(sf::Rect<unsigned int> rect, const sf::Color& color)
{
unsigned int index = m_vertices.getVertexCount();
m_vertices.resize(m_vertices.getVertexCount() + 4);
m_vertices[index] = sf::Vertex(sf::Vector2f(rect.left * WINDOW_RATIO_X + m_viewPos.x, rect.top * WINDOW_RATIO_Y + m_viewPos.y), color);
m_vertices[index + 1] = sf::Vertex(sf::Vector2f((rect.left + rect.width) * WINDOW_RATIO_X + m_viewPos.x, rect.top * WINDOW_RATIO_Y + m_viewPos.y), color);
m_vertices[index + 2] = sf::Vertex(sf::Vector2f((rect.left + rect.width) * WINDOW_RATIO_X + m_viewPos.x, (rect.top + rect.height) * WINDOW_RATIO_Y + m_viewPos.y), color);
m_vertices[index + 3] = sf::Vertex(sf::Vector2f(rect.left * WINDOW_RATIO_X + m_viewPos.x, (rect.top + rect.height) * WINDOW_RATIO_Y + m_viewPos.y), color);
}
void Menu::highlightUpdate(unsigned char newSelected)
{
m_texts[m_selected].setColor(sf::Color::White);
m_texts[newSelected].setColor(sf::Color::Red);
m_selected = newSelected;
audioManager->playSound("menuNav");
}
void Menu::drawMenu() const
{
window.draw(m_vertices);
for(const auto& text : m_texts)
{
window.draw(text);
}
}
| true |
1ebf306f0794a067625c86028f821f0cc1b98f31 | C++ | Codeon-GmbH/mulle-clang | /test/SemaCXX/cxx1z-init-statement.cpp | UTF-8 | 2,156 | 3.328125 | 3 | [
"Apache-2.0",
"LLVM-exception",
"NCSA"
] | permissive | // RUN: %clang_cc1 -std=c++1z -Wno-unused-value -verify %s
// RUN: %clang_cc1 -std=c++17 -Wno-unused-value -verify %s
void testIf() {
int x = 0;
if (x; x) ++x;
if (int t = 0; t) ++t; else --t;
if (int x, y = 0; y) // expected-note 2 {{previous definition is here}}
int x = 0; // expected-error {{redefinition of 'x'}}
else
int x = 0; // expected-error {{redefinition of 'x'}}
if (x; int a = 0) ++a;
if (x, +x; int a = 0) // expected-note 2 {{previous definition is here}}
int a = 0; // expected-error {{redefinition of 'a'}}
else
int a = 0; // expected-error {{redefinition of 'a'}}
if (int b = 0; b)
;
b = 2; // expected-error {{use of undeclared identifier}}
}
void testSwitch() {
int x = 0;
switch (x; x) {
case 1:
++x;
}
switch (int x, y = 0; y) {
case 1:
++x;
default:
++y;
}
switch (int x, y = 0; y) { // expected-note 2 {{previous definition is here}}
case 0:
int x = 0; // expected-error {{redefinition of 'x'}}
case 1:
int y = 0; // expected-error {{redefinition of 'y'}}
};
switch (x; int a = 0) {
case 0:
++a;
}
switch (x, +x; int a = 0) { // expected-note {{previous definition is here}}
case 0:
int a = 0; // expected-error {{redefinition of 'a'}} // expected-note {{previous definition is here}}
case 1:
int a = 0; // expected-error {{redefinition of 'a'}}
}
switch (int b = 0; b) {
case 0:
break;
}
b = 2; // expected-error {{use of undeclared identifier}}
}
constexpr bool constexpr_if_init(int n) {
if (int a = n; ++a > 0)
return true;
else
return false;
}
constexpr int constexpr_switch_init(int n) {
switch (int p = n + 2; p) {
case 0:
return 0;
case 1:
return 1;
default:
return -1;
}
}
void test_constexpr_init_stmt() {
constexpr bool a = constexpr_if_init(-2);
static_assert(!a, "");
static_assert(constexpr_if_init(1), "");
constexpr int b = constexpr_switch_init(-1);
static_assert(b == 1, "");
static_assert(constexpr_switch_init(-2) == 0, "");
static_assert(constexpr_switch_init(-5) == -1, "");
}
| true |
28f9551dd7d12c2937c04b2a469aefc64cf02b0b | C++ | rafaelflores520/P3Lab9_RafaelFlores | /Reina.hpp | UTF-8 | 2,382 | 2.984375 | 3 | [] | no_license | #ifndef REINA_H
#define REINA_H
#include <iostream>
#include "Pieza.hpp"
using std::string;
class Reina : public Pieza
{
public:
static const int FIXED_REINA_WHITE[];
static const int FIXED_REINA_BLACK[];
const bool isWHITE;
Reina(const int pos[], bool color) : Pieza(pos), isWHITE(color){};
bool validarMovimiento(string coordenada)
{
int actual[2], nuevo[2];
if (isWHITE)
{
actual[1] = (getNUmColumn(coordenada.at(1)));
nuevo[1] = (getNUmColumn(coordenada.at(4)));
actual[0] = (8 - (coordenada.at(2) - '0'));
nuevo[0] = (8 - (coordenada.at(5) - '0'));
}
else
{
actual[1] = (getNUmColumn(coordenada.at(1)));
nuevo[1] = (getNUmColumn(coordenada.at(4)));
actual[0] = ((coordenada.at(2) - '0'));
nuevo[0] = ((coordenada.at(5) - '0'));
}
if (posicion[0] != actual[0] || posicion[1] != actual[1])
{
err = "La posicion que ingreso no concuerda con la Reina";
return false;
}
else
{
std::cout << "Entra en la pieza" << std::endl;
std::cout << actual[0] << std::endl;
std::cout << nuevo[0] << std::endl;
if (nuevo[0] > 7 || nuevo[0] < 0 || nuevo[1] < 0 || nuevo[1] > 7)
{
err = "NO se puede mover fuera del tablero";
return false;
}
else if ((actual[0] - actual[1]) != (nuevo[0] - nuevo[1]))
{
setPosicion(nuevo);
return true;
}
else if (((actual[0] - 7) + (actual[1] - 7)) != ((nuevo[0] - 7) + (nuevo[1] - 7)))
{
setPosicion(nuevo);
return true;
}
else if ((actual[0] == nuevo[0] && nuevo[1] != actual[1]) ||
(actual[1] == nuevo[1] && nuevo[0] != actual[0]))
{
setPosicion(nuevo);
return true;
}
else
{
err = "NO se puede mover la reina a esa posicion";
return false;
}
}
};
string getSymbol() { return " | Q | "; };
};
const int Reina::FIXED_REINA_BLACK[] = {
0, 3};
const int Reina::FIXED_REINA_WHITE[] = {
7, 3};
#endif | true |
a658310d77136e7d2c4a11d716b6fc04606a16e1 | C++ | omarelsobkey/Problem_Solving | /Sheets/Assiut NewCommers/Sheet #6 (Math Geometry)/Divisability.cpp | UTF-8 | 381 | 2.828125 | 3 | [] | no_license | // https://codeforces.com/group/MWSDmqGsZm/contest/223338/problem/I
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main()
{
double a, b;
long long x, n1, n2;
cin >> a >> b >> x;
if (a > b)
swap(a, b);
n1 = (floor(b / x) * (floor(b / x) + 1)) / 2;
n2 = (ceil(a / x) * (ceil(a / x) - 1)) / 2;
cout << (n1-n2) * x << endl;
return 0;
} | true |
0257535224df94e773496212b6f858060d37983e | C++ | fangzhouzhang/LeetCodeCpp | /_1368MinimumCosttoMakeatLeastOneValidPathinaGrid.cpp | UTF-8 | 1,488 | 2.671875 | 3 | [] | no_license | //
// Created by Fangzhou Zhang on 2020/3/4.
//
vector<vector<int>> dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
class Solution {
private:
bool isValid(int rows, int n, int a, int b) {
if (a < 0 || a >= rows) return false;
if (b < 0 || b >= n) return false;
return true;
}
public:
int minCost(vector<vector<int>>& grid) {
deque<pair<int, int>> q;
unordered_set<int> set;
int rows = grid.size();
int n = grid[0].size();
q.push_back(make_pair(0, 0));
while (q.size() > 0) {
int size = q.size();
for (int k = 0; k < size; k++) {
pair<int, int> p = q.front();
q.pop_front();
int r = p.first / n;
int c = p.first % n;
if (r == rows - 1 && c == n - 1) return p.second;
if (set.find(p.first) != set.end()) continue;
set.insert(p.first);
for (int m = 0; m < 4; m++) {
int new_r = dirs[m][0] + r;
int new_c = dirs[m][1] + c;
if (!isValid(rows, n, new_r, new_c)) continue;
if ((grid[r][c] - 1) % 4 == m) {
q.emplace_front(make_pair(new_r * n + new_c, p.second));
} else {
q.emplace_back(make_pair(new_r * n + new_c, p.second + 1));
}
}
}
}
return -1;
}
};
| true |
e503c920fa3fd3127bd507e96d2d092aa7c80460 | C++ | xmba15/miscellaneous | /cuda/image_processing/src/Histogram.hpp | UTF-8 | 1,439 | 3.0625 | 3 | [] | no_license | /**
* @file Histogram.hpp
*
* @author btran
*
*/
#pragma once
#include <thrust/device_vector.h>
namespace _cv
{
namespace
{
template <typename T> __global__ void histoKernel(const T* input, int* hist, int size, int numBins)
{
extern __shared__ int sharedHist[];
int tid = threadIdx.x;
if (tid < numBins) {
sharedHist[tid] = 0;
}
__syncthreads();
int idx = blockIdx.x * blockDim.x + threadIdx.x;
while (idx < size) {
atomicAdd(&(sharedHist[input[idx] % numBins]), 1);
idx += blockDim.x * gridDim.x;
}
__syncthreads();
if (tid < numBins) {
atomicAdd(&(hist[tid]), sharedHist[tid]);
}
}
} // namespace
template <typename T> void histogramGPU(const T* input, int* hist, int size, int numBins)
{
thrust::device_vector<T> dInput(input, input + size);
thrust::device_vector<int> dHist(numBins);
dim3 blockDim = numBins;
dim3 gridDim = (size + numBins - 1) / numBins;
histoKernel<<<gridDim, blockDim, numBins * sizeof(int)>>>(thrust::raw_pointer_cast(dInput.data()),
thrust::raw_pointer_cast(dHist.data()), size, numBins);
thrust::copy(dHist.begin(), dHist.end(), hist);
}
template <typename T> void histogramCPU(const T* input, int* hist, int size, int numBins)
{
for (int i = 0; i < size; ++i) {
hist[input[i] % numBins]++;
}
}
} // namespace _cv
| true |
4994c60ed997e4405637c07b984229a97e50483f | C++ | matheusportela/black-hole-ray-tracer | /src/image.hpp | UTF-8 | 964 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef IMAGE_HPP
#define IMAGE_HPP
#include <iostream>
#include <string>
#include <vector>
#include <Eigen/Core>
#include "color.hpp"
#include "log.hpp"
#include "stb_image.h"
#include "stb_image_write.h"
class Image {
public:
Image() {}
Image(int width, int height);
void setPixel(int row, int col, std::shared_ptr<Color> color);
void save(std::string filename);
void load(std::string filename);
Eigen::Vector4d at(int width, int height);
Eigen::Vector4d at(double u, double v);
private:
void writeMatrixToRGB(const Eigen::MatrixXd& R, const Eigen::MatrixXd& G, const Eigen::MatrixXd& B, const Eigen::MatrixXd& A, const std::string& filename);
unsigned char doubleToUnsignedChar(const double d);
double unsignedCharToDouble(const unsigned char x);
Eigen::MatrixXd red_channel;
Eigen::MatrixXd green_channel;
Eigen::MatrixXd blue_channel;
Eigen::MatrixXd alpha_channel;
};
#endif // IMAGE_HPP
| true |
34844fe6003583d5ae7505bd16bc8541ff30b0a0 | C++ | N-911/c_plus_plus_white | /w3/family_and_history.cpp | UTF-8 | 4,162 | 3.390625 | 3 | [] | no_license | #include <vector>
#include <string>
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
string vector_name_to_str(vector<string> v) {
string res;
int c = v.size();
reverse(begin(v), end(v));
res += v[0];
if (v.size() > 1) {
res += " (";
for (int i = 1; i < c ; ++i) {
res += v[i];
if (i + 1 < c) {
res += ", ";
}
else {
res += ")";
}
}
}
return res;
}
class Person {
public:
void ChangeFirstName(int year, const string& first_name) {
fam[year].first_name = first_name;
}
void ChangeLastName(int year, const string& last_name) {
fam[year].last_name = last_name;
}
vector<string> find_change(int year) {
vector<string> res(2);
for (auto& i : fam) {
if (i.first <= year) {
if (!i.second.first_name.empty())
res[0] = i.second.first_name;
if (!i.second.last_name.empty())
res[1] = i.second.last_name;
}
else {
break;
}
}
return res;
}
string GetFullNameWithHistory(int year) {
vector<string> f_n;
vector<string> l_n;
for (auto& i : fam) {
if (i.first <= year) {
if (!i.second.first_name.empty() && (f_n.empty() || (i.second.first_name != f_n.back()))) {
f_n.push_back(i.second.first_name);
}
if (!i.second.last_name.empty() && (l_n.empty() || (i.second.last_name != l_n.back()))) {
l_n.push_back(i.second.last_name);
}
}
}
string res;
if (f_n.empty() && l_n.empty()) {
res = "Incognito";
}
else if (f_n.empty()) { // if first name not changed
res = vector_name_to_str(l_n);
res += " with unknown first name";
}
else if (l_n.empty()) { // if last name not changed
res = vector_name_to_str(f_n);
res += " with unknown last name";
}
else {
res = vector_name_to_str(f_n);
res += " ";
res += vector_name_to_str(l_n);
}
return res;
}
string GetFullName(int year) {
vector<string> last_changes = find_change(year);
string res;
if (last_changes[0].empty() && last_changes[1].empty()) {
res = "Incognito";
}
else if (last_changes[0].empty()) {
res += last_changes[1];
res += " with unknown first name";
}
else if (last_changes[1].empty()) {
res += last_changes[0];
res += " with unknown last name";
} else {
res += last_changes[0];
res += " ";
res += last_changes[1];
}
return res;
}
private:
struct name {
string first_name;
string last_name;
};
map<int, name> fam;
};
int main() {
Person person;
person.ChangeFirstName(1965, "Polina");
person.ChangeLastName(1967, "Sergeeva");
for (int year : {1900, 1965, 1990}) {
cout << person.GetFullNameWithHistory(year) << endl;
}
person.ChangeFirstName(1970, "Appolinaria");
for (int year : {1969, 1970}) {
cout << person.GetFullNameWithHistory(year) << endl;
}
person.ChangeLastName(1968, "Volkova");
for (int year : {1969, 1970}) {
cout << person.GetFullNameWithHistory(year) << endl;
}
person.ChangeFirstName(1990, "Polina");
person.ChangeLastName(1990, "Volkova-Sergeeva");
cout << person.GetFullNameWithHistory(1990) << endl;
person.ChangeFirstName(1966, "Pauline");
cout << person.GetFullNameWithHistory(1966) << endl;
person.ChangeLastName(1960, "Sergeeva");
for (int year : {1960, 1967}) {
cout << person.GetFullNameWithHistory(year) << endl;
}
person.ChangeLastName(1961, "Ivanova");
cout << person.GetFullNameWithHistory(1967) << endl;
return 0;
} | true |
da1e26595084d97cc30429225dba7e9ee8671b77 | C++ | moth96/leetcode | /1046.最后一块石头的重量.cpp | UTF-8 | 410 | 2.890625 | 3 | [] | no_license | int lastStoneWeight(vector<int>& stones)
{
int n = stones.size();
if (n == 0) return 0;
if (n == 1) return stones[0];
priority_queue<int> q;
for (int x : stones) q.push(x);
while(q.size() > 1)
{
int a = q.top();
q.pop();
int b = q.top();
q.pop();
if(a == b) continue;
else q.push(a-b);
}
return q.size() ? q.top() : 0;
}
| true |
9f968dec63004915f3f598edf29b0940092cd465 | C++ | Thiebosh/M1_S1project_Android | /Arduino/microcode_v3_42d/004console_input_functions.ino | UTF-8 | 13,536 | 2.765625 | 3 | [] | no_license | /*
check console return code and display arror if any
argument(s): return code
return: nothing
*/
void consoleErrorMessage(uint8_t error) {
switch (error) {
case 0: // nothing available on console, no message
break;
case 1:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad first field");
break;
case 2:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad 2nd field");
break;
case 3:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad 3rd field");
break;
case 4:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad 4th field");
break;
case 5:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad 5th field");
break;
case 6:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": bad 6th field");
break;
case 90:
Serial.print("Error code ");
Serial.print(error);
Serial.println(": command not yet implemented");
break;
case 99: // command OK
Serial.println("OK");
break;
default:
Serial.print("Unknown error code ");
break;
}
}// end consoleErrorMessage()
/*
converts hex string to uint16_t
arguments(s): hexa string limited to 4 hex characters (size not tested)
returns: integer value
*/
uint16_t hexToDec(String hexString) {
uint16_t decValue = 0;
int nextInt;
for (int i = 0; i < hexString.length(); i++) {
nextInt = int(hexString.charAt(i));
if (nextInt >= 48 && nextInt <= 57) nextInt = map(nextInt, 48, 57, 0, 9);
if (nextInt >= 65 && nextInt <= 70) nextInt = map(nextInt, 65, 70, 10, 15);
if (nextInt >= 97 && nextInt <= 102) nextInt = map(nextInt, 97, 102, 10, 15);
nextInt = constrain(nextInt, 0, 15);
decValue = (decValue * 16) + nextInt;
}
return decValue;
} // end hexToDec()
/*
calibrates in voltage source mode
arguments(s): channel (0..7)
returns: nothing
*/
uint8_t voltageCalibration(uint8_t channel) {
String phrase;
float fineOffsetStep = LSB_VALUE / 8;
float fineGainStep = (DEF_ABSOLUTE_MAX_VALUE - DEF_ABSOLUTE_MIN_VALUE) / pow(2, 17);
float zeroVolt, minVolt, maxVolt, maxGainError, minGainError;
int fineOffset, fineGain, coarseGain;
Serial.println("Voltage mode calibration, condition: no load . Continue [y] or skip [any key]?");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
if (phrase.substring(0, 1).compareTo("Y") != 0) {
Serial.println("Voltage mode calibration skipped");
return 1; // skip step & exit
}
// proceed with calibration, reset cal values in FRAM
fram.writeInt(0x5000 + VOLTAGE_MODE_COARSE_OFFSET_BASE_ADDRESS + 2 * channel, 0);
fram.writeInt(0x5000 + VOLTAGE_MODE_FINE_OFFSET_BASE_ADDRESS + 2 * channel, 0);
fram.writeInt(0x5000 + VOLTAGE_MODE_COARSE_GAIN_BASE_ADDRESS + 2 * channel, 0);
fram.writeInt(0x5000 + VOLTAGE_MODE_FINE_GAIN_BASE_ADDRESS + 2 * channel, 0);
setChannelType(channel, 0); // offset calibration
setChannelValue(channel, 0);
switchChannelOn(channel);
Serial.println("Enter measured value in mV");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
zeroVolt = phrase.toFloat();
fineOffset = (int)(-zeroVolt / fineOffsetStep);
fram.writeInt(0x5000 + VOLTAGE_MODE_FINE_OFFSET_BASE_ADDRESS + 2 * channel, formatFineOffset(fineOffset));
setChannelType(channel, 0); // reload new fine offset
setChannelValue(channel, DEF_ABSOLUTE_MAX_VALUE); // gain calibration
Serial.println("Enter measured value in mV");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
maxVolt = phrase.toFloat();
/*
maxGainError = DEF_ABSOLUTE_MAX_VALUE - maxVolt;
fineGain = (int)round(maxGainError / fineGainStep);
Serial.print("Fine Gain =");
Serial.println(fineGain);
if ((fineGain > 31) || (fineGain < -32)) Serial.println("Gain adjustment is not optimal");
fram.writeInt(0x5000 + VOLTAGE_MODE_FINE_GAIN_BASE_ADDRESS + 2 * channel, formatFineGain(fineGain));
*/
maxGainError = DEF_ABSOLUTE_MAX_VALUE / maxVolt;
Serial.print("Gain =");
Serial.println(maxGainError, 6);
coarseGain = (int)((maxGainError - 1) * 1e6);
fineGain = 0; // fine gain no more used for voltage mode
fram.writeInt(0x5000 + VOLTAGE_MODE_COARSE_GAIN_BASE_ADDRESS + 2 * channel, coarseGain);
fram.writeInt(0x5000 + VOLTAGE_MODE_FINE_GAIN_BASE_ADDRESS + 2 * channel, formatFineGain(fineGain));
setChannelType(channel, 0); // reload new fine gain
setChannelValue(channel, 0);
switchChannelOff(channel);
Serial.println("Step1: voltage mode calibration completed");
return 0;
} // end voltageCalibration()
/*
calibrates in current source mode
arguments(s): channel (0..7), range (0..3)
returns: nothing
*/
uint8_t currentCalibration(uint8_t channel, uint8_t range) {
String phrase;
float fineOffsetStep = LSB_VALUE / 8;
float fineGainStep = (HIGH_COMPLIANCE_MAX_CURRENT - HIGH_COMPLIANCE_MIN_CURRENT) / pow(2, 17);
float zeroVolt, minVolt, maxVolt, maxGainError, minGainError;
int fineOffset, fineGain, coarseOffset, coarseGain;
Serial.print("Current mode calibration, range ");
Serial.print(range);
Serial.println(" , condition: zero Ohm load . Continue [y] or skip [any key]?");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
if (phrase.substring(0, 1).compareTo("Y") != 0) {
Serial.print("Current mode calibration, range ");
Serial.print(range);
Serial.println(" skipped");
return 1; // skip step & exit
}
//proceed with calibration, reset cal values in FRAM
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_COARSE_OFFSET_BASE_ADDRESS + 0x0040 * range + 2 * channel, 0);
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_FINE_OFFSET_BASE_ADDRESS + 0x0040 * range + 2 * channel, 0);
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_COARSE_GAIN_BASE_ADDRESS + 0x0040 * range + 2 * channel, 0);
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_FINE_GAIN_BASE_ADDRESS + 0x0040 * range + 2 * channel, 0);
setChannelType(channel, 1); // offset calibration
setChannelValue(channel, 0);
setChannelRange(channel, range);
switchChannelOn(channel);
Serial.println("Enter measured value in uA");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
zeroVolt = pow(10, 3 - range) * phrase.toFloat();// convert uA int mV
coarseOffset = 0;
if (abs(zeroVolt) > 4.0) {
if (zeroVolt > 0) { // calculates coarse offset so that |fineOffset| is less than 4mV
do {
coarseOffset --;
} while ((zeroVolt - coarseOffset * LSB_VALUE) > 4.0);
} else { // calculates coarse offset
do {
coarseOffset ++;
} while ((zeroVolt - coarseOffset * LSB_VALUE) < -4.0);
}
}
zeroVolt += coarseOffset * LSB_VALUE; // apply and stores coarse correction
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_COARSE_OFFSET_BASE_ADDRESS + 0x0040 * range + 2 * channel, coarseOffset);
fineOffset = (int)(-zeroVolt / fineOffsetStep); // calculates and stores coarse correction
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_FINE_OFFSET_BASE_ADDRESS + 0x0040 * range + 2 * channel, formatFineOffset(fineOffset));
setChannelType(channel, 1); // reload new fine offset
setChannelRange(channel, range);// reload new coarse offset
setChannelValue(channel, HIGH_COMPLIANCE_MAX_CURRENT); // gain calibration
Serial.println("Enter measured value in uA");
while (!Serial.available()) {} // wait for string in buffer
phrase = Serial.readStringUntil('\n'); // get incomming string
phrase.toUpperCase(); // all uppercase
maxVolt = pow(10, 3 - range) * phrase.toFloat();// convert uA int mV
maxGainError = HIGH_COMPLIANCE_MAX_CURRENT / maxVolt;
Serial.print("Gain =");
Serial.println(maxGainError, 6);
coarseGain = (int)((maxGainError - 1) * 1e6);
fineGain = 0; // fine gain no more used for current mode
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_COARSE_GAIN_BASE_ADDRESS + 0x0040 * range + 2 * channel, coarseGain);
fram.writeInt(0x5000 + CURRENT_MODE_RANGE0_FINE_GAIN_BASE_ADDRESS + 0x0040 * range + 2 * channel, formatFineGain(fineGain));
setChannelType(channel, 1); // reload new fine gain
setChannelValue(channel, 0);
switchChannelOff(channel);
Serial.print("Current mode calibration, range ");
Serial.print(range);
Serial.println(" completed");
return 0;
} // end currentCalibration()
/*
format value to fine offset in order to avoid problems when the positive value is too high
argument: raw fine offset
returns: formatted fine offset
*/
int formatFineOffset( int value) {
if (value > 127) return 127;
else if (value < -128) return -128;
else return value;
} // end formatFineOffset()
/*
format value to fine gain in order to avoid problems when the positive value is too high
argument: raw fine gain
returns: formatted fine gain
*/
int formatFineGain( int value) {
if (value > 31) return 31;
else if (value < -32) return -32;
else return value;
} // end formatFineOffset()
/*
Interprets subPhrase[index] with a value potentially containing m or u
argument: subPhrase index, type (0= voltage, 1 = Current), converted value value in mV or uA depending on the type
returns: -1: ok >=0: index of field in error
*/
int consoleGetValueWithMultiplier(uint8_t index, uint8_t type, float *returnedValue) {
int stringLen;
float multiplier;
String lastChar;
stringLen = subPhrase[index].length();
lastChar = subPhrase[index].substring(stringLen - 1);
// Serial.print("lastchar=");
// Serial.println(lastChar);
switch (type) {
case 0: // voltage
if (lastChar.compareTo("M") == 0) multiplier = 1;
else if (lastChar.compareTo("U") == 0) multiplier = 0.001;
else if (lastChar.compareTo("0") == 0) multiplier = 1000;
else if (lastChar.compareTo("1") == 0) multiplier = 1000;
else if (lastChar.compareTo("2") == 0) multiplier = 1000;
else if (lastChar.compareTo("3") == 0) multiplier = 1000;
else if (lastChar.compareTo("4") == 0) multiplier = 1000;
else if (lastChar.compareTo("5") == 0) multiplier = 1000;
else if (lastChar.compareTo("6") == 0) multiplier = 1000;
else if (lastChar.compareTo("7") == 0) multiplier = 1000;
else if (lastChar.compareTo("8") == 0) multiplier = 1000;
else if (lastChar.compareTo("9") == 0) multiplier = 1000;
else return index++; // bad field
break;
case 1: // current
if (lastChar.compareTo("M") == 0) multiplier = 1000;
else if (lastChar.compareTo("U") == 0) multiplier = 1;
else if (lastChar.compareTo("0") == 0) multiplier = 1e6;
else if (lastChar.compareTo("1") == 0) multiplier = 1e6;
else if (lastChar.compareTo("2") == 0) multiplier = 1e6;
else if (lastChar.compareTo("3") == 0) multiplier = 1e6;
else if (lastChar.compareTo("4") == 0) multiplier = 1e6;
else if (lastChar.compareTo("5") == 0) multiplier = 1e6;
else if (lastChar.compareTo("6") == 0) multiplier = 1e6;
else if (lastChar.compareTo("7") == 0) multiplier = 1e6;
else if (lastChar.compareTo("8") == 0) multiplier = 1e6;
else if (lastChar.compareTo("9") == 0) multiplier = 1e6;
else return index++; // bad field
break;
}
*returnedValue = (subPhrase[index].substring(0, stringLen).toFloat() * multiplier);
return -1;
}// end consoleGetValueWithMultiplier(uint8_t index, uint8_t type)
void sendChannelStatus(uint8_t channel) {
float val;
Serial.print("CH,");
Serial.print(channel);
Serial.print(",");
if (boardOnSlotStatus & 0x01 << channel) {
if (channelActiveStatus & 0x01 << channel) Serial.print("ON,");
else Serial.print("OFF,");
if (channelModeStatus & 0x01 << channel) Serial.print("I,");
else Serial.print("V,");
if (channelModeStatus & 0x01 << channel) {
switch (channelCurrentRange[channel]) {
case 0:
val = (float)channelValue[channel] / 1000;
Serial.print(val, 3);
break;
case 1:
val = (float)channelValue[channel] / 100;
Serial.print(val, 2);
break;
case 2:
val = (float)channelValue[channel] / 10;
Serial.print(val, 1);
break;
case 3:
Serial.print(channelValue[channel], DEC);
break;
}
} else {
Serial.print(channelValue[channel], DEC);
}
Serial.print(",");
Serial.print("UVL,");
Serial.print(channelMaxVoltage[channel]);
Serial.print(",");
Serial.print("LVL,");
Serial.print(channelMinVoltage[channel]);
Serial.print(",");
Serial.print("UIL,");
Serial.print(channelMaxCurrent[channel]);
Serial.print(",");
Serial.print("LIL,");
Serial.println(channelMinCurrent[channel]);
} else Serial.println("Empty_Slot");
}// end sendChannelStatus()
| true |
a4fe7785bb7b3e96695ef26436e4cbe29079ae7f | C++ | Pugipug/liceu | /Recursivitate/Metode recursive/Metoda „Backtracking”/8.cpp | UTF-8 | 911 | 2.625 | 3 | [] | no_license | #include <iostream>
using namespace std;
/* Sa se genereze toate numerele naturale ale caror cifre se regasesc printre cifrele unui numar dat X si au lungimea cel mult egala
cu lungimea lui X. */
int st[10],v[10],X,n;
int valid(int p)
{
int OK=1;
if (p==1 && st[p]==0)
OK=0;
for (int i=1;i<p;i++)
if (st[p]==st[i])
OK=0;
return OK;
}
void tipar(int p)
{
for (int i=1;i<=p;i++)
cout << st[i];
cout << endl;
}
void backtracking(int p)
{
for (int pval=1;pval<=n;pval++)
{
st[p]=v[pval];
if (valid(p)==1)
{
tipar(p);
backtracking(p+1);
}
}
}
int main()
{
n=0;
cout << "X="; cin >> X;
while (X!=0)
{
n++;
v[n]=X%10;
X=X/10;
}
backtracking(1);
return 0;
}
| true |
afde47e7587b3cc82b2ecb49264349840c61bd11 | C++ | yameenjavaid/Online-Judge-Solutions | /Kattis/tracksmoothing.cpp | UTF-8 | 859 | 3 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// Track Smoothing
#define EPS 1e-9
struct point{
double x, y;
point() = default;
point(double x, double y){
this->x = x, this->y = y;
}
point& operator=(const point& o) = default;
double dist(const point& o){
return hypot(x - o.x, y - o.y);
}
};
double r;
int n;
point polygon[10003];
int main(){
int t;
cin >> t;
cout << fixed << setprecision(6);
while(t--){
cin >> r >> n;
for(int i = 0; i < n; i++)
cin >> polygon[i].x >> polygon[i].y;
double P = 0;
for(int i = 0; i < n; i++)
P += polygon[i].dist(polygon[(i + 1) % n]);
if(P - 2 * M_PI * r > -EPS)
cout << (P - 2 * M_PI * r) / P << endl;
else
cout << "Not possible" << endl;
}
} | true |
1e9852640ed608c554ce034a30c03d1b725b5bdb | C++ | sandeep2119/CPP | /5.cpp | UTF-8 | 312 | 3.625 | 4 | [] | no_license | //Write a program which accept temperature in Farenheit and print it in centigrade
#include <iostream>
using namespace std;
int main() {
float c,f;
cout<<"Enter the Temperature in Fahrenheit : "<<endl;
cin>>f;
c = (f-32)*5/9;
cout<<"The Temperature in Centigrade is :"<<c<<endl;
return 0;
}
| true |
348808d86c6c9614b4a195e1afcf4640d9af9c8c | C++ | Ely4s/InfiniteConquest | /src/Entity/Entity.h | UTF-8 | 2,955 | 2.640625 | 3 | [] | no_license | //
// Created by Elyas EL IDRISSI on 28/02/2021.
//
#ifndef INFINITECONQUEST_ENTITY_H
#define INFINITECONQUEST_ENTITY_H
#include <SFML/Graphics.hpp>
#include "Library/hashmap.h"
#include "Sprite/SpriteSheet.h"
#include "Interface/Transformable.h"
#include "Interface/Drawable.h"
#include "Entity/EntityTeam.h"
#include "Entity/EntityType.h"
#include "Entity/EntityState.h"
#include "Game/GameEntityRole.h"
class Entity : public Drawable, public Transformable, public Flippable, public EntityTeam, public EntityType, public EntityState
{
public :
virtual ~Entity() = default;
bool isIdling() const;
void idle(bool force = false);
bool isAttacking() const;
virtual void generateAttack(Entity &target) = 0;
virtual int attack(Entity &target, bool visualOnly = false, bool force = false);
bool isRunning() const;
void run(bool force = false);
bool isDying() const;
void die(bool force = false);
bool isAlive() const;
bool isDead() const;
const std::string &getEntityId() const;
void setEntityId(const std::string &entityId);
const std::string &getEntityName() const;
void setEntityName(const std::string &entityName);
GameEntityRole::Role getRole() const;
Entity & setRole(GameEntityRole::Role role);
Team getTeam() const;
Entity * setTeam(Team team);
Type getType() const;
void setType(Type type);
State getState() const;
void setState(State state);
int getAttackDamage() const;
void setAttackDamage(int atkDamage);
int getLifePointMax() const;
void setLifePointMax(int lifePointMax);
int getLifePoint() const;
void setLifePoint(int lifePoint);
const SpriteSheet &getSprite() const;
SpriteSheet &getSprite();
const SpriteSheet &getSprite(const std::string &spriteId) const;
SpriteSheet &getSprite(const std::string &spriteId);
void setSprite(const std::string &spriteId, const SpriteSheet &sprite);
const sf::Vector2f &getPosition() const override;
void setPosition(float x, float y) override;
void setPosition(const sf::Vector2f &position) override;
float getRotation() const override;
void setRotation(float angle) override;
const sf::Vector2f &getOrigin() const override;
void setOrigin(float x, float y) override;
void setOrigin(const sf::Vector2f &origin) override;
void flip() override;
void flip(Flippable::Side side) override;
protected:
Entity() = default;
Entity(const std::string &entityId, const std::string &entityName, Team team, Type type, const sf::Vector2f &size, int lifePointMax, int atkDamage);
std::string entityId;
std::string entityName;
GameEntityRole::Role role = GameEntityRole::ENTITYROLE_PLAYER;
Team team = TEAM_PLAYER;
Type type = TYPE_PLAYER;
State state = State::IDLE;
hashmap::unordered_map<std::string, SpriteSheet> sprites{};
int atkDamage = 0;
int lifePointMax = 0;
int lifePoint = 0;
void draw(sf::RenderTarget &target, sf::RenderStates states) const override;
};
#endif //INFINITECONQUEST_ENTITY_H
| true |
14ac51b91220711328ce214d17524e320c7d3bd6 | C++ | AnyTimeTraveler/C-CPP-course | /code/08_PTRN/src/base/Logger.hpp | UTF-8 | 368 | 2.703125 | 3 | [] | no_license | // file Logger.hpp
#ifndef Logger_hpp
#define Logger_hpp
#include <iostream>
class Logger {
static Logger* _theInstance;
public:
virtual void log(std::string message, std::string file="", int line=0) = 0;
static Logger* getInstance();
};
class StdoutLogger: public Logger {
public:
void log(std::string message, std::string file="", int line=0);
};
#endif
| true |
b015a7d2496b7aa8a267b46df0659475a7e6121f | C++ | hungpham2511/toppra | /cpp/src/toppra/geometric_path/piecewise_poly_path.hpp | UTF-8 | 5,118 | 3.03125 | 3 | [
"MIT"
] | permissive | #ifndef TOPPRA_PIECEWISE_POLY_PATH_HPP
#define TOPPRA_PIECEWISE_POLY_PATH_HPP
#include <array>
#include <toppra/geometric_path.hpp>
#include <toppra/toppra.hpp>
#include <toppra/export.hpp>
namespace toppra {
struct BoundaryCond {
BoundaryCond() = default;
/**
* @brief Construct a new BoundaryCond object with a manually specified derivative.
*
* @param order Order of the specified derivative.
* @param values Vector of values. Must have the same size as the path.
*/
BoundaryCond(int order, const std::vector<value_type> &values);
BoundaryCond(int order, const Vector values);
/**
* @brief Construct a new Boundary Cond object with well-known boundary condition.
*
* @param bc_type Possible values: not-a-knot, clamped, natural and manual.
*/
BoundaryCond(std::string bc_type);
enum Type { NotAKnot, Clamped, Natural, Manual};
Type bc_type = NotAKnot;
int order = 0;
Vector values;
};
using BoundaryCondFull = std::array<BoundaryCond, 2>;
/**
* \brief Piecewise polynomial geometric path.
*
* An implementation of a piecewise polynomial geometric path.
*
* The coefficient vector has shape (N, P, D), where N is the number
* segments. For each segment, the i-th row (P index) denotes the
* power, while the j-th column is the degree of freedom. In
* particular,
*
* coeff(0) * dt ^ 3 + coeff(1) * dt ^ 2 + coeff(2) * dt + coeff(3)
*
*
*/
class PiecewisePolyPath : public GeometricPath {
public:
PiecewisePolyPath() = default;
/**
* \brief Construct new piecewise polynomial.
*
* See class docstring for details.
*
* @param coefficients Polynomial coefficients.
* @param breakpoints Vector of breakpoints.
*/
PiecewisePolyPath(const Matrices &coefficients, std::vector<value_type> breakpoints);
/**
* /brief Evaluate the path at given position.
*/
Vector eval_single(value_type, int order = 0) const override;
/**
* /brief Evaluate the path at given positions (vector).
*/
Vectors eval(const Vector &, int order = 0) const override;
/**
* Return the starting and ending path positions.
*/
Bound pathInterval() const override;
void serialize(std::ostream &O) const override;
void deserialize(std::istream &I) override;
/**
* @brief Construct a piecewise Cubic Hermite polynomial.
*
* See https://en.wikipedia.org/wiki/Cubic_Hermite_spline for a good
* description of this interplation scheme.
*
* This function is implemented based on scipy.interpolate.CubicHermiteSpline.
*
* Note that path generates by this function is not guaranteed to have
* continuous acceleration, or the path second-order derivative.
*
* @param positions Robot joints corresponding to the given times. Must have
* the same size as times.
* @param velocities Robot joint velocities.
* @param times Path positions or times. This is the independent variable.
* @return PiecewisePolyPath
*/
static PiecewisePolyPath
CubicHermiteSpline(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
TOPPRA_DEPRECATED static PiecewisePolyPath
constructHermite(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
/**
* @brief Construct a cubic spline.
*
* Interpolate the given joint positions with a spline that is twice
* continuously differentiable. This means the position, velocity and
* acceleration are guaranteed to be continous but not jerk.
*
* This method is modelled after scipy.interpolate.CubicSpline.
*
* @param positions Robot joints corresponding to the given times.
* @param times Path positions or times. This is the independent variable.
* @param bc_type Boundary condition. Currently on fixed boundary condition.
* @return PiecewisePolyPath
*/
static PiecewisePolyPath CubicSpline(const Vectors &positions, const Vector ×, BoundaryCondFull bc_type);
private:
/**
* @brief Calculate coefficients for Hermite spline.
*
* @param positions See the constructor.
* @param velocities
* @param times
*/
void initAsHermite(const Vectors &positions, const Vectors &velocities,
const std::vector<value_type> times);
protected:
static void computeCubicSplineCoefficients(const Vectors &positions,
const Vector ×,
const BoundaryCondFull &bc_type,
Matrices &coefficients);
// static void checkInputArgs(const Vectors &positions, const Vector ×,
// const BoundaryCondFull &bc_type);
// Cubic spline
void reset();
size_t findSegmentIndex(value_type pos) const;
void checkInputArgs();
void computeDerivativesCoefficients();
const Matrix &getCoefficient(size_t seg_index, int order) const;
Matrices m_coefficients, m_coefficients_1, m_coefficients_2;
std::vector<value_type> m_breakpoints;
int m_degree;
};
} // namespace toppra
#endif
| true |
fde3d9c1904e0b11deb7f9eb43a6ec6862a9a986 | C++ | girim/cplusplusPrimerExamples | /STL_Algorithms/modifying/replace_copy_if.cpp | UTF-8 | 542 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <deque>
#include "../point.hpp"
#include "../printSeqContainer.hpp"
int main(int argc, char const *argv[])
{
Point pt0{}, pt1{1, 3}, pt2{5, 4}, pt3{9, 3}, pt4{4}, pt5{2, 8};
std::deque<Point> points = {pt0, pt1, pt2, pt3, pt4};
printSequentialContainer(points);
std::replace_copy_if(points.begin(), points.end(), points.begin(), [](const Point& point){
return (point.getX() == point.getY());
}, pt5);
printSequentialContainer(points);
return 0;
}
| true |
e4a9463427d182d51a1e51b371e48eeab533f546 | C++ | trxo/cpp_study_notes | /chapter3-Function and function template/3.11函数返回值作为函数的参数/main.cpp | UTF-8 | 191 | 3 | 3 | [
"AFL-3.0"
] | permissive | #include <iostream>
using namespace std;
int max(int,int);
int main()
{
cout << max(55, max(25, 39)) << endl;
}
int max(int m1, int m2){
return m1 > m2 ? m1 : m2;
}
// print
//55 | true |
b0c9046694bafdd4b33ed58b7a92aebebf6bb9ad | C++ | DcmTruman/my_acm_training | /UVA/12716/15177670_AC_970ms_0kB.cpp | UTF-8 | 390 | 2.765625 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
using namespace std;
int const maxn = 30000005;
int ans[maxn];
int main()
{
for(int c = 1;c < maxn; c++)
{
for(int a = c + c; a < maxn; a += c){
if((a ^ (a - c)) == c)ans[a] ++;
}
ans[c] += ans[c - 1];
}
int T;
scanf("%d", &T);
for(int t = 1; t <= T; t++)
{
int n;
scanf("%d", &n);
printf("Case %d: %d\n", t, ans[n]);
}
} | true |
59ce221fef423f6ad8b9716aa6b071a8faeac4eb | C++ | roshihie/At_Coder | /ABC_B/ABC072_B_OddString.cpp | UTF-8 | 379 | 3.203125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void fnInput(string& rsStr)
{
cin >> rsStr;
}
string fnOddString(string sStr)
{
string sOddStr = "";
for (int i = 0; i < sStr.size(); i++)
if (i % 2 == 0) sOddStr += sStr[i];
return sOddStr;
}
int main()
{
string sStr;
fnInput(sStr);
cout << fnOddString(sStr) << endl;
return 0;
}
| true |
92112db47df54570da0d4dba0a324dd658795ced | C++ | Feldrise/FeldEngineFirstCode | /FeldEngine-Core/src/Maths/Vector4.h | UTF-8 | 3,420 | 3.015625 | 3 | [
"MIT"
] | permissive | /*
* The MIT License(MIT)
*
* Copyright(c) 2016 Victor DENIS (victordenis01@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <iostream>
namespace Fd {
namespace Maths {
template <typename T>
struct Vector4
{
T x{};
T y{};
T z{};
T w{};
Vector4() = default;
Vector4(const T& x, const T& y, const T& z, const T& w) {
this->x = x;
this->y = y;
this->z = z;
this->w = w;
}
Vector4& add(const Vector4<T>& other) {
x += other.x;
y += other.y;
z += other.z;
w += other.w;
return *this;
}
Vector4& substract(const Vector4<T>& other) {
x -= other.x;
y -= other.y;
z -= other.z;
w -= other.w;
return *this;
}
Vector4& multiply(const Vector4<T>& other) {
x *= other.x;
y *= other.y;
z *= other.z;
w *= other.w;
return *this;
}
Vector4& divide(const Vector4<T>& other) {
x /= other.x;
y /= other.y;
z /= other.z;
w /= other.w;
return *this;
}
bool operator==(const Vector4<T>& other) {
return x == other.x && y == other.y && z == other.z && w == other.w;
}
bool operator!=(const Vector4<T>& other) {
return !(*this == other);
}
Vector4& operator+=(const Vector4<T>& other) {
return add(other);
}
Vector4& operator-=(const Vector4<T>& other) {
return substract(other);
}
Vector4& operator*=(const Vector4<T>& other) {
return multiply(other);
}
Vector4& operator/=(const Vector4<T>& other) {
return divide(other);
}
};
template <typename T>
Vector4<T> operator+(Vector4<T> left, const Vector4<T>& right) {
return left.add(right);
}
template <typename T>
Vector4<T> operator-(Vector4<T> left, const Vector4<T>& right) {
return left.substract(right);
}
template <typename T>
Vector4<T> operator*(Vector4<T> left, const Vector4<T>& right) {
return left.multiply(right);
}
template <typename T>
Vector4<T> operator/(Vector4<T> left, const Vector4<T>& right) {
return left.divide(right);
}
template <typename T>
std::ostream& operator<< (std::ostream& stream, const Vector4<T>& vector) {
stream << "Vector4 : (" << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w << ")";
return stream;
}
using vec4 = Vector4<float>;
using vec4i = Vector4<int>;
using vec4u = Vector4<unsigned>;
using vec4l = Vector4<long>;
}
} | true |
d32ca12c35512145660255d5c6de530d6d19eb14 | C++ | mrLarbi/CPAEgrep | /include/FileList.h | UTF-8 | 408 | 2.640625 | 3 | [] | no_license | #ifndef H_FILELIST
#define H_FILELIST
#include <string>
#include <vector>
class FileList
{
private:
static FileList* instance;
std::vector<std::string> files;
FileList();
FileList(const FileList&);
void operator=(const FileList&);
public:
static FileList* getFileListInstance();
void addFile(std::string& name);
int nbFiles();
std::string getFileName(int index);
};
#endif
| true |
ddf585d65350667f161897afe3f7dae0fa353cce | C++ | AbhijithMadhav/Notes | /Programming, Data Structures and Algorithms/src/Kernighan and ritchie/4-7.cpp | UTF-8 | 408 | 2.90625 | 3 | [] | no_license | /* Exercise 4-7. Write a routine ungets(s) that will push back an entire string onto the input.
Should ungets know about buf and bufp, or should it just use ungetch?
*/
#include <stdio.h>
#include "calc.h"
#define MAX 10
int main()
{
char s[MAX] = "012345678";
int i = 0;
// while (i != 10)
s[i++] = getch();
s[i] = '\0';
ungets("876");
putchar(getch());
getchar();
getchar();
} | true |
f2681e443f548a08572e131d2b30057004e98ef2 | C++ | NamaWho/University | /Fondamenti di Programmazione/Lab07/main.cpp | UTF-8 | 6,176 | 3.84375 | 4 | [
"MIT"
] | permissive | /**
* @author Daniel Namaki Ghaneh
* @date 11/11/2020
*/
#include <iostream>
using namespace std;
void componenti_negative(const int vett[], const unsigned int l, int *&newVect, unsigned int &lengthNewVect);
void first();
int somma_diag(const int mat[][3]);
void second();
int somma_diag(const int *mat, int n);
void third();
int *riempi_matrice(int r, int c);
void fourth();
int* trasposta(const int* matr, int n);
void fifth();
//Number of rows and columns of the matrix in the given exercises
const int DIM = 3;
int main() {
int choice;
do {
cout << "\nInserire la propria scelta: \n"
"1 per Creazione vettore sullo heap\n"
"2 per Somma diagonali\n"
"3 per Somma diagonali (versione 2)\n"
"4 per Serpente di numeri\n"
"5 per Matrice trasposta\n"
"Altro numero per uscire\n";
cin >> choice;
switch (choice) {
case 1:
first();
break;
case 2:
second();
break;
case 3:
third();
break;
case 4:
fourth();
break;
case 5:
fifth();
break;
default:
break;
}
} while (choice > 0 && choice < 6);
return 0;
}
void componenti_negative(const int vett[], const unsigned int l, int *&newVect, unsigned int &lengthNewVect) {
// Negative numbers count
for (int i = 0; i < l; ++i)
if (vett[i] < 0) lengthNewVect++;
// Allocation in the heap memory of the new array
newVect = new int[lengthNewVect];
// Set the new array
for (int i = 0, j = 0; i < l; ++i) {
if (vett[i] < 0) {
newVect[j] = vett[i];
j++;
}
}
}
void first() {
const unsigned int LENGTH = 6;
const int v[LENGTH] = {11, -22, 4, -3, 18, -1};
unsigned int lengthVettNeg = 0; // Length which will be passed by reference to the function and will be modified inside it
int *vettNeg = nullptr; // To be sure, always initialize the pointer to nullptr
componenti_negative(v, LENGTH, vettNeg, lengthVettNeg);
cout << "Vettore di partenza: " << endl;
for (int i = 0; i < LENGTH; ++i) {
cout << v[i] << " ";
}
cout << endl;
cout << "Nuovo vettore con sole componenti negative: " << endl;
for (int i = 0; i < lengthVettNeg; ++i) {
cout << vettNeg[i] << " ";
}
cout << endl;
cout << "Deallocazione del vettore creato dallo Heap \n";
delete[] vettNeg;
vettNeg = nullptr;
}
int somma_diag(const int mat[][DIM]) {
int sum = 0;
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
// Sum if it's a cell located in the principal diagonal
// or in the secondary one (where i+j = DIM-1)
if ((i == j) || (i + j == (DIM - 1)))
sum += mat[i][j];
}
}
return sum;
}
void second() {
int m[DIM][DIM];
cout << "Inserisci 9 interi: \n";
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cin >> m[i][j];
}
}
cout << "La somma degli elementi sulla diag. princ. e sec. e': " << somma_diag(m) << "\n";
}
int somma_diag(const int *mat, const int n) {
int sum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
// Sum if it's a cell located in the principal diagonal
// or in the secondary one
if ((i == j) || (i + j == (n - 1)))
sum += mat[i * n + j];
}
}
return sum;
}
void third() {
int m[DIM][DIM];
cout << "Inserisci 9 interi: \n";
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cin >> m[i][j];
}
}
cout << "La somma degli elementi sulla diag. princ. e sec. e': " << somma_diag(&m[0][0], DIM) << "\n";
}
int *riempi_matrice(int r, int c) {
int *mat = new int[r * c];
unsigned int count = 0;
// Fill the matrix
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
// If odd row, print number in the reverse order
if (i % 2) mat[i * c + ((c-1) - j)] = ++count; //prefixed increment
// If even, print them normally in order
else mat[i * c + j] = ++count; //prefixed increment
}
}
return mat;
}
void fourth() {
int r, c;
int *matrix = nullptr;
cout << "Inserire R: \n";
do {
cin >> r;
} while (r < 1);
cout << "Inserire C: \n";
do {
cin >> c;
} while (c < 1);
// Store the dynamic matrix first address in a pointer
matrix = riempi_matrice(r, c);
// Print the matrix
for (int i = 0; i < r; ++i) {
for (int j = 0; j < c; ++j) {
cout << matrix[i * c + j] << "\t";
}
cout << "\n";
}
delete[] matrix;
matrix = nullptr;
}
int* trasposta(const int* matr, const int n){
int *transposed = new int [n*n]; // Create a new matrix in the heap memory
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
//Inverting indexes to transpose the matrix
transposed[i*n+j] = matr[j*n+i];
}
}
return transposed;
}
void fifth(){
int matrix [DIM][DIM];
int *matTransposed = nullptr;
cout << "Inserisci 9 interi: \n";
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cin >> matrix[i][j];
}
}
// Print the matrix
cout << "Matrice di partenza: \n";
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cout << matrix[i][j]<< "\t";
}
cout << "\n";
}
//Retrieve the transposed matrix
matTransposed = trasposta(&matrix[0][0], DIM);
//Print the transposed matrix
cout << "\nMatrice trasposta: \n";
for (int i = 0; i < DIM; ++i) {
for (int j = 0; j < DIM; ++j) {
cout << matTransposed[i*DIM+j]<< "\t";
}
cout << "\n";
}
} | true |
b5c96c0a66b68763235d27c9b877163ce957abd5 | C++ | petru-d/leetcode-solutions-reboot | /problems/p1332.h | UTF-8 | 523 | 3.15625 | 3 | [] | no_license | #pragma once
#include <string>
namespace p1332
{
class Solution
{
public:
int removePalindromeSub(std::string s)
{
auto S = s.size();
if (S == 0)
return 0;
bool is_palindrome = true;
for (size_t i = 0; i <= S / 2; ++i)
if (s[i] != s[S - i - 1])
{
is_palindrome = false;
break;
}
return is_palindrome ? 1 : 2;
}
};
}
| true |
16efbf1c6ec159552633fcf099e0e79429a5f606 | C++ | yistoyanova18/SP2020-Exercises | /Last Digit Ultimate/Last Digit Ultimate.cpp | UTF-8 | 254 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool lastDig(int a, int b, int c)
{
int aa = a % 10;
int bb = b % 10;
int cc = c % 10;
int d = aa * bb;
if (d % 10 == cc)
{
return true;
}
return false;
}
int main()
{
cout << lastDig(154, 52, 254);
} | true |
ebd39751bca481dc07ae7ced506bbfd804c493ae | C++ | eburghardt/cs252WebApp | /server/src/bag.cpp | UTF-8 | 1,261 | 3.390625 | 3 | [] | no_license | /**
* @file bag.cpp
* @brief This file models a bag of tiles. Players will get tiles from here, and the game will end when the bag is empty.
*
* @author Eric Burghardt
* @date 11/30/2017
*/
#include "../include/bag.hpp"
#include <ctime>
#include <cstdlib>
Bag::Bag() {
add('a', 9 * 15);
add('b', 2 * 15);
add('c', 2 * 15);
add('d', 4 * 15);
add('e', 12 * 15);
add('f', 2 * 15);
add('g', 3 * 15);
add('h', 2 * 15);
add('i', 9 * 15);
add('j', 1 * 15);
add('k', 1 * 15);
add('l', 4 * 15);
add('m', 2 * 15);
add('n', 6 * 15);
add('o', 8 * 15);
add('p', 2 * 15);
add('q', 1 * 15);
add('r', 6 * 15);
add('s', 4 * 15);
add('t', 6 * 15);
add('u', 4 * 15);
add('v', 2 * 15);
add('w', 2 * 15);
add('x', 1 * 15);
add('y', 2 * 15);
add('z', 1 * 15);
//seed random number generator
srand((unsigned)time(NULL));
}
void Bag::add(char c, int num) {
for(int i = 0; i < num; i++) {
tiles.insert(tiles.end(), c);
}
}
char Bag::getTile() {
//randomly select a tile, swap it with the back, pop the back and return it
int random = rand() % tiles.size();
char out = tiles.at(random);
tiles.erase(tiles.begin() + random);
return out;
}
int Bag::getNumTilesRemaining() {
return tiles.size();
}
bool Bag::isEmpty() {
return tiles.empty();
}
| true |
63ae22124e67cb065807ecc6604f8083a28f3cce | C++ | JinnyJingLuo/Expanse | /Paradis_Hydrogen/ParadisJHU06012020/ParadisJHU06012020/ezmath/Edge.h | UTF-8 | 953 | 2.65625 | 3 | [] | no_license | #ifndef EDGE_H_
#define EDGE_H_
#include "GenericNode.h"
#include "GeometricComponent.h"
#include "Vector.h"
#include "Face.h"
using namespace EZ;
namespace GeometrySystem
{
class Edge : public GeometricComponent
{
public:
Edge();
Edge(const Edge& oEdge);
~Edge();
Edge& operator=(const Edge& oEdge);
void Reset();
void SetEndPoints(GenericNode* poStartPoint,GenericNode* poEndPoint);
void SetRightFace(Face* poFace);
void SetLeftFace(Face* poFace);
GenericNode* GetStartPoint() const;
GenericNode* GetEndPoint() const;
Face* GetRightFace() const;
Face* GetLeftFace() const;
Face* GetOtherFace(Face* poFace) const;
void ReplaceFace(Face* poOldFace,Face* poNewFace);
string ToString() const;
void RemoveFace(Face* poFace);
Vector GetVector() const;
double GetLength() const;
private:
protected:
void Initialize();
GenericNode* m_poStartPoint;
GenericNode* m_poEndPoint;
Face* m_poRightFace;
Face* m_poLeftFace;
};
}
#endif
| true |
63c29f8857d1717ae956b70bdb3827d2b8893d0f | C++ | cnanlmlin/piccante | /include/gl/filtering/filter_scatter.hpp | UTF-8 | 7,428 | 2.53125 | 3 | [] | no_license | /*
PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante
Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle
PICCANTE is free software; you can redistribute it and/or modify
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 3.0 of
the License, or (at your option) any later version.
PICCANTE is distributed in the hope that it will be useful, but
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License
( http://www.gnu.org/licenses/lgpl-3.0.html ) for more details.
*/
#ifndef PIC_GL_FILTERING_FILTER_SCATTER_HPP
#define PIC_GL_FILTERING_FILTER_SCATTER_HPP
#include "gl/filtering/filter.hpp"
namespace pic {
/**
* @brief The FilterGLScatter class implement
* the bilateral grid approximation of the bilateral
* filter.
*/
class FilterGLScatter: public FilterGL
{
protected:
GLfloat *vertex_array;
int nVertex_array;
GLuint vbo, vao;
/**
* @brief GenerateVA
* @param width
* @param height
*/
void GenerateVA(int width, int height);
/**
* @brief InitShaders
*/
void InitShaders();
/**
* @brief FragmentShader
*/
void FragmentShader();
float s_S, s_R, mul_E;
public:
/**
* @brief FilterGLScatter
* @param s_S
* @param s_R
* @param width
* @param height
*/
FilterGLScatter(float s_S, float s_R, int width, int height);
~FilterGLScatter();
/**
* @brief Update
* @param s_S
* @param s_R
*/
void Update(float s_S, float s_R);
/**
* @brief Process
* @param imgIn
* @param imgOut
* @return
*/
ImageRAWGL *Process(ImageRAWGLVec imgIn, ImageRAWGL *imgOut);
};
FilterGLScatter::FilterGLScatter(float s_S, float s_R, int width, int height)
{
this->s_S = s_S;
this->s_R = s_R;
GenerateVA(width, height);
FragmentShader();
InitShaders();
}
FilterGLScatter::~FilterGLScatter()
{
if(vertex_array != NULL) {
delete[] vertex_array;
vertex_array = NULL;
}
if(vbo != 0) {
glDeleteBuffers(1, &vbo);
vbo = 0;
}
if(vao != 0) {
glDeleteVertexArrays(1, &vao);
vao = 0;
}
}
void FilterGLScatter::GenerateVA(int width, int height)
{
vertex_array = new GLfloat[2 * width * height];
nVertex_array = width * height;
int index = 0;
for(int i = 0; i < height; i++) {
float i_f = float(i);
for(int j = 0; j < width; j++) {
vertex_array[index++] = float(j);
vertex_array[index++] = i_f;
}
}
//Vertex Buffer Object
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 2 * nVertex_array * sizeof(GLfloat), vertex_array,
GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
//Vertex Array Object
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void FilterGLScatter::FragmentShader()
{
vertex_source = GLW_STRINGFY(
uniform sampler2D u_tex;
uniform float s_S;
uniform float mul_E;
layout(location = 0) in vec2 a_position;
flat out vec4 v2g_color;
flat out int v2g_layer;
void main(void) {
//Texture Fetch
vec4 data = texelFetch(u_tex, ivec2(a_position), 0);
//Output coordinate
vec2 coord = vec2(a_position) / vec2(textureSize(u_tex, 0) - ivec2(1));
coord = coord * 2.0 - vec2(1.0);
v2g_color = vec4(data.xyz, 1.0);
v2g_layer = int(floor(dot(data.xyz, vec3(1.0)) * mul_E));
gl_Position = vec4(coord, 0.0, 1.0);
}
);
geometry_source = GLW_STRINGFY(
layout(points) in;
layout(points, max_vertices = 1) out;
flat in vec4 v2g_color[1];
flat in int v2g_layer[1];
flat out vec4 g2f_color;
void main(void) {
g2f_color = v2g_color[0];
gl_Layer = v2g_layer[0];
gl_PointSize = 1.0;
gl_Position = gl_in[0].gl_Position;
EmitVertex();
EndPrimitive();
}
);
fragment_source = GLW_STRINGFY(
flat in vec4 g2f_color;
layout(location = 0) out vec4 f_color;
void main(void) {
f_color = g2f_color;
}
);
}
void FilterGLScatter::InitShaders()
{
filteringProgram.setup(glw::version("330"), vertex_source, geometry_source, fragment_source,
GL_POINTS, GL_POINTS, 1);
#ifdef PIC_DEBUG
printf("[FilterGLScatter shader log]\n%s\n", filteringProgram.log().c_str());
#endif
glw::bind_program(filteringProgram);
filteringProgram.attribute_source("a_position", 0);
filteringProgram.fragment_target("f_color", 0);
filteringProgram.relink();
glw::bind_program(0);
Update(s_S, s_R);
}
void FilterGLScatter::Update(float s_S, float s_R)
{
this->s_S = s_S;
this->s_R = s_R;
mul_E = s_R / 3.0f;
#ifdef PIC_DEBUG
printf("Rate S: %f Rate R: %f Mul E: %f\n", s_S, s_R, mul_E);
#endif
glw::bind_program(filteringProgram);
filteringProgram.uniform("u_tex", 0);
filteringProgram.uniform("s_S", s_S);
filteringProgram.uniform("mul_E", mul_E);
glw::bind_program(0);
}
ImageRAWGL *FilterGLScatter::Process(ImageRAWGLVec imgIn, ImageRAWGL *imgOut)
{
if(imgIn.size() < 1 && imgIn[0] == NULL) {
return imgOut;
}
int width, height, range;
width = int(ceilf(float(imgIn[0]->width) * s_S));
height = int(ceilf(float(imgIn[0]->height) * s_S));
range = int(ceilf(s_R));
if(imgOut == NULL) {
imgOut = new ImageRAWGL(range + 1, width + 1, height + 1,
imgIn[0]->channels + 1, IMG_GPU, GL_TEXTURE_3D);
}
if(fbo == NULL) {
fbo = new Fbo();
fbo->create(width + 1, height + 1, range + 1, false, imgOut->getTexture());
}
//Rendering
fbo->bind();
glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
imgOut->getTexture(), 0);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
//Shaders
glw::bind_program(filteringProgram);
//Textures
glActiveTexture(GL_TEXTURE0);
imgIn[0]->bindTexture();
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glBindVertexArray(vao);
glDrawArrays(GL_POINTS, 0, nVertex_array);
glBindVertexArray(0);
glDisable(GL_BLEND);
//Fbo
fbo->unbind();
//Shaders
glw::bind_program(0);
//Textures
glActiveTexture(GL_TEXTURE0);
imgIn[0]->unBindTexture();
return imgOut;
}
} // end namespace pic
#endif /* PIC_GL_FILTERING_FILTER_SCATTER_HPP */
| true |
6e5f96994d3ef430c4f84540c3e7053d96214ebc | C++ | sohana08/week_of_code | /prime_number.cpp | UTF-8 | 920 | 3.359375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool primeorNot(int n ) {
int flag=0;
if (n<=1){
return false;
}
for(int i=2; i<=n; i++) {
if(n%i == 0) {
flag++;
}
}
if(flag>1){
return false;
}else {
return true;
}
}
int main() {
int T;
cin>>T;
int n[T];
bool isPrime;
for(int i = 0; i<T; i++){
cin>>n[i];
isPrime = primeorNot(n[i]);
if(isPrime) {
cout<<"yes prime";
} else {
cout<<"not prime";
}
}
return 0;
}
// #include <bits/stdc++.h>
// using namespace std;
// bool isPrime(int n) {
// for (int i = 2; i <= sqrt(n); i++)
// if (n % i == 0) return false;
// return true;
// }
// int main() {
// int T;
// cin >> T;
// for (int i = 0; i < T; i++) {
// int n;
// cin >> n;
// if (n >= 2 && isPrime(n)) cout << "Prime" << endl;
// else cout << "Not prime" << endl;
// }
// }
| true |
1df943233ae2092e36666ecab1b4b3e0cec1c4b7 | C++ | bhamon/codingDojo-2016-arkanoid | /tests-arkanoid-model/TestVector2.cpp | UTF-8 | 3,575 | 3.203125 | 3 | [] | no_license | #include "CppUnitTest.h"
#include <arkanoid-model\Vector2.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace tests
{
TEST_CLASS(TestVector2)
{
public:
TEST_METHOD(defaultConstructor)
{
math::Vector2<int> v;
Assert::AreEqual(0, v.getX());
Assert::AreEqual(0, v.getY());
}
TEST_METHOD(constructor)
{
math::Vector2<int> v(12, -259);
Assert::AreEqual(12, v.getX());
Assert::AreEqual(-259, v.getY());
}
TEST_METHOD(copyConstructor)
{
math::Vector2<int> v1(-85, 123);
math::Vector2<int> v2(v1);
Assert::AreEqual(-85, v2.getX());
Assert::AreEqual(123, v2.getY());
}
TEST_METHOD(affectationOperator)
{
math::Vector2<int> v1(-78, -12);
math::Vector2<int> v2;
v2 = v1;
Assert::AreEqual(-78, v2.getX());
Assert::AreEqual(-12, v2.getY());
}
TEST_METHOD(castOperator)
{
math::Vector2<float> v1(12.3f, 32.56f);
math::Vector2<int> v2(v1);
Assert::AreEqual(12, v2.getX());
Assert::AreEqual(32, v2.getY());
}
TEST_METHOD(rawAccess)
{
math::Vector2<int> v(12, 51);
Assert::AreEqual(12, v.getData()[0]);
Assert::AreEqual(12, v[0]);
Assert::AreEqual(51, v.getData()[1]);
Assert::AreEqual(51, v[1]);
v.data()[0] = -52;
v.data()[1] = -8;
Assert::AreEqual(-52, v.getX());
Assert::AreEqual(-8, v.getY());
}
TEST_METHOD(setters)
{
math::Vector2<int> v;
v.setX(-2);
v.setY(-4);
Assert::AreEqual(-2, v.getX());
Assert::AreEqual(-4, v.getY());
v.x() = 7;
v.y() = 9;
Assert::AreEqual(7, v.getX());
Assert::AreEqual(9, v.getY());
}
TEST_METHOD(addition)
{
math::Vector2<int> v1(0, -9);
math::Vector2<int> v2(12, 9);
math::Vector2<int> v3(v1 + v2);
v1 += v2;
Assert::AreEqual(12, v1.getX());
Assert::AreEqual(0, v1.getY());
Assert::AreEqual(12, v3.getX());
Assert::AreEqual(0, v3.getY());
}
TEST_METHOD(subtraction)
{
math::Vector2<int> v1(10, -8);
math::Vector2<int> v2(-1, 2);
math::Vector2<int> v3(v1 - v2);
v1 -= v2;
Assert::AreEqual(11, v1.getX());
Assert::AreEqual(-10, v1.getY());
Assert::AreEqual(11, v3.getX());
Assert::AreEqual(-10, v3.getY());
}
TEST_METHOD(multiplication)
{
math::Vector2<int> v1(10, -8);
math::Vector2<int> v2(v1 * 4);
v1 *= 4;
Assert::AreEqual(40, v1.getX());
Assert::AreEqual(-32, v1.getY());
Assert::AreEqual(40, v2.getX());
Assert::AreEqual(-32, v2.getY());
}
TEST_METHOD(division)
{
math::Vector2<int> v1(12, -4);
math::Vector2<int> v2(v1 / 2);
v1 /= 2;
Assert::AreEqual(6, v1.getX());
Assert::AreEqual(-2, v1.getY());
Assert::AreEqual(6, v2.getX());
Assert::AreEqual(-2, v2.getY());
}
TEST_METHOD(magnitude)
{
math::Vector2<float> v(3.0f, -4.0f);
Assert::AreEqual(25.0f, v.getSquaredMagnitude(), 0.0001f);
Assert::AreEqual(5.0f, v.getMagnitude(), 0.0001f);
}
TEST_METHOD(normalization)
{
math::Vector2<float> v1(3.0f, -4.0f);
math::Vector2<float> v2(v1.getNormalized());
v1.normalize();
Assert::AreEqual(0.6f, v1.getX(), 0.0001f);
Assert::AreEqual(-0.8f, v1.getY(), 0.0001f);
Assert::AreEqual(0.6f, v2.getX(), 0.0001f);
Assert::AreEqual(-0.8f, v2.getY(), 0.0001f);
}
TEST_METHOD(inverse)
{
math::Vector2<int> v1(3, -4);
math::Vector2<int> v2(-v1);
Assert::AreEqual(-3, v2.getX());
Assert::AreEqual(4, v2.getY());
}
TEST_METHOD(dot)
{
math::Vector2<int> v1(3, -4);
math::Vector2<int> v2(-2, -1);
int dot = v1 * v2;
Assert::AreEqual(-2, dot);
}
};
} | true |
2acd18dd51902b551d4fff1aff0ec6af07fdbb9b | C++ | corea1314/delirium-wars | /backup/Camera/Camera.cpp | UTF-8 | 2,219 | 2.578125 | 3 | [] | no_license | #include "Camera.h"
#include "Engine/Engine.h"
#include "Engine/Entities/Clock/Clock.h"
CCamera::CCamera()
{
m_MovementData.bMoving = false;
m_ZoomData.bZooming = false;
m_vCurrPos.Set(0,0);
m_fCurrZoom = 1.0f; // 1X
}
void CCamera::Goto( Vector2 in_vNewPos, float in_fDelayToDest )
{
m_MovementData.vOPos = m_vCurrPos;
m_MovementData.vDPos = in_vNewPos;
m_MovementData.fOTime = GetEngine()->GetClock()->GetTotalTime();
m_MovementData.fDuration = in_fDelayToDest;
m_MovementData.fDTime = m_MovementData.fOTime + m_MovementData.fDuration;
m_MovementData.bMoving = true;
}
void CCamera::ZoomTo( float in_fNewZoom, float in_fDelayToDest )
{
m_ZoomData.fOZoom = m_fCurrZoom;
m_ZoomData.fDZoom = in_fNewZoom;
m_ZoomData.fOTime = GetEngine()->GetClock()->GetTotalTime();
m_ZoomData.fDuration = in_fDelayToDest;
m_ZoomData.fDTime = m_ZoomData.fOTime + m_ZoomData.fDuration;
m_ZoomData.bZooming = true;
}
void CCamera::Update( float in_fDeltaTime )
{
if( m_MovementData.bMoving )
{
float tNow = GetEngine()->GetClock()->GetTotalTime();
if( tNow > m_MovementData.fDTime )
{
// reached destination
m_vCurrPos = m_MovementData.vDPos;
m_MovementData.bMoving = false;
}
else
{
float fRatio = SMOOTH_STEP( m_MovementData.fOTime, m_MovementData.fDTime, tNow );
m_vCurrPos.x = LERP( m_MovementData.vOPos.x, m_MovementData.vDPos.x, fRatio );
m_vCurrPos.y = LERP( m_MovementData.vOPos.y, m_MovementData.vDPos.y, fRatio );
}
}
if( m_ZoomData.bZooming )
{
float tNow = GetEngine()->GetClock()->GetTotalTime();
if( tNow > m_ZoomData.fDTime )
{
// reached zoom level
m_fCurrZoom = m_ZoomData.fDZoom;
m_ZoomData.bZooming = false;
}
else
{
float fRatio = SMOOTH_STEP( m_ZoomData.fOTime, m_ZoomData.fDTime, tNow );
m_fCurrZoom = LERP( m_ZoomData.fOZoom, m_ZoomData.fDZoom, fRatio );
}
}
}
void CCamera::Connect( CEngine* in_pEngine )
{
m_pEngine = in_pEngine;
GetEngine()->Connect_OnUpdate( this, &CCamera::Update );
}
void CCamera::Disconnect( CEngine* in_pEngine )
{
in_pEngine->Disconnect_OnUpdate( this );
assert(m_pEngine==in_pEngine);
m_pEngine = 0;
}
| true |
4d0418aa026ea8128def5b52868dc3a946b76321 | C++ | triffon/oop-2019-20 | /exercises/3/week3/main.cpp | UTF-8 | 398 | 3.34375 | 3 | [
"MIT"
] | permissive | #include<iostream>
using namespace std;
class Person{
public:
Person(){
cout << "constructor" << endl;
};
Person(Person& other){
cout << "copy constructor" << endl;
};
};
int swap(int& a, int& b){
int temp = a;
a = b;
b = temp;
}
///Person p1 = p2;
void func(Person p1){
}
int main(){
Person p2;
func(p2);
return 0;
}
| true |
cfe74324438a6cc8bee0d6443c517808d9abe2c4 | C++ | Hotiakov/PiAA_8304 | /Butko_Artem/CAA_lab4/main.cpp | UTF-8 | 1,213 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
void getPrefix(std::string pattern, std::vector<int>& prefix)
{
int index = 0;
for (int i = 1; i < pattern.size(); ++i)
{
while (index != -1 && pattern[index] != pattern[i]) index--;
index++;
prefix.push_back(index);
}
}
void algorithmKMP(std::string pattern, std::vector<int>& result)
{
int index = 0;
char symb;
int counter = 0;
std::vector<int> prefix{0};
getPrefix(pattern, prefix);
while (std::cin >> symb)
{
counter++;
while (index > 0 && pattern[index] != symb) index = prefix[index - 1];
if (pattern[index] == symb) index++;
if (index == pattern.size()) result.push_back(counter - index + 1);
}
if (result.empty()) result.push_back(-1);
}
void output(std::vector<int> result)
{
for(int i = 0; i < result.size(); ++i)
{
std::cout << result[i];
if (i + 1 != result.size()) std::cout << " ,";
}
std::cout << std::endl;
}
int main()
{
std::string prefix;
std::vector<int> result;
std::getline(std::cin, prefix);
algorithmKMP(prefix, result);
output(result);
}
/*
defabc
abcdef
*/
| true |
897b197dd7e1cbe8f1e9d25196ae096af1bae2dd | C++ | spelka/LinuxChat | /server.cpp | UTF-8 | 4,212 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <strings.h>
#include <arpa/inet.h>
#include <unistd.h>
#define DEFAULT_PORT 7000
#define MAX_CLIENTS 5
#define BUFFER_LENGTH 255
int main ()
{
//socket handling variables
int listen_socket, client_socket;
int retval; //holds a return value for testing failures
struct sockaddr_in listen_address, client_address;
unsigned int client_address_size;
// file descriptor handling variables
int max_filedescriptors; //the number of file descriptors used
fd_set master_filedescriptors; //the master set of file descriptors
fd_set copy_filedescriptors; //holds a copy of the master set
int clients[MAX_CLIENTS];
//variables dealing with reading and echoing
int i = 0;
int max_array_index = -1;
char* byte_pointer;
int bytes_to_read;
int bytes_read;
char read_buffer[BUFFER_LENGTH];
//start server
//create a stream socket
listen_socket = socket(AF_INET, SOCK_STREAM, 0);
if ( listen_socket == -1 )
{
//failed to create socket
return 1;
}
//set SO_REUSEADDR for the listen socket
int arg = 1;
retval = setsockopt ( listen_socket, SOL_SOCKET, SO_REUSEADDR, &arg, sizeof(arg) );
if ( retval == -1 )
{
//set socket option failure
return 1;
}
//set up a address structure
bzero( (char*) &listen_address, sizeof( struct sockaddr_in ) );
listen_address.sin_family = AF_INET;
listen_address.sin_port = htons( DEFAULT_PORT );
listen_address.sin_addr.s_addr = htonl ( INADDR_ANY );
//bind the socket to accept connections from any ip address
retval = bind( listen_socket, ( struct sockaddr* ) &listen_address, sizeof( listen_address ) );
if ( retval == -1 )
{
//bind failed
return 1;
}
//listen for connections
listen( listen_socket, 5 );
//set the largest file descriptor
max_filedescriptors = listen_socket;
//initialize the master file descriptor set and add the listen socket to it
FD_ZERO( &master_filedescriptors );
FD_SET( listen_socket, &master_filedescriptors );
//do work
//go into a forever loop
for (;;)
{
//copy the master fd set to a new variable
copy_filedescriptors = master_filedescriptors;
//call select to monitor multiple file descriptors
int num_ready_descriptors = select ( ( max_filedescriptors + 1 ), ©_filedescriptors, NULL, NULL, NULL );
if ( num_ready_descriptors == -1 )
{
//select failure
return 1;
}
//check for any new connections
if (FD_ISSET(listen_socket, ©_filedescriptors))
{
//accept the new socket request
client_address_size = sizeof ( client_address );
client_socket = accept ( listen_socket, (struct sockaddr *) &client_address, &client_address_size );
if ( client_socket == -1)
{
//failed to accept socket
}
//add the new socket to the file descriptor set
for ( i = 0 ; i < MAX_CLIENTS ; i++ )
{
if ( clients[i] < 0 )
{
//save the descriptor
clients[i] = client_socket;
break;
}
}
if ( i == FD_SETSIZE )
{
//too many clients
}
else
{
//add the descriptor to the set
FD_SET ( client_socket, &master_filedescriptors );
if ( client_socket > max_filedescriptors )
{
//update max_filedescriptors
max_filedescriptors = client_socket;
}
if ( i < max_array_index )
{
//update max index in array
max_array_index = i;
}
if ( --num_ready_descriptors <= 0 )
{
//no more descriptors ready
continue;
}
}
}
//check for any new data
for ( i = 0 ; i <= max_array_index ; i++ )
{
//if the socket has no data, skip it
if ( (client_socket = clients[i]) < 0 )
{
continue;
}
//??
if ( FD_ISSET ( client_socket, ©_filedescriptors ) )
{
byte_pointer = read_buffer;
bytes_to_read = BUFFER_LENGTH;
//read data in
while ( ( bytes_read = read ( client_socket, byte_pointer, bytes_to_read ) ) > 0 )
{
byte_pointer += bytes_read;
bytes_to_read -= bytes_read;
}
//echo data to all connected clients
for ( i = 0 ; i < clients[i] ; i++ )
{
write ( clients[i], read_buffer, BUFFER_LENGTH );
}
}
}
}
return 0;
} | true |
0391af017c4e158abb87378a1c61c7c65b7a982b | C++ | icgw/practice | /LeetCode/C++/0099._Recover_Binary_Search_Tree/solution.h | UTF-8 | 915 | 3.171875 | 3 | [
"MIT"
] | permissive | /*
* solution.h
* Copyright (C) 2021 Guowei Chen <icgw@outlook.com>
*
* Distributed under terms of the Apache license.
*/
#ifndef _SOLUTION_H_
#define _SOLUTION_H_
#include <algorithm>
using std::swap;
#include "../data_structures.hpp"
class Solution {
private:
TreeNode* firstWrongNode = nullptr;
TreeNode* secondWrongNode = nullptr;
TreeNode* previousNode = nullptr;
void traverse(TreeNode* root) {
if (!root) return;
traverse(root->left);
if (firstWrongNode == nullptr && previousNode && previousNode->val >= root->val) {
firstWrongNode = previousNode;
}
if (firstWrongNode != nullptr && previousNode && previousNode->val >= root->val) {
secondWrongNode = root;
}
previousNode = root;
traverse(root->right);
}
public:
void recoverTree(TreeNode* root) {
traverse(root);
swap(firstWrongNode->val, secondWrongNode->val);
}
};
#endif /* !_SOLUTION_H_ */
| true |
1839e9c68c2c214c53ed3df36ce76da12923db51 | C++ | YupengHan/LeetCode | /trapping_rain_water.cpp | UTF-8 | 4,945 | 3.34375 | 3 | [] | no_license | /*
class Solution {
public:
//cal sub water
int subwater(int a, int b, vector<int>& height) {
int min_tip = height[a]>height[b]? height[b]: height[a];
int sum = 0;
for (int i = a+1; i < b; ++i) {
sum += (height[i]<min_tip) ? (min_tip-height[i]) : 0;
}
return sum;
}
int trap(vector<int>& height) {
int len = height.size();
if (len < 3) return 0;
// get tips
vector<int> tips;
int cur_max = 0;
int max_id;
unordered_map <int, int> idx_val;
for (int i = 0; i < len; i++) {
if (height[i] >= cur_max) {
// cout << i << " " << height[i] << endl;
idx_val[i] = height[i];
cur_max = height[i];
tips.push_back(i);
max_id = i;
}
}
vector<int> back_tips;
cur_max = 0;
for (int i = 1; i < len-max_id; i++) {
if (height[len-i] >= cur_max) {
// cout << len - i << " " << height[len-i] << endl;
cur_max = height[len-i];
back_tips.push_back(i);
}
}
// cout << " " << endl;
for (int i = 1; i <= back_tips.size() ; i++) {
// cout << back_tips.size()-i << " "<< len - back_tips[back_tips.size()-i] << endl;
tips.push_back(len - back_tips[back_tips.size()-i]);
}
//calculate sum
// cout << "------------------------" << endl;
int total_sum = 0;
for (int i = 0; i < tips.size()-1; ++i) {
// cout << tips[i] << " " << tips[i+1] << endl;
total_sum += subwater(tips[i], tips[i+1], height);
// cout << tips[i] << " " << tips[i+1] << endl;
}
return total_sum;
}
};
*/
class Solution {
public:
//cal sub water
int subwater(int a, int b, vector<int>& height) {
int min_tip = height[a]>height[b]? height[b]: height[a];
int sum = 0;
for (int i = a+1; i < b; ++i) {
sum += (height[i]<min_tip) ? (min_tip-height[i]) : 0;
}
return sum;
}
int trap(vector<int>& height) {
int len = height.size();
if (len < 3) return 0;
// get tips
vector<int> left_tips, right_tips;
int left_idx, right_idx, left_max, right_max;
if (height[1] >= height[0]) {
left_idx = 1;
left_max = height[1];
left_tips.insert(left_tips.begin(),left_idx);
}
else {
left_idx = 0;
left_max = height[0];
left_tips.insert(left_tips.begin(),left_idx);
}
if (height[len-2] >= height[len-1]) {
right_idx = len-2;
right_max = height[right_idx];
right_tips.insert(right_tips.end(),right_idx);
}
else {
right_idx = len-1;
right_max = height[right_idx];
right_tips.insert(right_tips.end(),right_idx);
}
// left_tips.push_back(left_idx);
// right_tips.insert(right_tips.begin(), right_idx);
while (right_idx > left_idx) {
if (left_max <= right_max) { // 从左往右走
left_idx++;
if (height[left_idx] >= left_max){
left_max = height[left_idx];
left_tips.insert(left_tips.end(), left_idx);
}
}
else {
right_idx--;
if (height[right_idx] >= right_max) {
right_max = height[right_idx];
right_tips.insert(right_tips.begin(), right_idx);
}
}
}
left_tips.insert(left_tips.end(), right_tips.begin(), right_tips.end());
int total_sum = 0;
for (int i = 0; i < left_tips.size()-1; ++i) {
// cout << left_tips[i] << " " << left_tips[i+1] << endl;
total_sum += subwater(left_tips[i], left_tips[i+1], height);
}
return total_sum;
}
};
/*
上面做法比前一个还慢!!!! (这是因为leetcode的BUG)
insert 比 push_back 快????
// 这是一个好用的答案,
class Solution {
public:
int trap(vector<int>& height) {
if (height.empty()) return 0;
int max_left = 0, max_right = 0, left = 0, right = height.size() - 1;
int rtn = 0;
while (left <= right) {
if (max_left < max_right) {
if (height[left] > max_left) max_left = height[left];
else rtn += max_left - height[left];
++left;
} else {
if (height[right] > max_right) max_right = height[right];
else rtn += max_right - height[right];
--right;
}
}
return rtn;
}
};
*/ | true |
e8e4338e9b785efd6aadf1833a67a908d941b1ac | C++ | Jitendra-Sahu/cpp | /THREAD/th1.cpp | UTF-8 | 726 | 3.125 | 3 | [] | no_license | #include<pthread.h>
#include <unistd.h>
#include<iostream>
using namespace std;
void *hello(void *tid)
{
// long t;
// t = (long) tid;
for(int i = 20; i > 10; --i)
{
cout<<i<<"\n";
}
cout<<"\n Hello world, ";
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pid_t pid;
pthread_t tid;
long t;
pid = getpid();
cout<<"\n pid = "<<pid<<endl;
/*for(int i=0; i < argc; i++)
{
cout<<"\n argv["<<i<<"]"<<":"<<argv[i]<<"\n";
}*/
int rc = pthread_create(&tid, NULL, hello, (void *)t);
cout<<"\n In main cout"<<"\n";
for(int i = 0; i < 10; ++i)
{
cout<<i<<" ";
}
//cout<<"thread value: "<<pthread_self();
//pthread_join(tid, NULL);
pthread_exit(NULL);
return 0;
}
| true |
6572bd1e3345746b9c573dc15e846116f6f73b13 | C++ | lichen-liu/TFTvm | /TFTvm/PARSER.cpp | UTF-8 | 1,230 | 2.890625 | 3 | [] | no_license | #include "PARSER.h"
#include <cassert>
#include <string>
namespace PARSER {
radix_e& operator << (radix_e& rad, const std::string &str)
{
if (str == "BIN") {
rad = radix_e::BIN;
}
else if (str == "HEX") {
rad = radix_e::HEX;
}
else if (str == "OCT") {
rad = radix_e::OCT;
}
else if (str == "DEC") {
rad = radix_e::DEC;
}
else if (str == "UNS") {
rad = radix_e::UNS;
}
else {
rad = radix_e::INVALID;
}
return rad;
}
radix_e& operator >> (radix_e& rad, std::string &str)
{
switch (rad) {
case radix_e::BIN:
str = "BIN";
break;
case radix_e::HEX:
str = "HEX";
break;
case radix_e::OCT:
str = "OCT";
break;
case radix_e::DEC:
str = "DEC";
break;
case radix_e::UNS:
str = "UNS";
break;
case radix_e::INVALID:
str = "INVALID";
break;
default:
assert(false);
break;
}
return rad;
}
} | true |
a8a3f8cb92104770cfe8671ead157cfad7578157 | C++ | LVladislav/mp2-lab1-set | /src/tbitfield.cpp | UTF-8 | 6,716 | 3.078125 | 3 | [] | no_license | // ННГУ, ВМК, Курс "Методы программирования-2", С++, ООП
//
// tbitfield.cpp - Copyright (c) Гергель В.П. 07.05.2001
// Переработано для Microsoft Visual Studio 2008 Сысоевым А.В. (19.04.2015)
//
// Битовое поле
#include "tbitfield.h"
TBitField::TBitField()
{
BitLen = 0;
MemLen = 0;
pMem = 0;
}
TBitField::TBitField(int len)
{
if (len <= 0) //Исключение.
{
throw "negative_length";
}
BitLen = len;
MemLen = (len + 31) >> 5;
pMem = new TELEM[MemLen];
if (pMem != NULL)
{
for (int i = 0; i < MemLen; i++)
{
pMem[i] = 0;
}
}
}
TBitField::TBitField(const TBitField &bf) // конструктор копирования
{
if (bf.BitLen <= 0)
{
throw "negative_length";
}
this -> BitLen = bf.BitLen;
this -> MemLen = bf.MemLen;
pMem = new TELEM[MemLen];
if (pMem != NULL){
for (int i = 0; i < MemLen; i++)
{
this->pMem[i] = bf.pMem[i];
}
}
}
TBitField::~TBitField()
{
delete [] pMem;
}
int TBitField::GetMemIndex(const int n) const // индекс Мем для бита n
{
if ((n < 0) || (n >= BitLen))
{
throw "incorrect_set_index";
}
return n >> 5; // >> деление на 2^5. Например берем 45-ый элемент , он находится в первом инте. (0 ой инт и 1 ый инт) и его индекс 14.
// при делении на цело, получаем 45/32=1, мы получили, что первый инт. Чтобы найти его индекс, берем остаток, т.е. 45/32=14.
}
TELEM TBitField::GetMemMask(const int n) const // битовая маска для бита n
{
return 1 << (n & 31); /* пусть на пример дано битовое множество из 0 и 1. 011101, и мы хотим третий элемент сделать 1, т.е. берем маску 001000
и делаем операцию логического умножения "&", результатом будет 011101 & 001000 = 001000. Теперь сдвигаем нашу маску
на 1 индекс влево, т.е. будет 1<<001000=010000 */
}
// доступ к битам битового поля
int TBitField::GetLength(void) const // получить длину (к-во битов)
{
return BitLen;
}
void TBitField::SetBit(const int n) // установить бит
{
if ((n < 0) || (n >= BitLen)) //проверяем, чтобы не выходило за границы заданного поля.
{
throw "incorrect_set_index"; //проверяем на отрицательный индекс и исключаем
}
else
{
pMem[GetMemIndex(n)] = pMem[GetMemIndex(n)] | GetMemMask(n); // наш массив с индексом n складываем с маской, т.е. 01101 | 00010 = 011(1)1 мы установили бит.
}
}
void TBitField::ClrBit(const int n) // очистить бит
{
if ((n < 0) || (n >= BitLen)) //проверяем, чтобы не выходило за границы заданного поля.
{
throw "incorrect_clr_index";
}
else
{
pMem[GetMemIndex(n)] = pMem[GetMemIndex(n)] & ~GetMemMask(n); // наш массив с индексом n умножаем на нашу (~маску)
} // и потом применяем операцию "&", т.е. было 01101 & (~00010) => 01101 & 11101= 01101
}
int TBitField::GetBit(const int n) const // получить значение бита
{
if ((n < 0) || (n >= BitLen)) //проверяем, чтобы не выходило за границы заданного поля.
{
throw "incorrect_get_index";
}
else
{
return pMem[GetMemIndex(n)] & GetMemMask(n); //получаем значение 0 или 1
}
}
// битовые операции
TBitField& TBitField::operator=(const TBitField &bf) // присваивание
{
BitLen = bf.BitLen;
if (MemLen != bf.MemLen)
{
MemLen = bf.MemLen;
}
if (pMem != NULL){
delete[] pMem;
}
pMem = new TELEM[MemLen];
for (int i = 0; i < MemLen; i++)
{
pMem[i] = bf.pMem[i];
}
return *this;
}
int TBitField::operator==(const TBitField &bf) const // сравнение
{
int tmp = 1;
if (BitLen != bf.BitLen)
{
tmp = 0;
}
else
{
for (int i = 0; i < MemLen; i++)
{
if (pMem[i] != bf.pMem[i])
{
tmp = 0;
break;
}
}
}
return tmp;
}
int TBitField::operator!=(const TBitField &bf) const // сравнение
{
int tmp = 0;
if (BitLen != bf.BitLen)
{
tmp = 1;
}
else
{
for (int i = 0; i < MemLen; i++)
{
if (pMem[i] != bf.pMem[i])
{
tmp = 1;
break;
}
}
}
return tmp;
}
TBitField TBitField::operator|(const TBitField &bf) // операция "или"(объединение)
{
int len;
if (BitLen >= bf.BitLen)
{
len = BitLen;
}
else
{
len = bf.BitLen;
}
TBitField tmp(len);
for (int i = 0; i < MemLen; i++)
{
tmp.pMem[i] = pMem[i];
}
for (int i = 0; i < bf.MemLen; i++)
{
tmp.pMem[i] |= bf.pMem[i];
}
return tmp;
}
TBitField TBitField::operator&(const TBitField &bf) // операция "и"
{
int len;
if (BitLen >= bf.BitLen)
{
len = BitLen;
}
else
{
len = bf.BitLen;
}
TBitField tmp(len);
for (int i = 0; i < MemLen; i++)
{
tmp.pMem[i] = pMem[i];
}
for (int i = 0; i < bf.MemLen; i++)
{
tmp.pMem[i] &= bf.pMem[i];
}
return tmp;
}
TBitField TBitField::operator~(void) // отрицание
{
int n;
n = BitLen;
TBitField tmp(n);
for (int i = 0; i < n; i++)
{
if (GetBit(i))
{
tmp.ClrBit(i);
}
else
{
tmp.SetBit(i);
}
}
return tmp;
}
// ввод/вывод
istream &operator>>(istream &istr, TBitField &bf) // ввод
{
// вводить мы должны числа 0 или 1, без пробелов.
// Если на вход получили число !=0 или !=1, то прекращается ввод.
char a='\0';
while (a != ' ')
{
istr >> a;
}
int i=0;
while (1) //бесконечный цикл
{
istr >> a;
if (a == '0')
{
bf.ClrBit(i++);
}
if (a == '1')
{
bf.SetBit(i++);
}
else
{
break;
}
}
return istr;
}
ostream &operator<<(ostream &ostr, const TBitField &bf) // вывод
{
int tmp = bf.GetLength();
for (int i = 0; i < tmp; i++)
{
if (bf.GetBit(i))
{
ostr << '1';
}
else
{
ostr << '0';
}
}
return ostr;
}
| true |
d91a84262ff9cba107c3a513dc979a601f77d786 | C++ | shashank-13/GeeksForGeeks-InterviewBit | /equal.cpp | UTF-8 | 3,994 | 3.015625 | 3 | [] | no_license | vector<int> Solution::equal(vector<int> &A) {
vector<int>answer;
unordered_map<int,pair<int,int>>myMap;
int n=(int)A.size();
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
int sum=A[i]+A[j];
if(myMap.find(sum)==myMap.end())
{
pair<int,int>temp;
temp.first=i;
temp.second=j;
myMap.insert(make_pair(sum,temp));
}
else
{
set<int>tempSet;
pair<int,int>temp = myMap[sum];
tempSet.insert(i);
tempSet.insert(j);
tempSet.insert(temp.first);
tempSet.insert(temp.second);
if((int)tempSet.size()==4)
{
if(answer.empty())
{
if(temp.first<i || (temp.first==i && temp.second <j))
{
answer.push_back(temp.first);
answer.push_back(temp.second);
answer.push_back(i);
answer.push_back(j);
}
else
{
answer.push_back(i);
answer.push_back(j);
answer.push_back(temp.first);
answer.push_back(temp.second);
}
}
else
{
int index1,index2,index3,index4;
if(temp.first<i || (temp.first==i && temp.second <j))
{
index1=temp.first;
index2=temp.second;
index3=i;
index4=j;
}
else
{
index1=i;
index2=j;
index3=temp.first;
index4=temp.second;
}
if(index1 < answer[0])
{
answer[0]=index1;
answer[1]=index2;
answer[2]=index3;
answer[3]=index4;
}
else if(index1==answer[0] && index2<answer[1])
{
answer[0]=index1;
answer[1]=index2;
answer[2]=index3;
answer[3]=index4;
}
else if(index1==answer[0] && index2==answer[1] && index3<answer[2])
{
answer[0]=index1;
answer[1]=index2;
answer[2]=index3;
answer[3]=index4;
}
else if(index1==answer[0] && index2==answer[1] && index3==answer[2] && index4 < answer[3])
{
answer[0]=index1;
answer[1]=index2;
answer[2]=index3;
answer[3]=index4;
}
}
}
if(i<temp.first || (i==temp.first && j<temp.second))
{
pair<int,int>temp1;
temp1.first=i;
temp1.second=j;
myMap[sum]=temp1;
}
}
}
}
return answer;
}
| true |
70d195584c2d4937a73b1337d7ca21c91e45fe77 | C++ | phramos07/taskminer | /tests/temp/functionCallTasks/lib/Graph.hpp | UTF-8 | 1,444 | 3.015625 | 3 | [] | no_license | #ifndef __GRAPH_H__
#define __GRAPH_H__
#include <iostream>
#include <list>
#include <vector>
#include <queue>
template<class NodeType, class EdgeType> struct Edge;
template<class NodeType, class EdgeType> struct Node;
template<class T> struct Coord;
template<class T>
struct Coord
{
T x;
T y;
};
template<class NodeType, class EdgeType>
struct Node
{
int index;
NodeType weight;
std::vector<Edge<NodeType, EdgeType>* > edges;
bool visited;
Node(int i, NodeType w) : index(i), weight(w) {};
~Node() {};
void addEdge(Edge<NodeType, EdgeType> &e) { edges.push_back(&e); };
};
template<class NodeType, class EdgeType>
struct Edge
{
Node<NodeType, EdgeType>* src;
Node<NodeType, EdgeType>* dst;
EdgeType weight;
Edge(Node<NodeType, EdgeType>* s, Node<NodeType, EdgeType>* d, EdgeType w) :
src(s), dst(d), weight(w) {};
~Edge() {}
};
typedef int NT;
typedef int ET;
struct Graph
{
std::vector<Node<NT, ET>* > nodes;
std::vector<Edge<NT, ET>* > edges;
int size=0;
Graph() {};
Graph(int s);
~Graph() {};
void printToDot(std::ostream &o);
Node<NT, ET>* operator[] (unsigned i);
void readFromInput(std::istream &in);
Graph* boruvka_MST();
std::list<Node<NT, ET>* > shortestPath(Node<NT, ET> &src, Node<NT, ET> &dst);
void relaxEdges(Node<NT, ET> &src, Node<NT, ET> &dst);
void dfs();
void dfs_visit(Node<NT, ET> &N);
void bfs();
void bfs_visit(Node<NT, ET> &N, std::queue<unsigned>& unexplored);
};
#endif | true |
9eb84a8842a93ebad1138eb4273714232f3c2852 | C++ | zhangz5434/code | /2016/1459 最小公倍数.cpp | UTF-8 | 460 | 2.59375 | 3 | [] | no_license | #include<iostream>
#include<algorithm>
#include<cstdio>
int a[100];
using namespace std;
int zui(int x,int y)
{
int i;
cin>>x>>y;
int m=min(x,y);
for(i=m;i>1;i--)
if(x%i==0&&y%i==0)
break;
int a=(x*y)/i;
return a;
}
int main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
int x=zui(a[0],a[1]);
for(int i=2;i<n;i++)
x=zui(x,a[i]);
cout<<x<<endl;
system("pause");
return 0;
}
| true |
fd276144fa247f55385278f3582e71e749a03a1f | C++ | GautamSachdeva/Depth_first_search_reachibilty | /reachability.cpp | UTF-8 | 953 | 3.265625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
using std::vector;
using std::pair;
void depth(int current,int finish,vector<vector<int> > &adj,vector<bool> &visited,bool &reachable){
if(current == finish){
reachable = true;
}
visited[current] = true;
for(int i = 0; i < adj[current].size() ; i++){
if(!visited[adj[current][i]]){
depth(adj[current][i],finish,adj,visited,reachable);
}
}
}
int reach(vector<vector<int> > &adj, int x, int y) {
//write your code here
vector<bool> visited(adj.size(),false);
bool reachable = false;
depth(x,y,adj,visited,reachable);
if(reachable == true){
return 1;
}
return 0;
}
int main() {
size_t n, m;
std::cin >> n >> m;
vector<vector<int> > adj(n, vector<int>());
for (size_t i = 0; i < m; i++) {
int x, y;
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
adj[y - 1].push_back(x - 1);
}
int x, y;
std::cin >> x >> y;
std::cout << reach(adj, x - 1, y - 1);
}
| true |
a6133f412ae80dca19aa6075180c5514a2dbdc63 | C++ | joydip10/Code-Practise-with-C- | /three.cpp | UTF-8 | 821 | 3 | 3 | [] | no_license | #include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a,b,c;
int test;
scanf("%d",&test);
while(test--)
{
scanf("%d %d %d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
swap(a,c);
}
else
{
swap(a,b);
}
}
else if(b>c)
{
if(b<a)
{
swap(b,a);
}
else
{
swap(b,c);
}
}
else if(a>c)
{
if(a<b)
{
swap(a,b);
}
else
{
swap(b,c);
}
}
printf("%d %d %d",a,b,c);
}
return 0;
}
| true |
92a43e0a7bfe48c887366a48c719caede4f89021 | C++ | ManasHarbola/CTCI_Solutions | /Chapter1/oneAway.cpp | UTF-8 | 949 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
bool isOneEditAway(string s1, string s2) {
int diff = s1.size() - s2.size();
if (diff < -1 || diff > 1) {
return false;
}
string *smaller, *larger;
if (diff < 0) {
smaller = &s1;
larger = &s2;
} else {
smaller = &s2;
larger = &s1;
}
bool mismatchFound = false;
for (int i = 0, j = 0; i < smaller->size() && j < larger->size(); i++, j++) {
if (smaller->at(i) != larger->at(j)) {
if (mismatchFound) {
return false;
}
mismatchFound = true;
if (diff == 1 || diff == -1) {
i--;
}
}
}
return true;
}
int main() {
cout << isOneEditAway("pale", "ple") << endl;
cout << isOneEditAway("pales", "pale") << endl;
cout << isOneEditAway("bale", "pale") << endl;
cout << isOneEditAway("pale", "bake") << endl;
}
| true |
b54b5c334265d25c70709dbecfbf186823b99d44 | C++ | kate-ly-zhao/Eckel_ThinkingInCPP | /Chp5/Questions/C5Q06.cpp | UTF-8 | 851 | 4.125 | 4 | [] | no_license | // C5Q06.cpp
/* Create a Hen class. Inside this, nest a Nest class. Inside Nest, place an
Egg class. Each class should have a display() member function. In main(),
create an instance of each class and call the display() function for each
one. */
#include <iostream>
using namespace std;
class Hen {
public:
string display();
class Nest{
public:
string display();
class Egg{
public:
string display();
};
};
};
string Hen::display() {
cout << "This is Hen" << endl;
}
string Hen::Nest::display() {
cout << "This is Nest" << endl;
}
string Hen::Nest::Egg::display() {
cout << "This is Egg" << endl;
}
int main() {
Hen hen1;
hen1.display();
Hen::Nest nest1;
nest1.display();
Hen::Nest::Egg egg1;
egg1.display();
}
| true |
6fd650e5585b8256daaad5ff80ad0c1bbd18c0b1 | C++ | patiwwb/placementPreparation | /Trees/BinaryTrees/pruneWithPathSumLessThanK.cpp | UTF-8 | 1,372 | 3.453125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *left,*right;
Node(int x){
data=x;
left=right=NULL;
}
};
Node *pruneWithPathSumLessThanK(Node *root,int k,int *sum){
if(root==NULL)return NULL;
int lsum=*sum+root->data;
int rsum=lsum;
root->left=pruneWithPathSumLessThanK(root->left,k,&lsum);
root->right=pruneWithPathSumLessThanK(root->right,k,&rsum);
*sum=max(lsum,rsum);
if(*sum<k){
free(root);
return NULL;
}
return root;
}
void print(Node *root)
{
if (root != NULL)
{
print(root->left);
printf("%d ",root->data);
print(root->right);
}
}
int main(){
int k = 45;
int sum = 0;
Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->left->left->left = new Node(8);
root->left->left->right = new Node(9);
root->left->right->left = new Node(12);
root->right->right->left = new Node(10);
root->right->right->left->right = new Node(11);
root->left->left->right->left = new Node(13);
root->left->left->right->right = new Node(14);
root->left->left->right->right->left = new Node(15);
Node *temp=pruneWithPathSumLessThanK(root,k,&sum);
print(temp);
}
| true |
7d631a94acae5eea9b2b19ac1ac054670a0c22a2 | C++ | arangodb/windows-procdump-wrapper | /corewriter/main.cpp | UTF-8 | 378 | 2.734375 | 3 | [
"Apache-2.0"
] | permissive | // corewriter.cpp : Defines the entry point for the console application.
//
#include "CoreWriter.h"
#include <iostream>
int main(int argc, char** argv)
{
CoreWriter coreWriter;
try {
coreWriter.run(argc, argv);
} catch (std::exception &e) {
std::cerr << "Error: " << e.what();
return 1;
} catch (...) {
std::cerr << "Unknown error";
return 2;
}
return 0;
} | true |
cae711add9b88d47bf86d79b09fb77c9d8438a35 | C++ | lakshyajit165/Hackerrank1 | /Test_fraction.cpp | UTF-8 | 405 | 2.640625 | 3 | [] | no_license | #include<iostream>
#include<vector>
using namespace std;
int main(){
double n,pos=0,neg=0,zero=0; double fp,fn,fz;
cin>>n;
int A[100];
for(int i=0;i<n;i++)
cin>>A[i];
for(int j=0;j<n;j++){
if(A[j]>0)
pos++;
else if(A[j]<0)
neg++;
else if(A[j]==0)
zero++;
}
fp=pos/n;
fn=neg/n;
fz=zero/n;
cout<<fp<<" "<<fn<<" "<<fz;
return 0;
}
| true |
a5e30e0e75d98bff385fba3621e4b2b5b255f5f7 | C++ | hgneer/PAT | /1053.cpp | UTF-8 | 1,785 | 2.875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
const int MAX = 10014;
using namespace std;
int number,nonleaf,neededweight;
struct{
int weight;
vector<int> child;
}node[MAX];
int num = 0;
vector<int> track[MAX];
vector<int> nowtrack;
void preorder(int root,vector<int> nowtrack,int nowweight)
{
nowweight += node[root].weight;
nowtrack.push_back(node[root].weight);
if (nowweight > neededweight){
nowtrack.clear();
return;
}
if (node[root].child.size() == 0){
if (nowweight == neededweight){
track[num++] = nowtrack;
}
nowtrack.clear();
return;
}
else{
for (int i = 0; i < node[root].child.size(); i++){
preorder(node[root].child[i], nowtrack, nowweight);
}
}
}
void layerorder(int root)
{
queue<int> Queue;
Queue.push(root);
while (!Queue.empty()){
int top = Queue.front();
printf("%d ", node[top].weight);
Queue.pop();
for (int i = 0; i < node[top].child.size(); i++){
Queue.push(node[top].child[i]);
}
}
}
bool cmp(vector<int> a, vector<int> b)
{
return a > b;
}
int main()
{
scanf("%d%d%d", &number,&nonleaf,&neededweight);
for (int i = 0; i < number; i++){
scanf("%d", &node[i].weight);
}
int id, childnum, childid;
for (int i = 0; i < nonleaf; i++){
scanf("%d%d", &id, &childnum);
for (int j = 0; j < childnum; j++){
scanf("%d", &childid);
node[id].child.push_back(childid);
}
}
preorder(0,nowtrack,0);
sort(track, track + num,cmp);
for (int i = 0; i < num; i++)
{
int j;
for (j = 0; j < track[i].size() - 1; j++){
printf("%d ", track[i][j]);
}
printf("%d", track[i][j]);
if (i != num - 1){
printf("\n");
}
}
return 0;
}
| true |
fd240cf5b29c144a6c6f863ef9252c02eeb4e5f0 | C++ | daybrush/HCI_DrawingPad | /src/PenLine.h | UTF-8 | 315 | 2.578125 | 3 | [] | no_license | #include "PenGroup.h"
class PenLine : public PenGroup{
public:
PenLine();
~PenLine();
void add(ofPoint point, ofColor c);
virtual void setup();
virtual void add(int x, int y);
virtual void draw();
virtual void clear();
private:
vector<ofPoint> position;
vector<ofColor> color;
}; | true |
5055ddd11c9effe909b48a77de3596814aedacae | C++ | AsadUllahShaikh123/push-it-hacktoberfest | /C++/Postfix_conversion.cpp | UTF-8 | 2,753 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
// Implementaion if simple stack
template <class T>
class Stack{
T *x;
int p, size;
public:
Stack(int s=10){ size = s; x = new T[size]; p = 0; }
bool isFull(){ return p == size; }
bool isEmpty(){ return p == 0; }
void push(T d){
if (isFull()) throw (size);
x[p++] = d;
}
T pop(){
if (isEmpty()) throw(0);
return x[--p];
}
T seeTop(){
if (isEmpty()) throw(0);
return x[p-1];
}
~Stack(){ delete []x; }
};
char* convertToPostFix(char *exp){
Stack <char> stack(100);
char *postFix = new char[100] , temp;
int j = 0;
for (int i=0;exp[i]!=0;i++){
//-------------------------------------------------------------------
if (exp[i] == '(') stack.push('(');
else if (exp[i] >= '0' && exp[i] <= '9' ) postFix[j++]=exp[i];
else if (exp[i] == ')')
do{
temp = stack.pop();
if (temp=='(') break;
postFix[j++] = temp;
}while (!stack.isEmpty());
else if (exp[i] == '+' || exp[i] == '-' || exp[i] == '*' || exp[i] == '/'){
while (!stack.isEmpty()){
temp = stack.seeTop();
if (temp == '(') break;
if (exp[i] == '+' || exp[i] == '-' )
postFix[j++] = stack.pop();
if ( ( exp[i] == '*' || exp[i] == '/' ) && (temp == '*' || temp == '/') )
postFix[j++] = stack.pop();
else break;
}
stack.push(exp[i]);
}
//------------------------------------------------------------------------------
}
while (!stack.isEmpty())
postFix[j++] = stack.pop();
postFix[j] = 0;
return postFix;
}
int evaluate(int n1, int n2, char op){
switch(op){
case '+': return n1 + n2;
case '-': return n1 - n2;
case '*': return n1 * n2;
default: return n1 / n2;
}
}
int evaluatePostFix(char *exp){
Stack <int> stack(100);
int n1, n2;
for (int i=0;exp[i]!=0;i++)
if (exp[i] >= '0' && exp[i] <= '9' ) stack.push(exp[i]-'0'); //Convert character digit into number digit
else{
n2 = stack.pop();
n1 = stack.pop();
stack.push(evaluate(n1, n2, exp[i]));
}
return stack.pop();
}
int main(){
char exp1[100]="2+3*5";
char exp2[100]="(2+3)*5";
char exp3[100]="(2+3)*5+8*(6-4)*7";
cout << exp1 << " Post fix expression:" << convertToPostFix(exp1) << '\n';
cout << exp2 << " Post fix expression:" << convertToPostFix(exp2) << '\n';
cout << exp3 << " Post fix expression:" << convertToPostFix(exp3) << '\n';
cout << exp1 << " Post fix expression:" << evaluatePostFix(convertToPostFix(exp1) )<< '\n';
cout << exp2 << " Post fix expression:" << evaluatePostFix(convertToPostFix(exp2) )<< '\n';
cout << exp3 << " Post fix expression:" << evaluatePostFix(convertToPostFix(exp3) )<< '\n';
return 0;
}
| true |
4ec1fcf08a14b59aff5ed51e7b4684c6e438b99e | C++ | Mindful/sos | /data_structures/lab_6/min_stack.cpp | UTF-8 | 1,223 | 3.671875 | 4 | [] | no_license | #include <stack>
#include <iostream>
using namespace std;
class MinStack{
private:
stack<int> s;
stack<int> mins;
int min;
int curSize;
public:
MinStack() : curSize(0){}
bool isEmpty(){
return curSize==0;
}
void push(int i){
if(isEmpty() || i <= min){
min = i;
mins.push(i);
}
s.push(i);
++curSize;
}
int top(){
if(isEmpty()) return 0; //Really this is an error
return s.top();
}
void pop(){
if(isEmpty()) return;
int r = top();
if (r==min){
mins.pop();
min = mins.top();
}
s.pop();
}
int getMin(){
if(isEmpty()) return 0; //Really this is an error
return min;
}
};
void printPush(MinStack &ms, int i){
cout << "Push: " << i << endl;
ms.push(i);
}
void printMin(MinStack &ms){
cout << "Current Min: " << ms.getMin() << endl;
}
void printPop(MinStack &ms){
cout << "Pop: " << ms.top() << endl;
ms.pop();
}
int main(){
MinStack ms;
printPush(ms, 5);
printMin(ms);
printPush(ms, 4);
printMin(ms);
printPush(ms, 7);
printPush(ms, 8);
printPush(ms, 3);
printPush(ms, 2);
printPush(ms, 2);
printMin(ms);
printPop(ms);
printMin(ms);
printPop(ms);
printPop(ms);
printPop(ms);
printMin(ms);
return 0;
} | true |
5fbe93cfa9191cbd57baef40071948c3b95f6ba9 | C++ | libaoke/Cpp-Practices | /modern/for_range/for_range.cpp | UTF-8 | 387 | 3.078125 | 3 | [] | no_license | #include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4};
if (auto itr = std::find(vec.begin(), vec.end(), 3); itr != vec.end())
*itr = 4;
for (auto e : vec) {
std::cout << e << std::endl;
}
for (auto &e : vec) {
e += 1;
}
std::cout << std::endl;
for (auto e : vec) {
std::cout << e << std::endl;
}
}
| true |
5a27fe95de39d3a00fae25f11d29af30cd31f61c | C++ | samuelharroch/Pandemic-CPP | /sources/Player.cpp | UTF-8 | 3,382 | 3.359375 | 3 | [] | no_license | #include "Player.hpp"
#include "City.hpp"
#include "Color.hpp"
#include <string>
#include <exception>
using namespace std;
using namespace pandemic;
const unsigned int cards_to_cure = 5;
Player::Player(Board& board, City city):board(board), current_city(city){
}
Player& Player::take_card(City city){
this->cards.insert(city);
return *this;
}
Player& Player::drive(City city){
if(board.connections.at(this->current_city).count(city) == 0 || current_city == city){
throw invalid_argument {"the destination is not accessable"};
}
this->current_city = city;
return *this;
}
Player& Player::fly_direct(City city){
if(cards.count(city) == 0 || current_city == city){
throw invalid_argument {"You don't have the destination card \\ you are already in the city"};
}
cards.erase(city);
this->current_city = city;
return *this;
}
Player& Player::fly_charter(City city){
if(cards.count(current_city) == 0 || current_city == city){
throw invalid_argument {"You don't have the current city card \\ you are already in the city"};
}
cards.erase(current_city);
this->current_city = city;
return *this;
}
Player& Player::fly_shuttle(City city){
if( board.getSations().count(current_city) == 0 || board.getSations().count(city) == 0 || current_city == city){
throw invalid_argument {"There is no research station in the destination city \\ you are already in the city"};
}
this->current_city = city;
return *this;
}
Player& Player::build(){
if (board.getSations().count(current_city) != 0 ){
return *this;
}
if(cards.count(current_city) == 0 ){
throw invalid_argument {"You don't have the current city card "};
}
cards.erase(current_city);
board.build_station(current_city);
return *this;
}
Player& Player::discover_cure(Color color){
if (board.getSations().count(current_city) == 0 ){
throw invalid_argument {"There is no research station in the destination city "};
}
if(board.getDiscovers_cures().count(color) != 0){
return *this;
}
unsigned int count = 0;
for( City city : this->cards){
if(board.colors.at(city) == color){
count++;
}
}
if (count< cards_to_cure){
throw invalid_argument {"You don't have enough cards"};
}
count = cards_to_cure; // reset counter to num of card to erase
for(auto it=cards.begin(); it!= cards.end(); ){
if (count==0){ break;}
if(board.colors.at(*it) == color){
it = cards.erase(it);
count--;
}
else{
it++;
}
}
board.add_cure(color); // update the board about the discovered cure
return *this;
}
Player& Player::treat(City city){
if (current_city != city){
throw invalid_argument {"You can't treat this city "};
}
if (board[city] == 0){
throw invalid_argument {"There is not infection in this city"};
}
if (board.getDiscovers_cures().count(board.colors.at(city)) == 0){
board[city]--;
}
else{
board[city] = 0;
}
return *this;
}
void Player::remove_cards(){
this->cards.clear();
}
| true |
19bcb000b7fba16427538c969dd15db5cc96cb20 | C++ | fwolle30/VectorTest | /src/Math/Vector.cpp | UTF-8 | 2,110 | 3.5 | 4 | [] | no_license | #include "./Math/Vector.hpp"
#include <algorithm>
#include <cmath>
#include "./Math/Point.hpp"
Vector_2d::Vector_2d() : x(0), y(0) {}
Vector_2d::Vector_2d(float x, float y) : x(x), y(y)
{
if (isnanf(x))
{
this->x = 0;
}
if (isnanf(y))
{
this->y = 0;
}
}
Vector_2d::Vector_2d(const Point_2d &b) {
x = b.x;
y = b.y;
}
void Vector_2d::operator=(const Vector_2d &b)
{
x = b.x;
y = b.y;
}
Vector_2d Vector_2d::operator+(const Vector_2d &b)
{
return Vector_2d(x + b.x, y + b.y);
}
Vector_2d Vector_2d::operator-(const Vector_2d &b)
{
return Vector_2d(x - b.x, y - b.y);
}
Vector_2d Vector_2d::operator*(const Vector_2d &b)
{
return Vector_2d(x * b.x, y * b.y);
}
Vector_2d Vector_2d::operator/(const Vector_2d &b)
{
return Vector_2d(x / b.x, y / b.y);
}
Vector_2d Vector_2d::operator+=(const Vector_2d &b)
{
x += b.x;
y += b.y;
return Vector_2d(x, y);
}
Vector_2d Vector_2d::operator*(float f)
{
return Vector_2d(f * x, f * y);
}
Vector_2d Vector_2d::operator/(float f)
{
return Vector_2d(x / f, y / f);
}
Vector_2d::operator Point_2d()
{
return Point_2d(x, y);
}
Vector_2d Vector_2d::abs()
{
return Vector_2d(std::abs(x), std::abs(y));
}
Vector_2d Vector_2d::min(const Vector_2d &b)
{
return Vector_2d(std::min(x, b.x), std::min(y, b.y));
}
Vector_2d Vector_2d::max(const Vector_2d &b)
{
return Vector_2d(std::max(x, b.x), std::max(y, b.y));
}
Vector_2d Vector_2d::min(float b)
{
return Vector_2d(std::min(x, b), std::min(y, b));
}
Vector_2d Vector_2d::max(float b)
{
return Vector_2d(std::max(x, b), std::max(y, b));
}
float Vector_2d::length()
{
if (x == 0 && y == 0)
{
return 0;
}
return sqrtf((x * x) + (y * y));
}
Vector_2d Vector_2d::normalize()
{
float l = length();
if (l == 0)
{
return Vector_2d(0, 0);
}
return Vector_2d(x / l, y / l);
}
Vector_2d Vector_2d::transform(float matrix[4])
{
float a = matrix[0], b = matrix[1], c = matrix[2], d = matrix[3];
return Vector_2d(x * a + y * b, x * c + y * d);
} | true |
9ade46d1def1bab104ef0f05dd91f381f482c9f7 | C++ | evrudenko/path_searching_directed_graph | /main_header.hpp | UTF-8 | 632 | 2.765625 | 3 | [] | no_license | #ifndef _MAIN_G_HEADER_
#define _MAIN_G_HEADER_
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <regex>
using namespace std;
/*
* ~~~~ Описание структуры:
* Вспомогательная структура данных, представляющая направленное ребро графа (дугу),
* в направлении от вершины v к вершине w, стоимостью c.
*/
struct Edge {
int v, w, c;
Edge(int v = -1, int w = -1, unsigned c = 0) : v(v), w(w), c(c) { }
};
#endif // _MAIN_G_HEADER_ | true |
9a4538ef666f5c5cf37eef309e93ac678c014a2a | C++ | muhammadosmanali/Data-Structure | /linklist & stack Queue.cpp | UTF-8 | 2,071 | 3.859375 | 4 | [] | no_license | #include <iostream>
using namespace std;
class node {
public:
int data;
node * next;
};
class LL {
protected:
node * head;
public:
LL() {
head = NULL;
}
void insert(int v) {
node * nptr = new node();
nptr->data = v;
nptr->next = NULL; // Because next contain the garbage value so we make it NULL.
if(head == NULL) {
head = nptr;
}
else {
node * tptr = head;
while(tptr->next != NULL) {
tptr = tptr->next;
}
tptr->next = nptr;
}
}
void print() {
node * tptr = head;
while(tptr->next != NULL) {
cout << tptr->data << " ";
tptr = tptr->next;
}
cout << tptr->data;
}
void print1() {
node * tptr = head;
while(tptr != NULL) {
cout << tptr->data << " ";
tptr = tptr->next;
}
}
void deletes(int v) {
node * ftpr = head;
node * tptr = head;
while(tptr->data != v) {
ftpr = tptr;
tptr = tptr->next;
}
ftpr->next = tptr->next;
}
};
class Queue : public LL {
public:
void enQ(int x) {
this->insert(x);
}
int deQ() {
if(head != NULL) {
int x;
node * nptr = head;
head = head->next;
x = nptr->data;
delete nptr;
return x;
}
};
class stack : public LL {
public:
int pop() {
int x;
node * tptr = head;
if(head == NULL) {
return -1;
}
else if(head->next == NULL) {
int x;
x = head->data;
head = NULL;
return x;
}
else {
while(tptr->next->next == NULL) {
tptr = tptr->next;
}
int x;
x = tptr->next->data;
tptr->next = NULL;
return x;
}
}
void Push(int v) {
node * nptr = new node();
nptr->data = v;
nptr->next = NULL; // Because next contain the garbage value so we make it NULL.
if(head == NULL) {
head = nptr;
}
else {
node * tptr = head;
while(tptr->next != NULL) {
tptr = tptr->next;
}
tptr->next = nptr;
}
}
};
int main() {
stack obj;
obj.Push(1);
obj.Push(2);
obj.Push(3);
obj.Push(4);
obj.print1();
obj.pop();
obj.print1();
}
| true |
7d95f921bccb47791f0a65c09d2ccfb8c44cdb99 | C++ | JakubSzym/Library-for-home-usage | /inc/user.hh | UTF-8 | 1,575 | 3.328125 | 3 | [] | no_license | #ifndef USER_HH
#define USER_HH
/*
*Plik zawiera deklaracje klasy User, prototypy metod i przeciazenia operatorow wczytywania/zapisywania dla strumieni plikowych
*/
#include<string>
#include<iostream>
#include<fstream>
#include<ncurses.h>
class User{
private:
std::string name; //imie i nazwisko
std::string pesel; //PESEL
std::string address; //adres zamieszkania
std::string email; //adres mailowy
public:
//Ponizsze metody zezwalaja na dostep do skladnikow prywatnych
std::string& getName(){ return name;}
std::string& getPesel(){ return pesel;}
std::string& getAddress(){ return address;}
std::string& getEmail(){ return email;}
//ustawianie nowych wartosci dla poszczegolnych skladnikow
void setName(std::string nName){ name = nName;}
void setPesel(std::string nPesel){ pesel = nPesel;}
void setAddress(std::string nAddress){ address = nAddress;}
void setEmail(std::string nEmail){ email = nEmail;}
void read(); //wczytywanie z klawiatury
void write(); //wypisywanie na ekran (ncurses)
};
/*
*Przeciazenie operatora przesuniecia w lewo (zapisywanie)
*Argumenty:
* file - strumien plikowy
* user - obiekt klasy User (dane o uzytkowniku)
*Zwraca:
* strumien plikowy przez referencje
*/
std::fstream& operator<<(std::fstream& file, User& user);
/*
*Przeciazenie operatora przesuniecia w prawo (czytanie)
*Argumenty:
* file - strumien plikowy
* user - obiekt klasy User (dane o uzytkowniku)
*Zwraca:
* strumien plikowy przez referencje
*/
std::fstream& operator>>(std::fstream& file, User& user);
#endif
| true |
dead11d9288e6d77eae187bc32aacae408bc252f | C++ | Rastorguev0/graph_algorithms_course | /week2/toposort.cpp | UTF-8 | 1,240 | 3.375 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using std::vector;
using std::pair;
class DirectedGraph {
public:
DirectedGraph(vector<vector<int>> adj_list) {
adj = move(adj_list);
used.assign(adj.size(), false); //V
}
void DFS(int v, vector<int>& order) {
used[v] = true;
for (int neighbour : adj[v]) {
if (!used[neighbour]) DFS(neighbour, order);
}
order.push_back(v);
}
vector<int> Toposort() {
vector<int> order;
order.reserve(adj.size()); //V
for (int v = 0; v < adj.size(); v++) {
if (!used[v]) DFS(v, order);
} //2V + E
return order;
}
private:
int FindNotUsed() {
auto it = std::find(used.begin(), used.end(), false);
return it == used.end() ? -1 : std::distance(used.begin(), it);
}
private:
vector<vector<int>> adj;
vector<bool> used;
};
int main() {
size_t n, m;
std::cin >> n >> m;
vector<vector<int>> adj(n, vector<int>());
for (size_t i = 0; i < m; i++) {
int x, y;
std::cin >> x >> y;
adj[x - 1].push_back(y - 1);
} //V + E
DirectedGraph G(move(adj)); //V
vector<int> order = G.Toposort(); //4V + E
for (int i = order.size() - 1; i >= 0; --i) { //V
std::cout << order[i] + 1 << " ";
}
}
| true |
634d730fe83ba12dcd1a3be123b5d0ff8f5f53ba | C++ | vignesh-raghavan/SAT-solver | /parse_c.h | UTF-8 | 2,925 | 2.515625 | 3 | [] | no_license | #ifndef PARSE_C_H_
#define PARSE_C_H_
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
#include<stdlib.h>
#include"types.h"
#include<algorithm>
using namespace std;
using namespace SAT;
int getint(ifstream *inf, char *c)
{
int neg,val,factor;
int i = 0;
char buf[32];
val = 0;
factor = 1;
neg = 1;
if(*c == '-')
{
neg = -1;
inf->get(*c);
}
do
{
buf[i++] = *c;
inf->get(*c);
}while(*c != ' ' && *c!= '\n');
for(i--; i >=0 ; i--)
{
val += factor*(int)(buf[i]-'0');
factor = factor*10;
}
return neg*val;
}
int addclause(int *larray)
{
p_clause * pc;
clause * cl;
lit * Lt;
int i,j,l;
i = 0;
pc = new p_clause();
//make clause
cl = new clause;
pc->cl = cl;
while(larray[i] != 0)
{
l = abs(larray[i]);
//create only required lit,
if(l > literals.size()/2)
{
for(j = literals.size()/2 + 1; j <= l; j++)
{
Lt = new lit(2*j-1);
literals.push_back(Lt);
Lt = new lit(2*j);
literals.push_back(Lt);
}
}
//make clause
if(larray[i] < 0)
{
cl->list.push_back(2*l-1);
literals.at(2*l-1)->pc.push_back(pc);
}
if(larray[i] > 0)
{
cl->list.push_back(2*l);
literals.at(2*l)->pc.push_back(pc);
}
i++;
}
sort(cl->list.begin(), cl->list.end());
pc->UAcount = cl->list.size();
clauses.push_back(pc);
return 0;
}
int parsefile(string filename)
{
if(myDebug == HIGH) cout << __FUNCTION__ << endl;
char c;
int i=0;
int rlits[1000];
int n_clauses;
int n_lits;
ifstream infile(filename.c_str());
if(infile.is_open())
{
do
{
infile.get(c);
//cout << ".." << c << ".." << endl;
if(isspace(c))continue;
if( c == 'c')
{
//skip whole line
while(c != '\n')infile.get(c);
}
else if( c == 'p')
{
//skip whole line
while(c != '\n')infile.get(c);
//skip "p cnf"
/*while(c != 'f')infile.get(c);
infile.get(c);
cout << ".." << c << ".." << endl;
while(isspace(c))infile.get(c);
cout << ".." << c << ".." << endl;
//n_clauses = getint(&infile,&c);
while(isspace(c))infile.get(c);
cout << ".." << c << ".." << endl;
//n_lits = getint(&infile,&c);
//Make sure to finish parsing the line
if( c == '\n')continue;
while(isspace(c))infile.get(c);
if( c == '\n')continue;
else
{
cout << "Unexpected characters found. file format is wrong" << endl;
return -1;
}*/
}
else if(isdigit(c)|| c=='-')
{
if(c == '0')
{
rlits[i] = 0;
addclause(rlits);
i = 0;
}
else
{
rlits[i++] = getint(&infile,&c);
}
}
}
while( !infile.eof());
}
else
{
cout << "File cannot be opened" << endl;
return -1;
}
if(myDebug != OFF) cout << "Clauses : " << clauses.size() << " Literals : " << literals.size() << endl;
return 0;
}
#endif
| true |