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
9ead7dbf811661ba2dee1828172d33805ab6aa77
C++
AlinCioabla/SQLSystem
/SQLSystem/SQLSystem/Intermediar.h
UTF-8
366
2.640625
3
[]
no_license
#pragma once #include "ICommand.h" class Intermediar : public ICommand { public: Intermediar(IToken* aCommand) :mCommand(aCommand) {}; void SetArguments(IToken* aTableName) override; CommandType GetCommandType() const override; bool ExpectedNext(ICommand* aNextCommand)const override; ~Intermediar(); vector<IToken*> mArguments; IToken* mCommand; };
true
c48b3cf5a61bae77fda4b17e24e80a432adde3f0
C++
swaphack/CodeLib
/Foundation/Render/Common/Input/MouseManager.h
GB18030
2,349
2.53125
3
[]
no_license
#pragma once #include "system.h" #include "MouseDelegate.h" namespace render { class Node; class MouseManager { public: MouseManager(); ~MouseManager(); public: // ֻɷ void addMouseScrollDelegate(sys::Object* target, Node* node, MOUSE_SCROLL_DELEGATE_HANDLER handler); // Ƴֻɷ void removeMouseScrollDelegate(sys::Object* target, Node* node); // Ƴֻɷ void removeAllMouseScrollDelegates(); public: // ֻɷ void addMouseScrollFunc(sys::Object* target, Node* node, MouseScrollFunc func); // Ƴֻɷ void removeMouseScrollFunc(sys::Object* target, Node* node); // Ƴֻɷ void removeAllMouseScrollFuncs(); public: // ɷյİť¼ void onDispatchScrolleEvent(sys::ScrollEvent evt, float param); public: // Ӱɷ void addMouseButtonDelegate(sys::Object* target, Node* node, MOUSE_BUTTON_DELEGATE_HANDLER handler); // Ƴɷ void removeMouseButtonDelegate(sys::Object* target, Node* node); // Ƴаɷ void removeAllMouseButtonDelegates(); public: // Ӱɷ void addMouseButtonFunc(sys::Object* target, Node* node, MouseButtonFunc func); // Ƴɷ void removeMouseButtonFunc(sys::Object* target, Node* node); // Ƴаɷ void removeAllMouseButtonFuncs(); public: // Ƴ¼ void removeTargetAllEvents(sys::Object* target); public: // ɷյİť¼ void onDispatchButtonEvent(sys::MouseKey key, sys::ButtonStatus status, const math::Vector2& touchPoint); private: // ¼ίм std::map<sys::Object*, std::map<Node*, MOUSE_SCROLL_DELEGATE_HANDLER>> _mouseScrollDelegates; // ¼ίм std::map< sys::Object*, std::map<Node*, MouseScrollFunc>> _mouseScrollFuncs; private: // ¼ίм std::map<sys::Object*, std::map<Node*, MOUSE_BUTTON_DELEGATE_HANDLER>> _mouseButtonDelegates; // ¼ίм std::map< sys::Object*, std::map<Node*, MouseButtonFunc>> _mouseButtonFuncs; }; #define G_MOUSEMANAGER sys::Instance<MouseManager>::getInstance() }
true
1015cce0eb333788d6ec2ba5b09d03fd438bdeca
C++
qiqi789/NurseScheduler
/src/ReadWrite.h
UTF-8
4,490
2.640625
3
[ "MIT" ]
permissive
#ifndef _ReadWrite_h #define _ReadWrite_h #include <algorithm> #include <stdlib.h> #include <iostream> #include <fstream> #include <streambuf> #include <string> #include <vector> #include <time.h> #include <math.h> #include <limits.h> #include "Scenario.h" #include "StochasticSolver.h" using std::string; using std::cout; using std::endl; //BADVALDBL used as a flag value (not initialised parameter) when there's no ambiguity. #define BADVALDBL -666.0 #ifdef WIN32 #ifndef NAN const unsigned long nan[2]={0xffffffff, 0x7fffffff}; #define NAN (*(const double *) nan) #endif #endif //-------------------------------------------------------------------------- // // C l a s s R e a d W r i t e // // Contains the (static) functions to read the input and write the output // //-------------------------------------------------------------------------- class ReadWrite{ // All functions in this class shall be public public: //-------------------------------------------------------------------------- // Methods that read all the input files and store the content in the // input scenario instance // // Read the scenario file and store the content in a Scenario instance // static Scenario* readScenario(std::string strScenarioFile); //Read several week files and strore the content in one demand and one preference // static Demand* readWeeks(vector<std::string> strWeekFiles, Scenario* pScenario); // Read the Week file and store the content in a Scenario instance // static void readWeek(string strWeekFile, Scenario* pScenario, Demand** pDemand, Preferences** pPref); // Read the history file // static void readHistory(string strHistoryFile, Scenario* pScenario); // Read the input custom file // Store the result in a vector of historical demands and return the number of treated weeks // static int readCustom(string strCustomInputFile, Scenario* pScenario, vector<Demand*>& demandHistory); // Read the options of the stochastic and ot the other solvers // static string readStochasticSolverOptions(string strOptionFile, StochasticSolverOptions& options); static string readSolverOptions(string strOptionFile, SolverParam& options); // Read the solution from multiple week solution files // static vector<Roster> readSolutionMultipleWeeks(vector<std::string> strWeekSolFiles, Scenario* pScenario); // Print the main characteristics of all the demands of an input directory // This is done to find some invariant properties among demands static void compareDemands(string inputDir, string logFile); //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Methods that write the ouputs of the solver // Write the solution file for the current week // // void writeSolution(std::string strCustomOutputFile, Solution* pSolution); // // Write the output custom file from values in the scenario and the solution // instances // static void writeCustom(string stdCustomOutputFile, string strWeekFile, string strCustomInputFile=""); //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // Useful parsing functions // Read a file stream until the separating character (or one of them) is met // Store the characters read until the separating character in pStrRead // static bool readUntilChar(std::fstream *pFile, char separater, std::string *pStrRead); static bool readUntilOneOfTwoChar(std::fstream *pFile, char separater1, char separater2, std::string *pStrRead); // Checks if the string (sentence) ends with the given substring (word) // static bool strEndsWith(string sentence, string word); // writes a string in a stream with a constant number of character // template<typename T> static void writeConstantWidth(std::ostream &out, int width, const T output); //-------------------------------------------------------------------------- }; // writes a string in a stream with a constant number of character // template<typename T> void ReadWrite::writeConstantWidth(std::ostream &out, int width, const T output) { char buffer[100]; int cx; cx = snprintf(buffer, 100, "%s", output); if (cx > width){ std::cout << "Warning: the string is larger than the width!" << std::endl; width = cx; } std::fill_n(buffer+cx, width-cx, ' '); out.write(buffer, width); } #endif
true
bb9a84dad248510d049e42815b962d3037c18292
C++
MacroBull/Reconstructable
/clone_ptr.hpp
UTF-8
1,697
2.875
3
[]
no_license
/* Copyright (c) 2019 Macrobull */ #pragma once #include <utility> //// CloneBase: interface for clone-able container template <typename T> class CloneBase { public: CloneBase() = default; virtual ~CloneBase() = default; CloneBase(const CloneBase&) = default; CloneBase& operator=(const CloneBase&) = default; virtual T* instance() const = 0; virtual CloneBase* clone() const = 0; }; template <typename T, typename... CArgs> CloneBase<T>* create_clone_impl(T* instance, CArgs... args); //// ClonePtr: drop Params... from CloneImpl template <typename T> class ClonePtr { public: template <typename... CArgs> explicit ClonePtr(CArgs... args) : m_impl(create_clone_impl( new T(std::forward<CArgs>(args)...), std::forward<CArgs>(args)...)) {} template <typename U> explicit ClonePtr(std::initializer_list<U>&& args) : m_impl(create_clone_impl(new T(std::forward<std::initializer_list<U>>(args)), std::forward<std::initializer_list<U>>(args))) {} virtual ~ClonePtr(); ClonePtr(const ClonePtr& rvalue) : m_impl(rvalue.get_impl()->clone()) {} ClonePtr(ClonePtr&& xvalue) noexcept : m_impl(nullptr) { std::swap(m_impl, xvalue.m_impl); } ClonePtr& operator=(const ClonePtr& rvalue); ClonePtr& operator=(ClonePtr&& xvalue) noexcept; inline const T& operator*() const { return *get_impl()->instance(); } inline T& operator*() { return *get_impl()->instance(); } inline const T* operator->() const { return get_impl()->instance(); } inline T* operator->() { return get_impl()->instance(); } ClonePtr& reconstruct(); protected: CloneBase<T>* get_impl() const; private: CloneBase<T>* m_impl{}; };
true
d1780c74a5c550bc8542ed5ff0269b5602d1ee6a
C++
bhavikabadjate901/arrayCPPInterview
/Swap_major_minor_diagonals_of_matrix.cpp
UTF-8
805
3.40625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define N 2 // Swap major and minor diagonals of a square matrix // Given a square matrix, swap the element of major and minor diagonals. // Example : // Input : 0 1 2 // 3 4 5 // 6 7 8 // Output : 2 1 0 // 3 4 5 // 8 7 6 int main() { #ifndef ONLINE_JUDGE // for getting input from input.txt freopen("input1.txt", "r", stdin); // for writing output to output.txt freopen("output1.txt", "w", stdout); #endif int arr[N][N]; for(int i =0; i < N; i++) { for(int j =0; j < N; j++) { cin >> arr[i][j]; } } for(int i =0; i < N; i++) { swap(arr[i][i], arr[i][N-1-i]); } for(int i =0; i < N; i++) { for(int j =0; j < N; j++) { cout << arr[i][j] << " "; } cout << endl; } }
true
5e065113ac78abb05e8c4f9be42786883d136b7e
C++
ronleal0/cplus_codes
/lab6.cpp
UTF-8
1,876
4.03125
4
[]
no_license
#include <iostream> #include <string> using namespace std; int main(){ cout << endl << endl; // 1. DECLARING AND PRINTING VARIABLES /*int number = 10; char letter = 'a'; bool result = true; string str = "hello"; cout << "Number = " << number << endl; cout << "Letter = " << letter << endl; cout << "Result = " << result << endl; cout << "str = " << str << endl;*/ // 2. Getting the average of three numbers. // Create a program that outputs the average of three numbers. // Let the values of the three numbers be, 10, 20 and 45. // The expected screen output is, // number 1 = 10 // number 2 = 20 // number 3 = 45 // Average is = 25 // int num1 = 10; // int num2 = 20; // int num3 = 45; // int average = (num1 + num2 + num3)/3; // cout << average; //3. OUTPUT GREATEST VALUE // int first = 10; // int second = 23; // int third = 54; // int findFirstHigh, final; // findFirstHigh = (first > second) ? first : second; // final = (findFirstHigh > third) ? findFirstHigh : third; // cout << final; /* // CONVERSION double peso; double dollar = 1.000; double euro = 0.734719;ß double yuan = 6.346934; double koruna = 18.77263; double krone = 5.449007; double sheqel = 3.726334; double dinar = 0.274588; cout << "Enter Peso: " << endl; cin >> peso; cout << endl << endl; cout << "Dollor: " << dollar * peso << endl; cout << "Euro: " << euro * peso << endl; cout << "Yuan: " << yuan * peso << endl; cout << "Koruna: " << koruna * peso << endl; cout << "Krone: " << krone * peso << endl; cout << "Sheqel: " << sheqel * peso << endl; cout << "Dinar: " << dinar * peso << endl; */ /* //TEMPERATURE First: 26° × 9/5 = 234/5 = 46.8 Then: 46.8 + 32 = 78.8° F float input; cout << "Enter celsius: " << endl; cin >> input; float f = (input * 9)/5 + 32; cout << input << " celsius is " << f << "fahrenheit"; */ cout << endl << endl; return 0; }
true
c6389e85b0957a396b47a02a8d40ca65e38088fb
C++
alexandraback/datacollection
/solutions_5766201229705216_0/C++/zentropy/FullBinaryTree.cpp
UTF-8
2,048
2.734375
3
[]
no_license
#include <stdio.h> #include <vector> #include <string> #include <algorithm> #include <assert.h> using std::vector; using std::string; size_t slove_small(const vector< vector<bool> >& g) { size_t size = g.size(),ans = size + 1; for(unsigned int imask = 0;imask < (1<<size);++imask) { size_t countbit = 0; for(unsigned int ibit = 0;ibit < size;++ibit) { if(imask&(1<<ibit)) ++ countbit; } if(countbit >= ans) continue; vector<unsigned int> nodes; vector< vector<bool> > gtmp = g; for(unsigned int ibit = 0;ibit < size;++ibit) { if(0 == (imask&(1<<ibit))) continue; nodes.push_back(ibit); for(size_t i = 0;i < size;++i) { gtmp[ibit][i] = false;gtmp[i][ibit] = false; } } size_t count2 = 0,count0 = 0,count3 = 0,count1 = 0,count = 0; for(size_t i = 0;i < size;++i) { size_t degree = 0; for(size_t k = 0;k < size;++k) degree += gtmp[i][k]; if(0 == degree) { if(!std::binary_search(nodes.begin(),nodes.end(),i)) ++count0; } else if(1 == degree) ++ count1; else if(2 == degree) ++count2; else if(3 == degree) ++count3; else ++count; } if(count != 0) continue; // if(count2 != 1 && count2 != 0) continue; if(0 == count2) { if(1 != count0) continue; if(0 != count1) continue; if(0 != count3) continue; } else { if(0 != count0) continue; if(2 + count3 != count1) continue; } ans = countbit; } assert(ans < size); return ans; } size_t slove_large(const vector< vector<bool> >& g) { size_t size = g.size(),ans = size + 1; return ans; } int main() { unsigned int nCases = 0;scanf("%d",&nCases); for(unsigned int iCases = 1;iCases <= nCases;++iCases) { unsigned int n = 0,x = 0,y = 0;scanf("%d",&n); vector< vector<bool> > g(n,vector<bool>(n,false)); for(unsigned int i = 1;i < n;++i) { scanf("%d%d",&x,&y);--x;--y; g[x][y] = true;g[y][x] = true; } size_t ans = slove_small(g); printf("Case #%u: %u\n",iCases,ans); } return 0; }
true
f6ce30c15d867efc7b200eed87ec4335a934ea7c
C++
labelette91/Arduino
/OregonPi/Flag.h
UTF-8
975
3.09375
3
[]
no_license
/* =================================================== Flag.h * ==================================================== * Managing internal 16 bits flag with enum * * Created on: 24 june 2015 * Author: * * =================================================== */ #ifndef __FLAG_H__ #define __FLAG_H__ template<class eType> class Flags { public: Flags(eType init = 0); void setFlags(eType flags); void unsetFlags(eType flags); bool isFlagsSet(eType flags) const; void reset(); private: eType _flags; }; template<class eType> Flags<eType>::Flags(eType init) : _flags(init) { } template<class eType> void Flags<eType>::setFlags(eType flags) { _flags |= flags; } template<class eType> void Flags<eType>::unsetFlags(eType flags) { _flags &= ~flags; } template<class eType> bool Flags<eType>::isFlagsSet(eType flags) const { return ((_flags & flags) == flags); } template<class eType> void Flags<eType>::reset() { _flags = 0; } #endif //__FLAG_H__
true
cbf24d0886b37b5ba68c21caf8aa9366ede84247
C++
tranphuquy19/cpp-projects
/lcm.cpp
UTF-8
375
2.84375
3
[]
no_license
#include <iostream> using namespace std; int gdc(int a, int b) { if (b == 0) return a; return gdc(b, a % b); } int lcm(int a, int b) { return a * b / gdc(a, b); } // gcc lcm.cpp -lstdc++ -o lcm.out && ./lcm.out 42 72 int main(int argc, char const *argv[]) { int a = stoi(argv[1]); int b = stoi(argv[2]); cout << lcm(a, b) << endl; return 0; }
true
6ac8b61931c703a5395cbcc0fe8e13272adee775
C++
EcutDavid/oj-practices
/codeforces/1156/A.cpp
UTF-8
1,608
2.71875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef double f64; typedef long long i64; typedef int i32; typedef pair<i32, i32> pi32; typedef unsigned long long u64; typedef unsigned int u32; typedef vector<i32> vi32; typedef deque<i32> di32; #define all(c) (c).begin(), (c).end() #define REP(i, a, b) for (auto i = a; i < b; i++) #define REPA(i, a, b, acc) for (auto i = a; i < b; i += acc) #define PB push_back #define PF push_front #define PRINT(x) cout << #x ": " << (x) << endl; #define TR(c, it) for (auto(it) = (c).begin(); (it) != (c).end(); (it)++) #define MAX_PRECISION cout << setprecision(numeric_limits<double>::max_digits10); // 1: circle; // 2: isosceles triangle with the length of height equal to the length of base; // 3: square. i32 main() { ios::sync_with_stdio(false); // Makes IO faster, remove this line if C style scanf/printf needed. i32 n; cin >> n; vi32 a(n); REP(i, 0, n) { cin >> a[i]; } i32 count = 0; bool cInS = false; REP(i, 1, n) { switch (a[i - 1]) { case 1: if (cInS) { count += a[i] == 2 ? 2 : 4; } else { count += a[i] == 2 ? 3 : 4; } cInS = false; break; case 2: if (a[i] == 3) { cout << "Infinite" << endl; return 0; } count += 3; cInS = false; break; case 3: if (a[i] == 2) { cout << "Infinite" << endl; return 0; } count += 4; cInS = true; break; default: break; } } cout << "Finite\n" << count << endl; }
true
3519206abd5ae5cd788a03f557037b23d959ed9c
C++
Gnnnar/search_server
/net/TcpConnection.h
UTF-8
2,119
2.75
3
[]
no_license
#pragma once #include "Callbacks.h" #include "InetAddress.h" #include "Buffer.h" #include "../base/noncopyable.h" #include "Wheel.h" class Channel; class EventLoop; class Socket; class TcpConnection : noncopyable ,public std::enable_shared_from_this<TcpConnection> { public: TcpConnection(EventLoop* loop, const std::string& name, int sockfd, const InetAddress& localAddr, const InetAddress& peerAddr); ~TcpConnection(); EventLoop* getLoop() const { return _loop; } const std::string& name() const { return _name; } const InetAddress& localAddress() { return _localAddr; } const InetAddress& peerAddress() { return _peerAddr; } bool connected() const { return _state == kConnected; } void send(const std::string& message); void shutdown(); void forceClose(); void setContext(WeakEntryPtr& context) { _context = context; } const WeakEntryPtr& getContext() const { return _context; } void setConnectionCallback(const ConnectionCallback& cb) { _connectionCallback = cb; } void setMessageCallback(const MessageCallback& cb) { _messageCallback = cb; } void setCloseCallback(const CloseCallback& cb) { _closeCallback = cb; } void connectEstablished(); void connectDestroyed(); private: enum StateE { kConnecting, kConnected, kDisconnecting, kDisconnected }; void setState(StateE s) { _state = s; }; void handleRead(Timestamp receiveTime); void handleWrite(); void handleClose(); void handleError(); void sendInLoop(const std::string& message); void shutdownInLoop(); void forceCloseInLoop(); EventLoop *_loop; std::string _name; StateE _state; std::unique_ptr<Socket> _socket; std::unique_ptr<Channel> _channel; const InetAddress _localAddr; const InetAddress _peerAddr; ConnectionCallback _connectionCallback; MessageCallback _messageCallback; CloseCallback _closeCallback; Buffer _inputBuffer; Buffer _outputBuffer; WeakEntryPtr _context; };
true
39e2dd16436a9fb4718fcb7cb1653f0a38efb540
C++
BiPaulEr/3d-Complex-Asset-Representation-by-Hybrid-
/Sources/MeshLoader.h
UTF-8
2,735
2.765625
3
[]
no_license
#ifndef MESH_LOADER_H #define MESH_LOADER_H #include <string> #include <memory> #include "Mesh.h" namespace MeshLoader { //Explaination of the function of each attribute is in Mesh.h // Loads an OFF mesh file. See https://en.wikipedia.org/wiki/OFF_(file_format) void loadOFF (const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Write List of indices of adjacent triangles in the file void writeEdges(const std::string & filename, std::shared_ptr<Mesh> meshPtr); // Load attribut triangle_Adj_Edges from mesh object void loadEdges(const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Write in files the ListofTriangles and Vertex from DataInterpolation, size_radius used to analyse the mesh, the transfer data between thow sizes, the new position of vertex after the decimation void writeScaleDataInterpolation(const std::string & filename, std::shared_ptr<Mesh> meshPtr, float &taille_radius); //Load data from file to fill the attributes from mesh object : DataInterpolationVertexLoad/DataInterpolationTrianglesLoad/vertex_transferGroupe_load/vertexPositions_NEWLoad/size_radius void loadScaleDataInterpolation(const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Show Data from m_vertexPositions_NEWLoad/m_DataInterpolationTrianglesLoad/m_DataInterpolationVertexLoad/m_vertex_transferGroupe_load void showScaleDataInterpolation(std::shared_ptr<Mesh> meshPtr); //Write Potentiel and real macro surfaces current groupe object : Need to have component_Triangle_Potentiel_MacroSurface and component_Triangle_Real_MacroSurface initialise void writePotentielAndRealMacrosurface(const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Load component_Triangle_Potentiel_MacroSurface_Load and component_Triangle_Real_MacroSurface_Load which is currentGroupe of vertex void loadPotentielAndRealMacrosurface(const std::string & filename, std::shared_ptr<Mesh> meshPtr); void writeDecimationAndVoxel(const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Load attributes vertexDecimationPositionsLoad/ triangleDecimationIndicesLoad/vertexVoxelPositionsLoad/triangleVoxelIndicesLoad from files to Mesh input void loadDecimationAndVoxel(const std::string & filename, std::shared_ptr<Mesh> meshPtr); //Write all attribute needed for interpolation/decmation/voxellisation in the files void WriteAllDataToFiles(std::string Name, std::shared_ptr<Mesh> meshPtr, float taille_radius); //Load all attribute needed for interpolation/decmation/voxellisation from the files void LoadAllDataFromFiles(std::string Name, std::shared_ptr<Mesh> & meshPtr); //Show to the console all the attributes load to check void ShowAllDataLoaded(std::shared_ptr<Mesh> MeshPtr); } #endif // MESH_LOADER_H
true
e28d23a0c965cbac4979f7065bc3846b81357105
C++
FinixLei/leetcode_finix
/src/74_medium_Search2DMatrix.cpp
UTF-8
2,440
4.0625
4
[]
no_license
/* Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. */ #include <vector> #include <iostream> #include <algorithm> using namespace std; template<typename T> void print_vec(vector<T> vec) { for (auto v : vec) { cout << v << " " ; } cout << endl; } bool searchMatrix_way1(vector<vector<int>>& matrix, int target) { int row = matrix.size(); if (row == 0) return false; int col = matrix[0].size(); int min_num = matrix[0][0]; int max_num = matrix[row-1][col-1]; if (target < min_num || target > max_num) return false; if (target == min_num || target == max_num) return true; vector<int> headers; headers.reserve(row); for (int i=0; i<row; i++) { headers.push_back(matrix[i][0]); } auto it = std::lower_bound(headers.begin(), headers.end(), target); if ( it != headers.end() ) { if (*it == target) return true; int val = *(--it); int i = 0; for (; i<row; i++) { if (headers[i] == val) break; } return binary_search(matrix[i].begin(), matrix[i].end(), target); } else { return binary_search(matrix[row-1].begin(), matrix[row-1].end(), target); } } bool searchMatrix_way2(vector<vector<int>>& matrix, int target) { int row = matrix.size(); if (row == 0) return false; int col = matrix[0].size(); int min_num = matrix[0][0]; int max_num = matrix[row-1][col-1]; if (target < min_num || target > max_num) return false; int total_num = row * col; vector<int> vec; vec.reserve(total_num); for (int i=0; i<row; ++i) { copy(matrix[i].begin(), matrix[i].end(), back_inserter(vec)); } return binary_search(vec.begin(), vec.end(), target); } int main() { vector<vector<int>> matrix { {1,3,5,7}, {10,11,16,20}, {23,30,34,60} }; int target = 3; bool result = searchMatrix_way1(matrix, target); cout << "result is " << std::boolalpha << result << endl; matrix = { {1,3} }; target = 2; cout << "result is " << std::boolalpha << result << endl; return 0; }
true
a79ea3a6b66fc37c172d9527d0211a7a5f8be990
C++
JazInimicus/Advanced-Mathematics-2-Summersemester-2021
/4. Praktikum/main.cpp
UTF-8
3,618
3.140625
3
[]
no_license
#include <iostream> #include "CKomplex.h" int main() { int input = 0; std::cout << "1 - Test Addition zweier komplexer Zahlen" << std::endl; std::cout << "2 - Test Multiplikation zweier komplexer Zahlen" << std::endl; std::cout << "3 - Test Multiplikation komplexer Zahlen mit double" << std::endl; std::cout << "4 - Test Aufgabe 2" << std::endl; std::cout << "5 - Ausgabe von Epsilon" << std::endl; std::cout << "6 - Maximale Abweichung" << std::endl; CKomplex komp1(2, 3); CKomplex komp2(4, 1); std::cin >> input; switch (input) { case 1: { CKomplex add = komp1 + komp2; std::cout << add.re() << " + " << add.im() << std::endl; break; } case 2: { CKomplex mult = komp1 * komp2; std::cout << mult.re() << " + " << mult.im() << std::endl; break; } case 3: { CKomplex mult = komp1 * 2; std::cout << mult.re() << " + " << mult.im() << std::endl; break; } case 4: { std::vector<CKomplex> values = werte_einlesen("Daten_original.txt"); werte_ausgeben("test1.txt", values, 10); } case 5: { std::vector<CKomplex> values_O = werte_einlesen("Daten_original.txt"); std::vector<CKomplex> values_FT = f_transformation(values_O, false); werte_ausgeben("DatenF1.txt", values_FT, -1.0); std::vector<CKomplex> values_FT_inv = f_transformation(werte_einlesen("DatenF1.txt"), true); werte_ausgeben("DatenF1inv.txt", values_FT_inv, -1.0); std::vector<CKomplex> values_FT2 = f_transformation(values_O, false); werte_ausgeben("DatenF2.txt", values_FT2, 0.001); std::vector<CKomplex> values_FT2_inv = f_transformation(werte_einlesen("DatenF2.txt"), true); werte_ausgeben("DatenF2inv.txt", values_FT2_inv, 0.001); std::vector<CKomplex> values3_FT = f_transformation(values_O, false); werte_ausgeben("DatenF3.txt", values_FT, 0.01); std::vector<CKomplex> values_FT3_inv = f_transformation(werte_einlesen("DatenF3.txt"), true); werte_ausgeben("DatenF3inv.txt", values_FT3_inv, 0.01); std::vector<CKomplex> values_FT4 = f_transformation(values_O, false); werte_ausgeben("DatenF4.txt", values_FT4, 0.1); std::vector<CKomplex> values_FT4_inv = f_transformation(werte_einlesen("DatenF4.txt"), true); werte_ausgeben("DatenF4inv.txt", values_FT4_inv, 0.1); std::vector<CKomplex> values_FT5 = f_transformation(values_O, false); werte_ausgeben("DatenF5.txt", values_FT5, 1.0); std::vector<CKomplex> values_FT5_inv = f_transformation(werte_einlesen("DatenF5.txt"), true); werte_ausgeben("DatenF5inv.txt", values_FT5_inv, 1.0); break; } case 6: { std::vector<CKomplex> values_O = werte_einlesen("Daten_original.txt"); std::vector<CKomplex> values_FT = f_transformation(values_O, false); werte_ausgeben("DatenFur.txt", values_FT, -1.0); std::vector<CKomplex> test = werte_einlesen("DatenFur.txt"); std::vector<CKomplex> values_FT_inv = f_transformation(test, true); //werte_ausgeben("DatenFinv.txt", values_FT_inv, -1.0); std::cout << "Maximale Abweichung bei Epsilon = -1.0 : " << difference(values_O, values_FT_inv) << std::endl; for (double epsilon = 0.001; epsilon < 2; epsilon *= 10) { std::vector<CKomplex> values_FT = f_transformation(values_O, false); werte_ausgeben("DatenFur.txt", values_FT, epsilon); std::vector<CKomplex> values_FT_inv = f_transformation(werte_einlesen("DatenFur.txt"), true); //werte_ausgeben("DatenFurinv.txt", values_FT_inv, epsilon); difference(values_FT, values_FT_inv); std::cout << "Maximale Abweichung bei Epsilon = " << epsilon << " : " << difference(values_O, values_FT_inv) << std::endl; } break; } } system("PAUSE"); return 0; }
true
2f5ad92189d866e3738325217610416b5f46815b
C++
fungoshacks/HEXER
/Mutator.cpp
UTF-8
488
2.75
3
[]
no_license
#include "Mutator.h" #include "windows.h" Mutator::Mutator(int cycles) { _cycles = cycles; } string Mutator::random_filename(string name) { static const char values[25] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'n', 'p', 'q', 'r', 's','t', 'u', 'v', 'x', 'y', 'z'}; char x; for (int i = 0; i < 16; ++i) { x = values[rand() % 25]; name.append(&x, 1); } name.append(".pdf"); return name; }
true
7a57a95ec15143ad9d28e5b35d98402e16746d83
C++
local-projects/ofxOrbbecAstra
/libs/astra/include/AstraUL/streams/Hand.h
UTF-8
5,525
2.671875
3
[]
no_license
#ifndef HAND_H #define HAND_H #include <Astra/Astra.h> #include <stdexcept> #include <AstraUL/astraul_ctypes.h> #include <AstraUL/streams/hand_capi.h> #include <AstraUL/Vector.h> namespace astra { class HandPoint : public astra_handpoint_t { public: HandPoint(std::int32_t trackingId, astra_handstatus_t status, Vector2i depthPosition, Vector3f worldPosition, Vector3f worldDeltaPosition) { astra_handpoint_t::trackingId = trackingId; astra_handpoint_t::status = status; astra_handpoint_t::depthPosition = depthPosition; astra_handpoint_t::worldPosition = worldPosition; astra_handpoint_t::worldDeltaPosition = worldDeltaPosition; } HandPoint(const astra_handpoint_t& handPoint) { *this = handPoint; } HandPoint& operator=(const ::astra_handpoint_t& handPoint) { astra_handpoint_t::trackingId = handPoint.trackingId; astra_handpoint_t::status = handPoint.status; astra_handpoint_t::depthPosition = handPoint.depthPosition; astra_handpoint_t::worldPosition = handPoint.worldPosition; astra_handpoint_t::worldDeltaPosition = handPoint.worldDeltaPosition; return *this; } inline operator ::astra_handpoint_t*() { return this; } inline operator const ::astra_handpoint_t*() const { return this; } inline int32_t trackingId() const { return astra_handpoint_t::trackingId; } inline astra_handstatus_t status() const { return astra_handpoint_t::status; } inline Vector2i depthPosition() const { return astra_handpoint_t::depthPosition; } inline Vector3f worldPosition() const { return astra_handpoint_t::worldPosition; } inline Vector3f worldDeltaPosition() const { return astra_handpoint_t::worldDeltaPosition; } private: astra_handpoint_t m_handPoint; Vector2i m_depthPosition; Vector3f m_worldPosition; Vector3f m_worldDeltaPosition; }; using HandPointList = std::vector<HandPoint>; class HandStream : public DataStream { public: explicit HandStream(astra_streamconnection_t connection) : DataStream(connection), m_handStream(connection) { } static const astra_stream_type_t id = ASTRA_STREAM_HAND; bool get_include_candidate_points() { bool includeCandidatePoints; astra_handstream_get_include_candidate_points(m_handStream, &includeCandidatePoints); return includeCandidatePoints; } void set_include_candidate_points(bool includeCandidatePoints) { astra_handstream_set_include_candidate_points(m_handStream, includeCandidatePoints); } private: astra_handstream_t m_handStream; }; class HandFrame { public: template<typename TFrameType> static TFrameType acquire(astra_reader_frame_t readerFrame, astra_stream_subtype_t subtype) { if (readerFrame != nullptr) { astra_handframe_t handFrame; astra_frame_get_handframe_with_subtype(readerFrame, subtype, &handFrame); return TFrameType(handFrame); } return TFrameType(nullptr); } HandFrame(astra_handframe_t handFrame) { m_handFrame = handFrame; if (m_handFrame) { astra_handframe_get_frameindex(m_handFrame, &m_frameIndex); size_t maxHandCount; astra_handframe_get_hand_count(m_handFrame, &maxHandCount); m_handPoints.reserve(maxHandCount); } } bool is_valid() { return m_handFrame != nullptr; } astra_handframe_t handle() { return m_handFrame; } size_t handpoint_count() { throwIfInvalidFrame(); verify_handpointlist(); return m_handPoints.size(); } const HandPointList& handpoints() { throwIfInvalidFrame(); verify_handpointlist(); return m_handPoints; } astra_frame_index_t frameIndex() { throwIfInvalidFrame(); return m_frameIndex; } private: void throwIfInvalidFrame() { if (m_handFrame == nullptr) { throw std::logic_error("Cannot operate on an invalid frame"); } } void verify_handpointlist() { if (m_handPointsInitialized) { return; } m_handPointsInitialized = true; astra_handpoint_t* handPtr; size_t maxHandCount; astra_handframe_get_shared_hand_array(m_handFrame, &handPtr, &maxHandCount); for (size_t i = 0; i < maxHandCount; ++i, ++handPtr) { astra_handpoint_t& p = *handPtr; if (p.status != astra_handstatus_t::HAND_STATUS_NOTTRACKING) { m_handPoints.push_back(HandPoint(p)); } } } bool m_handPointsInitialized{ false }; HandPointList m_handPoints; astra_handframe_t m_handFrame{nullptr}; astra_frame_index_t m_frameIndex; }; } #endif /* HAND_H */
true
d1a24160aa1bf04c41de00a20f0dfcb5e8e882a6
C++
derek-zr/leetcode
/Solution/376-wiggle-subsequence/wiggle-subsequence.cpp
UTF-8
2,840
3.6875
4
[]
no_license
// A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. // // For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero. // // Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. // // Example 1: // // // Input: [1,7,4,9,2,5] // Output: 6 // Explanation: The entire sequence is a wiggle sequence. // // // Example 2: // // // Input: [1,17,5,10,13,15,10,5,16,8] // Output: 7 // Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8]. // // // Example 3: // // // Input: [1,2,3,4,5,6,7,8,9] // Output: 2 // // Follow up: // Can you do it in O(n) time? // // // class Solution { public: int wiggleMaxLength(vector<int>& nums) { //https://www.cnblogs.com/grandyang/p/5697621.html //第二种方法是贪心,从上面链接评论图可以看出,在找到大于或小于的序列时,无需比较大小,直接更新即可,因为一定能够组成更长的子序列 if (nums.empty()) return 0; int positive = 1, negative = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i] > nums[i-1]) positive = negative + 1; else if (nums[i] < nums[i-1]) negative = positive + 1; } return max(positive, negative); /* //第一种方法是dp,由于是寻找子序列,根据当前的差值是正还是负可以建立两个dp数组 //分别表示到i位置的差值为正或负的最大子序列长度 if (nums.empty()) return 0; int len = nums.size(); vector<int> positive(len, 1); vector<int> negative(len, 1); //dp for (int i = 1; i < len; ++i) { for (int j = 0; j < i; ++j) { if (nums[i] > nums[j]) { //can add one positive seq to the neg seq end with j positive[i] = max(positive[i], negative[j] + 1); } else if (nums[i] < nums[j]){ negative[i] = max(negative[i], positive[j] + 1); } } } return max(positive.back(), negative.back()); */ } };
true
e110a82481292b68a33ebfdc5af0108c4561863f
C++
Falcone-H/Algorithm
/AcWing/七夕祭.cpp
UTF-8
1,581
2.703125
3
[]
no_license
// https://www.acwing.com/solution/content/9524/ // c[i] = c[i - 1] + a[i] - avg #include<bits/stdc++.h> #define int long long using namespace std; const int N = 1e5 + 5; int n, m, t; int row[N], col[N], tmp[N]; signed main() { cin >> n >> m >> t; for (int i = 1; i <= t; i++) { int x, y; cin >> x >> y; row[x]++, col[y]++; } int res1 = -1; if (t % n == 0) { int sum = 0; for (int i = 1; i <= n; i++) sum += row[i]; int avg = sum / n; for (int i = 1; i <= n; i++) tmp[i] = tmp[i - 1] + row[i] - avg; sort(tmp + 1, tmp + 1 + n); int mid = tmp[(n >> 1) + 1]; res1 = 0; for (int i = 1; i <= n; i++) res1 += abs(mid - tmp[i]); } int res2 = -1; if (t % m == 0) { int sum = 0; for (int i = 1; i <= m; i++) sum += col[i]; int avg = sum / m; for (int i = 1; i <= m; i++) tmp[i] = tmp[i - 1] + col[i] - avg; sort(tmp + 1, tmp + m + 1); int mid = tmp[(m >> 1) + 1]; res2 = 0; for (int i = 1; i <= m; i++) res2 += abs(mid - tmp[i]); } if (res1 != -1 && res2 != -1) { cout << "both "; cout << res1 + res2 << endl; } else if (res1 != -1) { cout << "row "; cout << res1 << endl; } else if (res2 != -1) { cout << "column "; cout << res2 << endl; } else { cout << "impossible" << endl; } return 0; }
true
058858d3971ef1a34a8a40ec426fe66b70b2b299
C++
STMU-IEEE/Robotics-16-17
/TestComm/TestComm.ino
UTF-8
746
3.234375
3
[ "MIT" ]
permissive
int LED = 13; int state = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(LED, OUTPUT); } void loop() { // put your main code here, to run repeatedly: commands(); } void commands(){ if(Serial.available() > 0){ int input = Serial.read(); switch(input){ case '1': light_on(); break; case '0': light_off(); break; case 's': delay(10); light_state(); } } } void light_on(){ digitalWrite(LED, HIGH); } void light_off(){ digitalWrite(LED, LOW); } void light_state(){ state = digitalRead(LED); if(state == HIGH){ Serial.print("1"); } if(state == LOW){ Serial.print("0"); } }
true
51023c0bfb2c5757342ac67d7f673c3dd7da5963
C++
diskursmonger/RNA
/rna.h
UTF-8
1,123
2.609375
3
[]
no_license
#ifndef rna_h #define rna_h //#include <iostream> #pragma once typedef unsigned char Nucleotide; const Nucleotide A = 0b00; const Nucleotide G = 0b01; const Nucleotide C = 0b10; const Nucleotide T = 0b11; class reference; class RNA { friend class reference; int length = 0; int blocks = 1; Nucleotide* rna = nullptr; public: RNA(int length, Nucleotide); RNA(); RNA(const RNA&); RNA& add(Nucleotide); unsigned char get(int) const; RNA& put(int, Nucleotide); RNA& put_ref(int, Nucleotide); RNA operator+(const RNA&); RNA& operator=(const RNA&); unsigned char operator[](int) const; reference operator[](int); RNA& split(int); bool isComplimentary(const RNA&); bool operator==(const RNA&); bool operator!=(const RNA&); RNA operator!(); void get_length(); ~RNA() { delete[]rna; } }; class reference { int index = 0; RNA* rna_ref; public: reference(RNA&, int); ~reference() {}; reference& operator=(const reference&); reference& operator=(const Nucleotide); operator unsigned char(); }; #endif
true
9e4d9ea920600fb47460eae38a8374115077ca92
C++
prateekroy/SPOJ
/AGGRCOW.cpp
UTF-8
2,179
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <cstring> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <ctime> #include <vector> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include "limits.h" #include <time.h> #include <stdio.h> using namespace std; int bin_search(vector<int> _time, int b){ int low = 0; int high = _time.size() - 1; while (low <= high) { int mid = low + ((high - low) / 2); if (_time[mid] > b) high = mid - 1; else if (_time[mid] < b) low = mid + 1; else return mid; // found } return -1; // not found } bool TryFor(vector<int> sheds, int dist, int C){ // cout << sheds.size() << " " << dist << " " << C << endl; int cowsPlaced = 0; int prev = sheds[0]; for (int shed = 1; shed < sheds.size(); ++shed) { if( sheds[shed] - prev >= dist ){ prev = sheds[shed]; cowsPlaced++; // cout << "cowsPlaced : " << cowsPlaced << endl; } if (cowsPlaced == C-1) { return true; } } return false; } int findSolution(vector<int> sheds, int max, int min, int C){ int start=0,end=max-min,mid; while(end-start > 1) { mid=(end+start)>>1; if (TryFor(sheds, mid, C)) { start = mid; } else { end = mid; } } return start; } int main(int argc, char const *argv[]) { int testcases; cin >> testcases; for (int tc = 0; tc < testcases; ++tc) { int N, C; cin >> N >> C; int max = INT_MIN; int min = INT_MAX; int x; vector<int> sheds; for (int i = 0; i < N; ++i) { cin >> x; if (x > max) { max = x; } if (x < min) { min = x; } sheds.push_back(x); } // cout << max << " " << min << endl; std::sort(sheds.begin(), sheds.end()); cout << findSolution(sheds, max, min, C) << endl; // for (int trys = 1; trys < (max-min); ++trys) // { // if (TryFor(sheds, trys, C)) // { // //cout << trys-1 << endl; // // break; // continue; // } // else // { // cout << trys-1 << endl; // break; // } // } } return 0; }
true
b9f8e181a8db84c9f99255fc4b8109d02e5359de
C++
mehtaanuj95/practice_codes
/geeksforgeeks/majority_element.cpp
UTF-8
1,081
4.03125
4
[]
no_license
// Find the majority element //A majority element is an eleemnt which appears more than n/2 times. #include <iostream> #include <stdio.h> using namespace std; int majority_optimised(int a[], int size) { int count = 1, maj_index = 0; for(int i = 1; i < size; i++) { if(a[maj_index] == a[i]) { count++; } else count--; if(count == 0) { maj_index = i; count = 1; } } cout<<a[maj_index]<<endl; return a[maj_index]; } void isMajority(int num, int a[], int size) { int count = 0; for(int i = 0; i < size; i++) { cout<<a[i]<<" "; if(a[i] == num) count++; } cout<<endl<<"count - "<<count; if(count > size/2) cout<<"Yes : "<<num<<endl; else cout<<"No"<<endl; } void majority(int a[], int size) { int b[1000] = {0}; int flag = 0; for(int i = 0; i < size; i++) { b[a[i]]++; } for(int i = 0; i < 1000; i++) { if(b[i] > size / 2) { cout<<i; flag++; } } if(! flag) cout<<"None"<<endl; cout<<endl; } int main() { int a[] = {3, 3, 4, 2, 4, 4, 2, 4, 4}; //majority(a, 8); isMajority(majority_optimised(a, 9), a, 9); }
true
e2e7cb233f60a99b54fde128edc47f9c85d4699c
C++
mosszhd/Problem-Solutions
/CodeforcesSolutions/490A.Team Olympiad.cpp
UTF-8
638
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); int n,skill; vector<int> v[4]; cin >> n; for(int i=1;i<=n;i++){ cin >> skill; v[skill].push_back(i); } int comp = INT_MAX; for(int i=1;i<=3;i++){ int size_vector = v[i].size(); int minimum = min(comp,size_vector); comp = minimum; } cout << comp << endl; for(int i=0;i<comp;i++) cout << v[1][i] << " " << v[2][i] << " "<< v[3][i] << endl; //<< v[1][i] << " " << v[2][i] << " " << v[3][i]; }
true
5960bbfec6e08dcccf4bf716f9c6d13e952d8956
C++
dpariag/leetcode
/reverse_vowels.cpp
UTF-8
1,960
3.6875
4
[]
no_license
// Leetcode: https://leetcode.com/problems/reverse-vowels-of-a-string/#/description // Write a function that takes a string as input and reverse only the vowels of a string. // Example: "hello" --> "holle", "leetcode" --> "leotcede". // Brute Force: // Better: #include <vector> #include <string> #include <iostream> #include <assert.h> // Accepted. 9ms. Beats 68.94% of submissions, ties 31.06% of submissions. class Solution { public: inline bool is_vowel(const char ch) { return (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U'); } std::string reverseVowels(const std::string& s) { if (s.empty()) { return s; } std::string reversed = s; int left = 0, right = reversed.size() - 1; while (left < right) { while (left < reversed.size() && !is_vowel(reversed[left])) ++left; while (right > 0 && !is_vowel(reversed[right])) --right; if (left <= right) { std::swap(reversed[left], reversed[right]); ++left; --right; } } return reversed; } }; void test_reverse_vowels() { Solution soln; assert(soln.reverseVowels("") == ""); assert(soln.reverseVowels("e") == "e"); assert(soln.reverseVowels("aA") == "Aa"); assert(soln.reverseVowels("ex") == "ex"); assert(soln.reverseVowels("exe") == "exe"); assert(soln.reverseVowels("axe") == "exa"); assert(soln.reverseVowels("axE") == "Exa"); assert(soln.reverseVowels("hello") == "holle"); assert(soln.reverseVowels("leetcode") == "leotcede"); assert(soln.reverseVowels("aaaaa") == "aaaaa"); assert(soln.reverseVowels("zZz") == "zZz"); assert(soln.reverseVowels("aeiou") == "uoiea"); } int main(int argc, char** argv) { test_reverse_vowels(); std::cout << argv[0] + 2 << "...OK!" << std::endl; return 0; }
true
06d69261b43af57583cf4e43bf6a22ba857c12ab
C++
mirceamt/MPACK
/jni/MPACK/Resources/SDInputFile.cpp
UTF-8
2,630
2.609375
3
[ "Apache-2.0" ]
permissive
#include "SDInputFile.hpp" #include "Log.hpp" namespace MPACK { namespace Core { SDInputFile::SDInputFile(const char* pPath): Resource(pPath), mInputStream(), mBuffer(NULL) { } ReturnValue SDInputFile::Open() { mInputStream.open(mPath, std::ios::in | std::ios::binary); return mInputStream ? RETURN_VALUE_OK : RETURN_VALUE_KO; } void SDInputFile::Close() { if(mInputStream.is_open()) { mInputStream.close(); } if(!mBuffer) { delete[] mBuffer; mBuffer = NULL; } } ReturnValue SDInputFile::Read(void* pBuffer, size_t count) { mInputStream.read((char*)pBuffer, count); return (!mInputStream.fail()) ? RETURN_VALUE_OK : RETURN_VALUE_KO; } ReturnValue SDInputFile::ReadFrom(int offset, void* pBuffer, size_t count) { if(mInputStream.is_open()) { int oldOffset=GetOffset(); SetOffset(offset); Read(pBuffer,count); SetOffset(oldOffset); } } const void* SDInputFile::Bufferize() { int lSize = GetLength(); if (lSize <= 0) { return NULL; } if(mBuffer != NULL) { LOGI("Already bufferized"); return mBuffer; } mBuffer = new char[lSize+1]; int pos = mInputStream.tellg(); mInputStream.seekg(0); mInputStream.read(mBuffer, lSize); mInputStream.seekg(pos); mBuffer[lSize]=0; if (!mInputStream.fail()) { return mBuffer; } else { LOGE("Bufferize failed for SDInputFile %s", mPath); return NULL; } } int SDInputFile::GetOffset() { if(mInputStream.is_open()) { int offset=mInputStream.tellg(); if(offset < -1) { LOGE("SDInputFile::GetOffset error: tellg() returned -1 yet file is still opened!"); } return offset; } else { return 0; } } void SDInputFile::SetOffset(int offset) { if(mInputStream.is_open()) { mInputStream.seekg(offset, mInputStream.beg); } } void SDInputFile::Skip(int bytes) { if(mInputStream.is_open()) { int offset=GetOffset(); SetOffset(offset+bytes); } } int SDInputFile::GetLength() { int len; if(mInputStream.is_open()) { int pos = mInputStream.tellg(); mInputStream.seekg(0, mInputStream.end); len = mInputStream.tellg(); mInputStream.seekg(pos); } else { std::ifstream file( mPath, std::ios::binary | std::ios::ate); len = file.tellg(); file.close(); } return len; } SDInputFile::~SDInputFile() { Close(); } } }
true
6304440e3f2d8c6919f2a6f45e4e786fb2be47ee
C++
tobytyx/leetcode
/面试题26_树的子结构.cpp
UTF-8
951
3.4375
3
[]
no_license
#include<iostream> #include<vector> #include<deque> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isSubStructure(TreeNode* A, TreeNode* B) { if(A == NULL || B == NULL) return false; vector<TreeNode*> stack(1, A); while(!stack.empty()){ TreeNode* root = stack.back(); stack.pop_back(); if(isSub(root, B)) return true; if(root->right != NULL) stack.push_back(root->right); if(root->left != NULL) stack.push_back(root->left); } return false; } bool isSub(TreeNode* A, TreeNode* B){ if(B == NULL) return true; if(A == NULL) return false; if(A->val == B->val && isSub(A->left, B->left) && isSub(A->right, B->right)) return true; return false; } };
true
3dca436bef45c48e444bb4bdd2a6a76b2fecdd41
C++
TimDarcet/MyRayTracer
/Triangle.h
UTF-8
800
3.09375
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include "Vec3.h" #include "Vertex.h" using namespace std; class Triangle { public: vector<int> m_vertices; Triangle(int p0, int p1, int p2) { m_vertices = {p0, p1, p2}; } // Vec3f normal() { // Vec3f p0 = m_vertices[0]->m_point; // Vec3f p1 = m_vertices[1]->m_point; // Vec3f p2 = m_vertices[2]->m_point; // Vec3f n = cross(p1 - p0, p2 - p0); // n.normalize(); // return n; // } // float area() { // Vec3f p0 = m_vertices[0]->m_point; // Vec3f p1 = m_vertices[1]->m_point; // Vec3f p2 = m_vertices[2]->m_point; // return cross(p1 - p0, p2 - p0).length() / 2.0f; // } };
true
fa5847fd94965dbac9f5459096ba8ebc1e284209
C++
SimaoAraujo/ScopeMainProcess
/process.cpp
UTF-8
1,366
2.734375
3
[]
no_license
#include "process.h" CProcess* CProcess::instance = nullptr; CProcess* CProcess::getInstance() { if(!instance) instance = new CProcess(); return instance; } CProcess::CProcess() { } CProcess::~CProcess() { } CRecord* CProcess::getCRecord() { static CRecord *oRecord = CRecord::getInstance(); oRecords.push_back(oRecord); return oRecord; } int CProcess::getDaemonPid() { FILE *fp; char cmdInfo[10] = {}; char cPid[10] = {}; /* Open the command for reading. */ fp = popen("ps -Af | grep /etc/SCOPE/ScopeDaemonProcess", "r"); if (fp == nullptr) { printf("Failed to run command\n" ); exit(1); } /* Read the output a line at a time - output it. */ fgets(cmdInfo, sizeof(cmdInfo), fp); /* close */ pclose(fp); cout << cmdInfo << endl; int firstPidIndex = 0; while (cmdInfo[firstPidIndex] == ' ') { firstPidIndex++; } int cPidIndex = 0; while (cmdInfo[firstPidIndex] != ' ') { cPid[cPidIndex] = cmdInfo[firstPidIndex]; cPidIndex++; firstPidIndex++; } int pid = 0; pid = atoi(cPid); cout << "Daemon PID: "<< pid << endl; return pid; } void CProcess::sendDaemonSignal(string sig) { string signal = "kill -s " + sig + " " + to_string(getDaemonPid()); system(signal.c_str()); }
true
22742439eeccd7534aaf657aafaf4a82b2e76096
C++
centuryglass/Pocket-Home-Bismuth
/Source/System/Wifi/LibNM/Wifi_LibNM_SSID.h
UTF-8
4,073
3.15625
3
[]
no_license
#pragma once /** * @file Wifi_LibNM_SSID.h * * @brief Stores a Wifi access point's ID. */ #include "JuceHeader.h" #include <glib.h> namespace Wifi { namespace LibNM { class SSID; } } /** * @brief Represents the ID name of a Wifi network broadcast by a Wifi access * point. * * SSID values are stored as byte arrays. SSID values are usually descriptive * string values, but they may contain unprintable characters or lack a null * terminator. SSID object store one of these values, allowing it to be * accessed as a raw byte array or a sanitized String object. */ class Wifi::LibNM::SSID { public: /** * @brief Creates this SSID copying another SSID. * * @param toCopy The other SSID to copy. */ SSID(const SSID& toCopy); /** * @brief Creates this SSID from a temporary SSID object. * * @param toCopy The temporary SSID to copy. */ SSID(SSID&& toCopy); /** * @brief Creates this SSID from a SSID byte string. * * @param toCopy The SSID byte string this object will copy. */ SSID(const GByteArray* toCopy = nullptr); /** * @brief Frees all SSID data on destruction. */ virtual ~SSID(); /** * @brief Gets a text representation of this SSID. * * @return The SSID, as a text string suitable for display or debugging. */ juce::String toString() const; /** * @brief Gets this SSID's internal SSID byte string. * * @return The SSID's exact value, as a byte array that may contain * unprintable characters. */ GByteArray* getByteArray() const; /** * @brief Assigns another SSID's data to this SSID. * * @param toCopy Another SSID this SSID object should copy. * * @return This SSID object. */ SSID& operator= (const SSID& toCopy); /** * @brief Assigns a copy of an SSID bytestring to this SSID. * * @param toAssign A SSID byte string that will be used to replace this * object's data. * * @return This SSID object. */ SSID& operator= (GByteArray* toAssign); /** * @brief Checks if two SSIDs are equivalent. * * @param rhs Another SSID to compare with this one. * * @return Whether both SSIDs have identical stored values. */ bool operator== (const SSID& rhs) const; /** * @brief Checks if two SSIDs are not equivalent. * * @param rhs Another SSID to compare with this one. * * @return Whether both SSIDs do not have identical stored values. */ bool operator!= (const SSID& rhs) const; /** * @brief Compares this object with another SSID alphabetically. * * @param rhs Another SSID to compare with this one. * * @return Whether this SSID's byte string comes before rhs. */ bool operator< (const SSID& rhs) const; /** * @brief Checks if a SSID and a raw SSID byte string are equivalent. * * @param rhs A raw SSID bytestring to compare to this object. * * @return Whether this object's internal byte string matches rhs. */ bool operator== (GByteArray* rhs) const; /** * @brief Checks if a SSID and a raw SSID byte string are not equivalent. * * @param rhs A raw SSID bytestring to compare to this object. * * @return Whether this object's internal byte string does not match * rhs. */ bool operator!= (GByteArray* rhs) const; private: /** * @brief Copies a SSID byte string, storing it in this object. * * @param toCopy An SSID byte string to copy, or nullptr to set this * object to a null value. */ void copyByteArray(const GByteArray* ssidBytes); /** * @brief Frees any non-null SSID byte string stored in this object. */ void clearByteArray(); // Stores the SSID value as a byte string. GByteArray* ssidBytes = nullptr; };
true
ec092671f8daa57a9e1dc2bae1e0eda571204f9e
C++
IvoStoilov/Raytracer
/source/core/geometry/plane.h
UTF-8
423
2.78125
3
[]
no_license
#pragma once #include "core/geometry/geometry.h" #include "core/math/vec4.h" class Plane : public Geometry { public: Plane(const vec4& normal, float d) : m_Normal(normal), m_D(d) {} virtual bool IntersectsWith(const Ray& r, IntersectionInfo& outInfo) override; virtual vec4 GetNormal(const vec4& collisionPoint) override { return m_Normal; } private: vec4 m_Normal; float m_D; };
true
032ad355672ccf43ab2124907dd90ec56f479f89
C++
hanseul1795/ElkCraft
/ElkCraft-master/Sources/ElkEngine/ElkGameEngine/include/ElkGameEngine/Objects/GameObject.h
UTF-8
1,829
2.96875
3
[ "MIT" ]
permissive
#pragma once #include <map> #include <unordered_map> #include <memory> #include <iostream> #include <type_traits> #include <typeinfo> #include "ElkGameEngine/export.h" #include "ElkGameEngine/Objects/AObject.h" #include "ElkGameEngine/Objects/Components/AComponent.h" #include "ElkGameEngine/Objects/Components/Transform.h" namespace ElkGameEngine { namespace Objects { /* * A GameObject is an Object that can be placed in the Scene. It contains differents components */ class ELK_GAMEENGINE_EXPORT GameObject : public AObject { public: GameObject(const std::string& p_name = "GameObject"); virtual ~GameObject() = default; void UpdateComponents(); template <typename Class, typename ... Args> std::shared_ptr<Class> AddComponent(Args... args); template<typename Class> std::shared_ptr<Class> GetComponent(); std::vector<std::shared_ptr<Objects::Components::AComponent>>& GetComponents(); std::shared_ptr<Objects::Components::Transform> transform; std::vector<std::shared_ptr<Objects::Components::AComponent>> m_components; }; template <typename Class, typename ... Args> std::shared_ptr<Class> ElkGameEngine::Objects::GameObject::AddComponent(Args... args) { auto newComp = std::shared_ptr<Class>(nullptr); if (std::is_base_of<Objects::Components::AComponent, Class>::value) { newComp = std::make_shared<Class>(std::forward<Args>(args)...); newComp->SetOwner(*this); m_components.push_back(newComp); return newComp; } return newComp; } template <typename Class> std::shared_ptr<Class> GameObject::GetComponent() { std::shared_ptr<Class> result(nullptr); for (auto component : m_components) { result = std::dynamic_pointer_cast<Class>(component); if (result) break; } return result; } } }
true
8ad67e1dc074348f2f92589a52efe1e2bf133b93
C++
chosungmann/book-examples
/Professional C++, 5th Edition/Code/c08_code/03_SpreadsheetCellThisAmbiguous/SpreadsheetCell.cpp
UTF-8
634
2.8125
3
[]
no_license
module spreadsheet_cell; import <charconv>; using namespace std; void SpreadsheetCell::setValue(double value) { value = value; // Confusing! } double SpreadsheetCell::getValue() const { return value; } void SpreadsheetCell::setString(string_view value) { value = stringToDouble(value); } string SpreadsheetCell::getString() const { return doubleToString(value); } string SpreadsheetCell::doubleToString(double value) const { return to_string(value); } double SpreadsheetCell::stringToDouble(string_view value) const { double number{ 0 }; from_chars(value.data(), value.data() + value.size(), number); return number; }
true
eeb552b40cbf44b38bf72089acb0f5627dc044e4
C++
dxvidnguyen/csis45
/CSIS 45 STUFF/p57.cpp
UTF-8
2,557
4.34375
4
[]
no_license
// Name: David Nguyen // File: p57.cpp // Date: 10/21/19 - 12/06/2019 // Description: Arrays Min, Max, Average // Ask the user to enter any 7 numbers into an array of float type, in any order. // Show all the entered numbers, then find the Minimum, Maximum, and Average of all the numbers in the array. #include <iostream> using namespace std; int main() { // float array float input[7]; // use for loop to get inputs of 7 numbers for (int a = 0; a < 7; a++) { cout << "Please enter a number " << (a + 1) << ": "; cin >> input[a]; } // showing all entered numbers cout << "The numbers you entered are: "; // using a for loop for array output for (int b = 0; b < 7; b++) { if (b < (7-1)) cout << input[b] << ", "; if (b == (7-1)) cout << input[b]; } // finding the average float sum = 0; float count = 0; float average = 0; for (int c = 0; c < 7; c++) { sum = sum + input[c]; count++; } // after loop we have the final sum of numbers and the count of the numbers average = sum/count; cout << count << endl; // should be 7 // finding the largest number float largest = input[0]; for (int d = 0; d < 7; d++) if (input[d] > largest ) largest = input[d]; // finding the smallest number float smallest = input[0]; for (int e = 0; e < 7; e++) if (input[e] < smallest ) smallest = input[e]; // printing stuff out cout << "The largest of the 7 numbers is: " << largest << endl; cout << "The smallest of the 7 numbers is: " << smallest << endl; cout << "The average of the 7 numbers is: " << average << endl; return 0; } /* === OUTPUT === Run 1: Please enter a number 1: 20 Please enter a number 2: 50 Please enter a number 3: 30 Please enter a number 4: 40 Please enter a number 5: 80 Please enter a number 6: 70 Please enter a number 7: 10 The numbers you entered are: 20, 50, 30, 40, 80, 70, 107 The largest of the 7 numbers is: 80 The smallest of the 7 numbers is: 10 The average of the 7 numbers is: 42.8571 Run 2: Please enter a number 1: 1.5 Please enter a number 2: 1.7 Please enter a number 3: 1.9 Please enter a number 4: 1.2 Please enter a number 5: 1.1 Please enter a number 6: 1.7 Please enter a number 7: 1.2 The numbers you entered are: 1.5, 1.7, 1.9, 1.2, 1.1, 1.7, 1.27 The largest of the 7 numbers is: 1.9 The smallest of the 7 numbers is: 1.1 The average of the 7 numbers is: 1.47143 */
true
4828475b510f3bcd4b7b1da76d5aecd1e1237cc5
C++
NirShalmon/Competitive-Programming-Code
/IOI/2010/Quality of Living.cpp
UTF-8
1,326
2.890625
3
[]
no_license
/***************** Competative programming code written by Nir Shalmon IMPORTANT NOTE: This code was written during a time limited competition or for use in competition. THIS CODE IS NOT AN INDICATION OF MY USUAL CODE QUALITY!! ******************/ #include<iostream> #include<algorithm> #include<set> using namespace std; int a[3000][3000]; set<int> s; int b[3001][3001]; int r, c, h, w; bool canBe(int k) { for (size_t y = 0; y < r; ++y) { for (size_t x = 0; x < c; x++) { if (a[y][x] < k) { b[y+1][x+1] = -1; } else if (a[y][x] == k) { b[y+1][x+1] = 0; } else { b[y+1][x+1] = 1; } } } for (size_t y = 1; y <= r; y++) { for (size_t x = 1; x <= c; x++) { b[y][x] += b[y - 1][x] + b[y][x - 1] - b[y - 1][x - 1]; if (y >= h && x >= w && b[y][x] - b[y - h][x] - b[y][x - w] + b[y - h][x - w] <= 0) { return true; } } } return false; } int main() { ios::sync_with_stdio(false); cin >> r >> c >> h >> w; for (int y = 0; y < r; ++y) { for (size_t x = 0; x < c; x++) { cin >> a[y][x]; } } int lo = w * h / 2; int hi = r * c - w * h / 2; while (lo < hi) { int t = (lo + hi) / 2; if(canBe(t)){ hi = t; } else { lo = t+1; } } cout << hi; }
true
778a9a11e32610cda108a101e851056b10200ca1
C++
LaraGalvan/Ejercicios-Algo2
/Ejercicios_TDA/TDA_TarjetaBaja/tarjeta_baja.h
UTF-8
1,030
3.0625
3
[]
no_license
#ifndef TARJETA_BAJA_H_ #define TARJETA_BAJA_H_ class TarjetaBaja{ private: double saldo; int cant_viajes_colectivo; int cant_viajes_subte; public: //Metodos //PRE: la variable saldo_inicial es positivo //POST: saldo de la tarjeta en la variable saldo_inicial TarjetaBaja(double saldo_inicial); double obtener_saldo(); //PRE: monto es positivo //POST: agrega el monto al saldo de la tarjeta void cargar(double monto); //PRE: saldo suficiente , seccion es 1, 2 o 3. //POST: utiliza del saldo $12 , $13 o $13 .75 segun la seccion para un viaje en colectivo. void pagar_viaje_colectivo(int seccion); //PRE: saldo suficiente //POST: utiliza 12.50 del saldo para un viaje en subte void pagar_viaje_subte(); //POST: devuelve la cantidad total de viajes realizados int contar_viajes(); //POST: devuelve la cantidad total de viajes en colectivo int contar_viajes_colectivo(); //POST: devuelve la cantidad de viajes en subte realizados int contar_viajes_subte(); }; #endif /* TARJETA_BAJA_H_ */
true
03ac526d7c1e3111c695e6b836f4e435e216eddc
C++
RedGreenCode/uDebug
/12455/GenerateInput.cpp
UTF-8
784
2.671875
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <ctime> using namespace std; int main(int argc, char *argv[]) { srand((unsigned int)time(NULL)); const int numCases = 20; const int maxLen = 1000; const int maxBars = 20; cout << numCases << endl; for (int i = 0; i < numCases; i++) { int bars[maxBars]; int p = (rand() % maxBars) + 1; int sum = 0; for (int j = 0; j < p ; j++) { int len = (rand() % maxLen/p) + 1; if (sum+len > maxLen) { p = j-1; break; } else { bars[j] = len; sum += len; } } int rnd = (rand() % 100); int add = (rand() % (maxLen - sum)); if (rnd > 75) sum += add; cout << sum << endl; cout << p << endl; for (int j = 0; j < p ; j++) cout << bars[j] << " "; cout << endl; } return 0; }
true
0884aa2c9e77c63e39e05a0db5b7c78543198216
C++
adrian-j-velasco/Tic_Tac_Toe_01
/Tic_Tac_Toe_01_Source.cpp
UTF-8
2,374
3.3125
3
[]
no_license
#include <iostream> #include <string> #include "CheckerBoard.h" using namespace std; void die(const string & msg); bool boardWin(CheckerBoard board); void endGame(char plyr, bool draw); int main() { bool gameFlag = true, draw = false; int holder; CheckerBoard Board; int turn = 0; char plyr; while (gameFlag) { Board.printBoard(); cin >> holder; if (!Board.tileCheck(holder)) { if (turn % 2 == 0) { plyr = 'X'; } else { plyr = 'O'; } Board.changeBoard(holder,plyr); turn++; } if (turn == 9 || boardWin(Board) ) { gameFlag = false; if (turn == 9 && !boardWin(Board)) { draw = true; } } } Board.printBoard(); endGame(plyr, draw); system("PAUSE"); return 0; } void endGame(char plyr, bool draw) { if (draw) { cout << "DRAW!\n"; } else { cout << "Player " << plyr << " Wins!\n"; } } bool boardWin(CheckerBoard board) { bool ret = false; bool flag = true; /* THIS IS WHAT I GET FOR NOT WRITING STUFF DOWN LOL Winning combination: 123,456,789,147,258,369,357,159 MY GOD IM SO BAD */ while (flag) { if (board.tileGet(1) == board.tileGet(2) && board.tileGet(1) == board.tileGet(3)) { flag = false; ret = true; } if (board.tileGet(4) == board.tileGet(5) && board.tileGet(4) == board.tileGet(6)) { flag = false; ret = true; } if (board.tileGet(7) == board.tileGet(8) && board.tileGet(7) == board.tileGet(9)) { flag = false; ret = true; } if (board.tileGet(1) == board.tileGet(4) && board.tileGet(1) == board.tileGet(7)) { flag = false; ret = true; } if (board.tileGet(2) == board.tileGet(5) && board.tileGet(2) == board.tileGet(8)) { flag = false; ret = true; } if (board.tileGet(3) == board.tileGet(6) && board.tileGet(3) == board.tileGet(9)) { flag = false; ret = true; } if (board.tileGet(3) == board.tileGet(5) && board.tileGet(3) == board.tileGet(7)) { flag = false; ret = true; } if (board.tileGet(1) == board.tileGet(5) && board.tileGet(1) == board.tileGet(9)) { flag = false; ret = true; } else { flag = false; } } return ret; } void die(const string & msg) { cerr << "Fatal Error:\n" << msg << endl; exit(EXIT_FAILURE); }
true
0c5bbb2d0806314e6d6193fe32cb97666a48921f
C++
awarirahul365/CSE-2003-Data-Structures-and-Algorithms
/Leetcode 30 Days Solution/Smallest String Starting From Leaf.cpp
UTF-8
1,430
3.234375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void roottoleaf(TreeNode *root,vector<string> &vect,int index,int arr[]) { if(root==NULL) { return; } arr[index]=root->val; index++; if(root->left==NULL && root->right==NULL) { string temp=""; for(int i=0;i<index;i++) { int num=97+arr[i]; temp=temp+(char)num; } reverse(temp.begin(),temp.end()); vect.push_back(temp); } else { roottoleaf(root->left,vect,index,arr); roottoleaf(root->right,vect,index,arr); } } string smallestFromLeaf(TreeNode* root) { if(root==NULL) { return ""; } else { vector<string>vect; vect.clear(); int index=0; int arr[1000]; roottoleaf(root,vect,index,arr); sort(vect.begin(),vect.end()); return vect[0]; } } };
true
71a396ad8589a770d0f877af936f70c2e74d1eb5
C++
moschneider/NLR
/Neurobot_bk.cpp
UTF-8
93,023
2.59375
3
[]
no_license
////////////////////////////////////////////////////////////////// // // // * * * NEURAL LABYRINTH ROBOT * * * // // // // Copyright (c) 2002 Marvin Oliver Schneider // // // // Projeto a ser apresentado no Xo. Encontro Nacional de // // Inteligencia Artificial (ENIA) durante o XXo. Congresso // // da Sociedade Brasileira de Computacao (SBC) // // // ////////////////////////////////////////////////////////////////// // // // // ---------- VERSAO --------- // ---- DATA DE ATUALIZACAO ---- // // // // // 1.0b // 29/12/2002 // // // // ////////////////////////////////////////////////////////////////// // // // -------------------- TAREFAS EM ABERTO --------------------- // // // // 1. Modificacao de labirintos mais comfortavel - OK // // 2. Testes com labirintos diferentes - OK // // 3. Implementacao da entrada adicional - OK // // 4. Testes com labirintos parecidos - OK // // 5. Completar os comentarios no codigo fonte // // ------------------------------------------------------------ // // 6. Criacao de leitura e gravacao de labirintos // // 7. Criacao de logs de aprendizado // // 8. Desenvolvimento de diferentes arquivos de labirintos // // 9. Testes finais e avaliacao dos resultados // // // ////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////// // Arquivos incluidos // /////////////////////////////////////////////////////// #include <stdio.h> // standard #include <stdlib.h> // standard #include <conio.h> // Para funcao "GETCH()" #include <math.h> // Para funcao "ABS()" #include <console.h> // Biblioteca para uso com a console // Comandos disponiveis: // clrscr( escrita | fundo ); // setcolor( escrita | fundo ); // gotoxy(x,y); // Cores disponiveis: // BLACK, BLUE, GREEN, CYAN, RED, PURPLE, BROWN, LIGHTGRAY, DARKGRAY, // LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTPURPLE, YELLOW, WHITE // Uso de cores: // XFOREGROUND_[cor] (ex: XFOREGROUND_WHITE) - cor da escrita // XBACKGROUND_[cor] (ex: XBACKGROUND_BLACK) - cor do fundo /////////////////////////////////////////////////////// // Constantes globais // /////////////////////////////////////////////////////// const char versao[5] = "1.0b"; const int x_max = 8; // numero maximo de elementos const int y_max = 8; //const int x_start = 33; // ponto de comeco do tabuleiro para saida na tela // x_start foi redefinido como variavel global no programa // principal (veja abaixo) const int y_start = 11; const int caminhos_max = 20; // numero maximo de caminhos a ser achado; const int max_itens_menu = 15; // numero maximo de itens em um menu; const int max_tabuleiros = 20; // numero maximo de tabuleiros tratados const int obstaculo = 1; // codificacao interna do tabuleiro const int vazio = 0; const int robo = 2; // apenas para visualizacao de visao com cor certa const int destino = 3; const char obstaculo_ch = char(177); // characteres para visualizacao na tela const char destino_ch[3] = "[]"; const char robo_ch[3] = "oo"; const char vazio_ch[3] = " "; const char visao_ch[3] = ".."; const int sem_giro = 0; // para administracao dos giros possiveis const int para_cima = 1; const int para_baixo = 2; const int para_esquerda = 3; const int para_direita = 4; const int dummy = -1; // valores dummy para inicializacao de arrays const int nro_codigos = 2; const int elemento_visibilidade = 2; // para processamento da rede const int elemento_obstaculo = 0; const int elemento_adicional = 1; const int True = 1; // na verdade nao necessario, mas para versoes antigas de Visual C const int False = 0; const int simples = 0; // para as caixas de mensagem const int alerta = 1; const int pergunta = 2; const int aviso = 3; const int chave = 4; // caracteres para poder fazer um tabuleiro "limpo" (codigo Ascii standard) const char ces = char(201); //canto direito superior; const char cdi = char(188); //canto esquerdo inferior; const char ho = char(205); //horizontal const char cr = char(206); //cruz const char ve = char(186); //vertical const char vhe = char(185); //vertical com linha horizontal na esquerda const char vhd = char(204); //vertical com linha horizontal na direita const char cei = char(200); //canto direito inferior const char cds = char(187); //canto esquerdo superior const char hva = char(203); //horizontal com linha vertical em cima const char hve = char(202); //horizontal com linha vertical em baixo const char cds1 = char(218); //canto direito superior; const char cei1 = char(217); //canto esquerdo inferior; const char ho1 = char(196); //horizontal const char cr1 = char(197); //cruz const char ve1 = char(179); //vertical const char vhe1 = char(180); //vertical com linha horizontal na esquerda const char vhd1 = char(195); //vertical com linha horizontal na direita const char cdi1 = char(192); //canto direito inferior const char ces1 = char(191); //canto esquerdo superior const char hva1 = char(194); //horizontal com linha vertical em cima const char hve1 = char(193); //horizontal com linha vertical em baixo const char h1 = char(196); // linha para o titulo const char s1 = char(176); // sombra 1 - a mais fraca const char s2 = char(177); // sombra 2 - um pouco mais forte const char s3 = char(178); // sombra 3 - a sombra mais forte const char s4 = char(219); // "sombra 4" - um campo solido const char right_ch = char(16); // para visualizacao de giros const char left_ch = char(17); const char up_ch = char(30); const char down_ch = char(31); const int nr_entradas = x_max*y_max*nro_codigos; // forma generica de definicao das camadas const int nr_escondidos = x_max*y_max; // por causa da topologia da rede livre ajuste possivel!! const int nr_saidas = x_max*y_max; const BOOL debug = True; // liga/desliga do modo debug /////////////////////////////////////////////////////// // Tipos globais // /////////////////////////////////////////////////////// typedef int BOOL; // variaveis booleanas typedef struct _xy { // tipo para coordenadas no tabuleiro int x, y; } XY; typedef struct _caminho { // tipo para guardar o caminho do robo do inicio ate o final XY pos[x_max*y_max]; } CAMINHO; typedef struct _caminhos { // para processamento "cache" dos caminhos CAMINHO cam[max_tabuleiros]; } CAMINHOS; typedef struct _tabuleiro { // tabuleiro (mundo virtual 2D) com todos os dados necessarios p/ processamento int numero, giros_pos; int elemento[x_max][y_max]; // tabuleiro "real" de elementos BOOL visao[x_max][y_max]; // tabuleiro de elementos visiveis XY giro[x_max*y_max]; // valor maximo nominal de giros possiveis CAMINHO cam_mem; XY destino; // destino e robo estao fora do tabuleiro para facilitar os calculos XY robo; } TABULEIRO; typedef struct _mapa { // saida da rede em forma de matriz float preferencia[x_max][y_max]; } MAPA; typedef struct _saida { // para definicao da saida certa float valor[nr_saidas]; } SAIDA; typedef struct _rede_neural { // rede neural => Perceptron Multicamadas (1 camada escondida) float entrada[nr_entradas]; float sinapse1[nr_entradas][nr_escondidos]; float escondido[nr_escondidos]; float sinapse2[nr_escondidos][nr_saidas]; float saida[nr_saidas]; } REDE_NEURAL; typedef struct _menu { char* titulo; char* item[max_itens_menu]; } MENU; /////////////////////////////////////////////////////// // Variaveis globais // /////////////////////////////////////////////////////// TABULEIRO data[max_tabuleiros]; TABULEIRO central; CAMINHO resultado; CAMINHOS cache; REDE_NEURAL rede; SAIDA saida_central; MAPA mapa_central; MENU principal, labirinto, vision; BOOL todos_ok; int total_acertos, total_giros, x_start; float taxa_erro; /////////////////////////////////////////////////////// // Prototipos de funcoes // // (Descricao das funcoes se encontra na implementa- // // cao de cada uma abaixo) // /////////////////////////////////////////////////////// void init_menus(void); void janela(int,int,int,int); BOOL caixa_mensagem(int,int,int,char*); void tecla(void); int escolha(int,int,MENU); void cor_padrao(void); void cor_visao(int); void tab(void); void titulo(void); void informacoes_gerais(void); void init_todos_tabuleiros(void); TABULEIRO init_tabuleiro(int); CAMINHO init_caminho(void); void mostra_tabuleiro(TABULEIRO,BOOL,BOOL); TABULEIRO estabelece_visao(TABULEIRO); TABULEIRO estabelece_giros(TABULEIRO); int conta_elementos(CAMINHO); int calcula_distancia(CAMINHO); CAMINHO algoritmo_simbolico(XY,TABULEIRO,CAMINHO); MAPA init_mapa(); void execute_caminho(TABULEIRO,CAMINHO); void aprende_caminho(TABULEIRO,CAMINHO); void use_algoritmo_simbolico(void); void use_rede_neural(void); void aprende_caminhos(void); float sigmoide(float); REDE_NEURAL init_rede(void); void dump_rede(REDE_NEURAL,BOOL); REDE_NEURAL feedforward(TABULEIRO,REDE_NEURAL); REDE_NEURAL backpropagation(REDE_NEURAL,SAIDA); SAIDA extrai_saidas(REDE_NEURAL); MAPA cria_mapa_das_saidas(SAIDA); SAIDA cria_saidas_do_mapa(MAPA); void modificar_tabuleiro(void); void mostra_tabuleiros(void); void mostra_mapa(MAPA); void mostra_saida(SAIDA); SAIDA gera_saida_para_teste(int,int); void testa_teclado(void); int gera_codigo_visao(TABULEIRO); int gera_codigo_obstaculos(TABULEIRO); /////////////////////////////////////////////////////// // Programa principal // /////////////////////////////////////////////////////// void main() { int opcao; BOOL final_do_programa; // testa_teclado(); x_start=39-x_max; // definicao automatica da posicao no eixo x do tabuleiro init_menus(); init_todos_tabuleiros(); final_do_programa=False; rede=init_rede(); while(final_do_programa==False) { clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); cor_padrao(); titulo(); opcao=escolha(0,8,principal); switch(opcao) { case 0: informacoes_gerais(); break; case 1: mostra_tabuleiros(); break; case 2: modificar_tabuleiro(); break; case 3: dump_rede(rede,False); break; case 4: use_algoritmo_simbolico(); break; case 5: if(caixa_mensagem(pergunta,0,20," Zerar toda a Rede? ")==True) { rede=init_rede(); caixa_mensagem(aviso,0,20," Rede inicializada com sucesso. "); } break; case 6: aprende_caminhos(); break; case 7: use_rede_neural(); break; case 8: if(caixa_mensagem(pergunta,0,20," Sair do Programa? ")==True) final_do_programa=True; break; } } clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLACK ); setcolor( XFOREGROUND_WHITE | XBACKGROUND_BLACK ); } /////////////////////////////////////////////////////// // Rotinas // /////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // Funcao: init_menus // // Descricao: Rotina de IO para inicializacao dos dialogos menu // // Parametros: - // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: Se for desejado espacos tambem precisam ser // // inicializados // ///////////////////////////////////////////////////////////////////// void init_menus(void) { principal.titulo=" MENU PRINCIPAL "; principal.item[0]=" Sobre o Sistema "; principal.item[1]=" Mostrar Labirintos "; principal.item[2]=" Modificar Labirintos "; principal.item[3]=" Dump da Rede Neural "; principal.item[4]=" Usar Algoritmo Simbolico "; principal.item[5]=" Inicializar Rede Neural "; principal.item[6]=" Aprender Caminhos "; principal.item[7]=" Usar Rede Neural "; principal.item[8]=" Sair do Programa "; principal.item[9]=NULL; labirinto.titulo=" ESCOLHA LABIRINTO "; labirinto.item[0]=" Modificar Labirinto 00 "; labirinto.item[1]=" Modificar Labirinto 01 "; labirinto.item[2]=" Modificar Labirinto 02 "; labirinto.item[3]=" Modificar Labirinto 03 "; labirinto.item[4]=" Modificar Labirinto 04 "; labirinto.item[5]=" Modificar Labirinto 05 "; labirinto.item[6]=" Modificar Labirinto 06 "; labirinto.item[7]=" Modificar Labirinto 07 "; labirinto.item[8]=" Modificar Labirinto 08 "; labirinto.item[9]=" Modificar Labirinto 09 "; labirinto.item[10]=" Modificar Labirinto 10 "; labirinto.item[11]=" Modificar Labirinto 11 "; labirinto.item[12]=NULL; vision.titulo=" ESCOLHA VISAO "; vision.item[0]=" Sem Elementos do Processamento "; vision.item[1]=" Mostrar Lugares com Visao "; vision.item[2]=" Mostrar Pontos de Giro "; vision.item[3]=" Mostrar Giros e Visao "; vision.item[4]=NULL; } ///////////////////////////////////////////////////////////////////// // Funcao: janela // // Descricao: Rotina de IO para criacao de contorno de janelas // // Parametros: Canto esquerdo superior (x,y) e comprimento das // // linhas (x,y) // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void janela(int canto_x, int canto_y, int ext_x, int ext_y) { int i, j; gotoxy(canto_x,canto_y); printf("%c",ces); for(i=0;i<ext_x;i++) printf("%c",ho); printf("%c",cds); for(i=0;i<ext_y;i++) { gotoxy(canto_x,canto_y+i+1); printf("%c",ve); for(j=0;j<ext_x;j++) printf(" "); printf("%c",ve); } gotoxy(canto_x,canto_y+ext_y+1); printf("%c",cei); for(i=0;i<ext_x;i++) printf("%c",ho); printf("%c",cdi); } ///////////////////////////////////////////////////////////////////// // Funcao: caixa_mensagem // // Descricao: Rotina para mostrar uma caixa de mensagem na tela // // Parametros: Tipo da caixa, comeco x, comeco y, texto // // Retorno: Confirmacao (se for do tipo pergunta) // // Versao: 0.1 - Versao inicial // // Observacoes: // // Tipos disponiveis // // ----------------- // // Aviso // // Pergunta // // Alerta // // Simples // // Tecla // // // ///////////////////////////////////////////////////////////////////// BOOL caixa_mensagem(int tipo, int x, int y, char* dialogo) { int comprimento_topo, comprimento_dialogo, comprimento_x, comprimento_y; char ch; BOOL confirmacao; char* topo; topo=NULL; confirmacao=False; switch(tipo) { case alerta: topo=" ALERTA "; setcolor( XFOREGROUND_WHITE | XBACKGROUND_RED ); break; case pergunta: topo=" PERGUNTA "; setcolor( XFOREGROUND_WHITE | XBACKGROUND_CYAN ); break; case aviso: topo=" AVISO "; setcolor( XFOREGROUND_WHITE | XBACKGROUND_PURPLE ); break; case simples: topo=NULL; setcolor( XFOREGROUND_WHITE | XBACKGROUND_LIGHTBLUE ); break; case chave: topo=NULL; setcolor( XFOREGROUND_WHITE | XBACKGROUND_GREEN ); break; } comprimento_dialogo=strlen(dialogo); if(topo!=NULL) comprimento_topo=strlen(topo); else comprimento_topo=0; comprimento_y=2; if(tipo==simples || tipo==chave) comprimento_y=1; if(comprimento_topo>comprimento_dialogo) comprimento_x=comprimento_topo; else comprimento_x=comprimento_dialogo; if(x==0) x=(80-comprimento_x-2)/2; // se x=0 entao assume que o dialogo deve ser posto no meio da tela janela(x,y,comprimento_x,comprimento_y); gotoxy(x+1+(comprimento_x-comprimento_dialogo)/2,y+1); printf("%s",dialogo); gotoxy(x+1+(comprimento_x-comprimento_topo)/2,y); if(topo!=NULL) printf("%s",topo); setcolor( XFOREGROUND_BLUE | XBACKGROUND_WHITE ); if(tipo==alerta || tipo==aviso) { gotoxy(x+1+(comprimento_x-4)/2,y+2); printf(" OK "); gotoxy(x+2+(comprimento_x-4)/2,y+2); getch(); } if(tipo==pergunta) { gotoxy(x+1+(comprimento_x-5)/2,y+2); printf(" S/N "); gotoxy(x+3+(comprimento_x-5)/2,y+2); ch=' '; while(ch!='N' && ch!='S' && ch!='J' && ch!='Y') { ch=getch(); ch=toupper(ch); } if(ch=='S') confirmacao=True; } if(tipo==simples || tipo==chave) { gotoxy(x+comprimento_x,y+1); } cor_padrao(); return confirmacao; } void tecla(void) { caixa_mensagem(chave,0,22," Pressione qualquer tecla para continuar.... "); getch(); } ///////////////////////////////////////////////////////////////////// // Funcao: escolha // // Descricao: Funcao de menu // // Parametros: Comeco x e comeco y como o menu inicializado // // Retorno: Item escolhido pelo usuario // // Versao: 0.1 - Versao inicial // // Observacoes: // // Uso // // --- // // [Cursor Up] ou [8] para cima no menu // // [Cursor Down] ou [2] para baixo no menu // // [Enter] ou [5] para confirmar // // // ///////////////////////////////////////////////////////////////////// int escolha(int x, int y, MENU menu_local) { int escolha_local, m, itens, comprimento, comprimento_titulo, aux, ajuste_titulo; char ch; setcolor( XFOREGROUND_WHITE | XBACKGROUND_GREEN ); comprimento=strlen(menu_local.titulo); itens=0; while(menu_local.item[itens]!=NULL) itens++; for(m=0;m<itens;m++) { aux=strlen(menu_local.item[m]); if(aux>comprimento) comprimento=aux; } if(x==0) x=(80-comprimento-2)/2; // se x=0 entao assume que o dialogo deve ser posto no meio da tela janela(x,y,comprimento,itens); escolha_local=0; comprimento_titulo=strlen(menu_local.titulo); if(comprimento_titulo<comprimento) ajuste_titulo=(comprimento-comprimento_titulo)/2; else ajuste_titulo=0; gotoxy(x+1+ajuste_titulo,y); printf("%s",menu_local.titulo); ch=' '; while(ch!=char(13) && ch!='5') { for(m=0;m<itens;m++) { gotoxy(x+1,y+1+m); if(m==escolha_local) setcolor( XFOREGROUND_BLUE | XBACKGROUND_WHITE ); printf("%s",menu_local.item[m]); setcolor( XFOREGROUND_WHITE | XBACKGROUND_GREEN); } gotoxy(x+1,y+1+escolha_local); ch=getch(); for(m=0;m<itens;m++) { gotoxy(x+1,y+1+m); printf("%s",menu_local.item[m]); } switch(ch) { case char(72): escolha_local--; if(escolha_local<0) escolha_local=itens-1; break; case char(80): escolha_local++; if(escolha_local>=itens) escolha_local=0; break; case '8': escolha_local--; if(escolha_local<0) escolha_local=itens-1; break; case '2': escolha_local++; if(escolha_local>=itens) escolha_local=0; break; } } return escolha_local; } ///////////////////////////////////////////////////////////////////// // Funcao: cor_padrao // // Descricao: Rotina que estabelece o equema de cor padrao // // Parametros: - // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void cor_padrao() { setcolor(XFOREGROUND_WHITE | XBACKGROUND_BLUE); } ///////////////////////////////////////////////////////////////////// // Funcao: cor_visao // // Descricao: Estabelece a cor na visualizacao da visao // // Parametros: Codigo do elemento a ser visualizado // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void cor_visao(int codigo) { switch(codigo) { case robo : setcolor(XFOREGROUND_LIGHTBLUE | XBACKGROUND_GREEN); break; case destino : setcolor(XFOREGROUND_LIGHTGREEN | XBACKGROUND_GREEN); break; case obstaculo : setcolor(XFOREGROUND_LIGHTRED | XBACKGROUND_GREEN); break; case vazio : setcolor(XFOREGROUND_WHITE | XBACKGROUND_GREEN); break; } } ///////////////////////////////////////////////////////////////////// // Funcao: tab // // Descricao: Rotina para simplificar os espacos antes de uma // // linha // // Parametros: - // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void tab(void) { printf(" "); } ///////////////////////////////////////////////////////////////////// // Funcao: titulo // // Descricao: Mostra o titulo do sistema na tela // // Parametros: - // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void titulo() { setcolor( XFOREGROUND_WHITE | XBACKGROUND_DARKGRAY ); janela(5,1,69,3); setcolor( XFOREGROUND_YELLOW | XBACKGROUND_DARKGRAY ); gotoxy(19,2); printf("N E U R A L L A B Y R I N T H R O B O T"); setcolor( XFOREGROUND_WHITE | XBACKGROUND_DARKGRAY ); gotoxy(10,4); printf("Copyright (c) 2002-2003 by Marvin Oliver Schneider - Freeware"); setcolor( XFOREGROUND_LIGHTGREEN | XBACKGROUND_DARKGRAY ); gotoxy(63,2); printf(" %s ",versao); gotoxy(69,2); printf("t%i",max_tabuleiros+1); cor_padrao(); } void informacoes_gerais(void) { clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," SOBRE O SISTEMA "); setcolor( XFOREGROUND_WHITE | XBACKGROUND_CYAN ); janela(2,10,74,10); gotoxy(5,11); printf("O presente sistema foi criado para demonstrar o uso de uma rede neural"); gotoxy(5,12); printf("em um robo que acha o caminho para a saida dentro de um labirinto"); gotoxy(5,13); printf("virtual."); gotoxy(5,15); printf("Ele foi desenvolvido para apresentacao no ENIA'03 (parte do congresso"); gotoxy(5,16); printf("da SBC em Campinas em 2003)."); gotoxy(5,18); printf("Sao analisados 11 labirintos por um algoritmo simbolico, que fornece"); gotoxy(5,19); printf("o resultado de seus calculos a rede neural. A rede neural e realizada"); gotoxy(5,20); printf("atraves de um Perceptron de duas camadas e aprendizado Backpropagation."); tecla(); } ///////////////////////////////////////////////////////////////////// // Funcao: init_tabuleiro // // Descricao: Inicializacao dos 11 tabuleiros // // Parametros: Identificacao do tabuleiro a ser retornado // // Retorno: Tabuleiro inicializado // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void init_todos_tabuleiros(void) { int i, j, k; // Zerar os tabuleiros a serem trabalhados inicialmente for(k=0;k<max_tabuleiros;k++) { for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { data[k].elemento[i][j]=vazio; data[k].visao[i][j]=False; } // Inicializacao do array de giros for(i=0;i<x_max*y_max;i++) { data[k].giro[i].x=dummy; data[k].giro[i].x=dummy; data[k].cam_mem.pos[i].x=dummy; data[k].cam_mem.pos[i].y=dummy; } data[k].giros_pos=0; } /* Tabuleiro Nro.: 0 0 1 2 3 4 5 6 7 +-----------------+ 0 | . . . . . . . . | 1 | . o . . . . . . | 2 | . . . . . . . . | 3 | . . . . . . . . | 4 | . . . . . . . . | 5 | . . . . . . . . | 6 | . . . . . . P . | 7 | . . . . . . . . | +-----------------+ */ data[0].numero=0; data[0].robo.x=1; data[0].robo.y=1; data[0].destino.x=6; data[0].destino.y=6; /* Tabuleiro Nro.: 1 0 1 2 3 4 5 6 7 +-----------------+ 0 | P . . . . . . . | 1 | . # . # . # . # | 2 | . . . . . . . . | 3 | . # . # . # . # | 4 | . . . . . . . . | 5 | # . # . # . # . | 6 | . . . . . . . . | 7 | # . # . # . # o | +-----------------+ */ data[1].numero=1; data[1].robo.x=7; data[1].robo.y=7; data[1].destino.x=0; data[1].destino.y=0; data[1].elemento[1][1]=obstaculo; data[1].elemento[3][1]=obstaculo; data[1].elemento[5][1]=obstaculo; data[1].elemento[7][1]=obstaculo; data[1].elemento[1][3]=obstaculo; data[1].elemento[3][3]=obstaculo; data[1].elemento[5][3]=obstaculo; data[1].elemento[7][3]=obstaculo; data[1].elemento[0][5]=obstaculo; data[1].elemento[2][5]=obstaculo; data[1].elemento[4][5]=obstaculo; data[1].elemento[6][5]=obstaculo; data[1].elemento[0][7]=obstaculo; data[1].elemento[2][7]=obstaculo; data[1].elemento[4][7]=obstaculo; data[1].elemento[6][7]=obstaculo; /* Tabuleiro Nro.: 2 0 1 2 3 4 5 6 7 +-----------------+ 0 | . . . # P . . . | 1 | . . . # . . . . | 2 | . . . # . . . . | 3 | . . . # . . . . | 4 | . . . . . . . . | 5 | . . . . # . . . | 6 | . o . . # . . . | 7 | . . . . # . . . | +-----------------+ */ data[2].numero=2; data[2].robo.x=1; data[2].robo.y=6; data[2].destino.x=4; data[2].destino.y=0; data[2].elemento[3][0]=obstaculo; data[2].elemento[3][1]=obstaculo; data[2].elemento[3][2]=obstaculo; data[2].elemento[3][3]=obstaculo; data[2].elemento[4][5]=obstaculo; data[2].elemento[4][6]=obstaculo; data[2].elemento[4][7]=obstaculo; /* Tabuleiro Nro.: 3 0 1 2 3 4 5 6 7 +-----------------+ 0 | . . # . . . . . | 1 | . . # . # . . . | 2 | . . # . . . . . | 3 | . . # P # . . . | 4 | . . # # # # . . | 5 | . . . # . . . . | 6 | . # . # . . # # | 7 | o # . . . . . . | +-----------------+ */ data[3].numero=3; data[3].robo.x=0; data[3].robo.y=7; data[3].destino.x=3; data[3].destino.y=3; data[3].elemento[2][0]=obstaculo; data[3].elemento[2][1]=obstaculo; data[3].elemento[2][2]=obstaculo; data[3].elemento[2][3]=obstaculo; data[3].elemento[2][4]=obstaculo; data[3].elemento[3][4]=obstaculo; data[3].elemento[4][1]=obstaculo; data[3].elemento[4][3]=obstaculo; data[3].elemento[4][4]=obstaculo; data[3].elemento[3][5]=obstaculo; data[3].elemento[3][6]=obstaculo; data[3].elemento[1][6]=obstaculo; data[3].elemento[1][7]=obstaculo; data[3].elemento[6][6]=obstaculo; data[3].elemento[7][6]=obstaculo; data[3].elemento[5][4]=obstaculo; /* Tabuleiro Nro.: 4 0 1 2 3 4 5 6 7 +-----------------+ 0 | o # . # . # . . | 1 | . # . . . . . . | 2 | . # . # # . # # | 3 | . # . # . . . . | 4 | . . . # . # # . | 5 | . # . # . # . . | 6 | . # . . . # . # | 7 | . . . # . # . P | +-----------------+ */ data[4].numero=4; data[4].robo.x=0; data[4].robo.y=0; data[4].destino.x=7; data[4].destino.y=7; data[4].elemento[1][0]=obstaculo; data[4].elemento[1][1]=obstaculo; data[4].elemento[1][2]=obstaculo; data[4].elemento[1][3]=obstaculo; data[4].elemento[1][5]=obstaculo; data[4].elemento[3][0]=obstaculo; data[4].elemento[3][2]=obstaculo; data[4].elemento[3][3]=obstaculo; data[4].elemento[3][4]=obstaculo; data[4].elemento[3][5]=obstaculo; data[4].elemento[4][2]=obstaculo; data[4].elemento[5][4]=obstaculo; data[4].elemento[1][6]=obstaculo; data[4].elemento[3][7]=obstaculo; data[4].elemento[5][0]=obstaculo; data[4].elemento[5][5]=obstaculo; data[4].elemento[5][6]=obstaculo; data[4].elemento[5][7]=obstaculo; data[4].elemento[6][2]=obstaculo; data[4].elemento[6][4]=obstaculo; data[4].elemento[7][2]=obstaculo; data[4].elemento[7][6]=obstaculo; /* Tabuleiro Nro.: 5 0 1 2 3 4 5 6 7 +-----------------+ 0 | . # . # . . . . | 1 | . . . o # . . . | 2 | . # . # . . . . | 3 | . . # . . . . . | 4 | . # . # . . . . | 5 | . . . . # . . . | 6 | . . . . . . # . | 7 | . . . . # . . P | +-----------------+ */ data[5].numero=5; data[5].robo.x=3; data[5].robo.y=1; data[5].destino.x=7; data[5].destino.y=7; data[5].elemento[1][0]=obstaculo; data[5].elemento[1][2]=obstaculo; data[5].elemento[1][4]=obstaculo; data[5].elemento[2][3]=obstaculo; data[5].elemento[3][0]=obstaculo; data[5].elemento[3][2]=obstaculo; data[5].elemento[3][4]=obstaculo; data[5].elemento[4][1]=obstaculo; data[5].elemento[4][5]=obstaculo; data[5].elemento[4][7]=obstaculo; data[5].elemento[6][6]=obstaculo; /* Tabuleiro Nro.: 6 0 1 2 3 4 5 6 7 +-----------------+ 0 | . . . . . . . . | 1 | . . . . . . . . | 2 | # # . # . # . . | 3 | o . . . . . . . | 4 | # # # # # . # # | 5 | . . . P # . . . | 6 | . . . . . . # . | 7 | . . . . # . . . | +-----------------+ */ data[6].numero=6; data[6].robo.x=0; data[6].robo.y=3; data[6].destino.x=3; data[6].destino.y=5; data[6].elemento[0][2]=obstaculo; data[6].elemento[1][2]=obstaculo; data[6].elemento[3][2]=obstaculo; data[6].elemento[5][2]=obstaculo; data[6].elemento[0][4]=obstaculo; data[6].elemento[1][4]=obstaculo; data[6].elemento[2][4]=obstaculo; data[6].elemento[3][4]=obstaculo; data[6].elemento[4][4]=obstaculo; data[6].elemento[4][5]=obstaculo; data[6].elemento[6][4]=obstaculo; data[6].elemento[7][4]=obstaculo; data[6].elemento[4][7]=obstaculo; data[6].elemento[6][6]=obstaculo; /* Tabuleiro Nro.: 7 0 1 2 3 4 5 6 7 +-----------------+ 0 | # . # . # . # . | 1 | # . # . # . # . | 2 | # . . . . . . . | 3 | . . . # . # . . | 4 | . # . # . # . . | 5 | . # . # . # # # | 6 | . # . . . . . . | 7 | o # . # # # P . | +-----------------+ */ data[7].numero=7; data[7].robo.x=0; data[7].robo.y=7; data[7].destino.x=6; data[7].destino.y=7; data[7].elemento[0][0]=obstaculo; data[7].elemento[0][1]=obstaculo; data[7].elemento[0][2]=obstaculo; data[7].elemento[1][4]=obstaculo; data[7].elemento[1][5]=obstaculo; data[7].elemento[2][0]=obstaculo; data[7].elemento[2][1]=obstaculo; data[7].elemento[3][3]=obstaculo; data[7].elemento[3][4]=obstaculo; data[7].elemento[3][5]=obstaculo; data[7].elemento[4][0]=obstaculo; data[7].elemento[4][1]=obstaculo; data[7].elemento[5][3]=obstaculo; data[7].elemento[5][4]=obstaculo; data[7].elemento[5][5]=obstaculo; data[7].elemento[1][6]=obstaculo; data[7].elemento[1][7]=obstaculo; data[7].elemento[3][7]=obstaculo; data[7].elemento[4][7]=obstaculo; data[7].elemento[5][7]=obstaculo; data[7].elemento[6][0]=obstaculo; data[7].elemento[6][1]=obstaculo; data[7].elemento[6][5]=obstaculo; data[7].elemento[7][5]=obstaculo; /* Tabuleiro Nro.: 8 0 1 2 3 4 5 +-------------+ 0 | x x x x x x | 1 | x . . . P x | 2 | x . x x . x | 3 | x . x x . x | 4 | x o . . . x | 5 | x x x x x x | +-------------+ */ /* Tabuleiro Nro.: . 0 1 2 3 4 5 6 7 +-----------------+ 0 | x x x x x x . . | 1 | x o . . . x . . | 2 | x . x x . x . . | 3 | x . x x . x . # | 4 | x . . . . . . # | 5 | x x x x x x . # | 6 | . . . . . . . # | 7 | P # . . . . . # | +-----------------+ */ data[8].numero=8; data[8].robo.x=1; data[8].robo.y=1; data[8].destino.x=0; data[8].destino.y=7; data[8].elemento[0][0]=obstaculo; data[8].elemento[0][1]=obstaculo; data[8].elemento[0][2]=obstaculo; data[8].elemento[0][3]=obstaculo; data[8].elemento[0][4]=obstaculo; data[8].elemento[0][5]=obstaculo; data[8].elemento[5][0]=obstaculo; data[8].elemento[5][1]=obstaculo; data[8].elemento[5][2]=obstaculo; data[8].elemento[5][3]=obstaculo; data[8].elemento[5][5]=obstaculo; data[8].elemento[1][0]=obstaculo; data[8].elemento[2][0]=obstaculo; data[8].elemento[3][0]=obstaculo; data[8].elemento[4][0]=obstaculo; data[8].elemento[1][5]=obstaculo; data[8].elemento[2][5]=obstaculo; data[8].elemento[3][5]=obstaculo; data[8].elemento[4][5]=obstaculo; data[8].elemento[2][2]=obstaculo; data[8].elemento[2][3]=obstaculo; data[8].elemento[3][2]=obstaculo; data[8].elemento[3][3]=obstaculo; data[8].elemento[7][3]=obstaculo; data[8].elemento[7][4]=obstaculo; data[8].elemento[7][5]=obstaculo; data[8].elemento[7][6]=obstaculo; data[8].elemento[7][7]=obstaculo; data[8].elemento[1][7]=obstaculo; /* Tabuleiro Nro.: 9 0 1 2 3 4 5 6 7 +-----------------+ 0 | o # # # # # # P | 1 | . # . . # . # . | 2 | . . . # . . . . | 3 | . # . # # . . . | 4 | . # . # # . . . | 5 | . . . . # . . . | 6 | . . . . # . . . | 7 | . . . . . . . . | +-----------------+ */ data[9].numero=9; data[9].robo.x=0; data[9].robo.y=0; data[9].destino.x=7; data[9].destino.y=0; data[9].elemento[1][0]=obstaculo; data[9].elemento[2][0]=obstaculo; data[9].elemento[3][0]=obstaculo; data[9].elemento[4][0]=obstaculo; data[9].elemento[1][1]=obstaculo; data[9].elemento[1][3]=obstaculo; data[9].elemento[1][4]=obstaculo; data[9].elemento[3][2]=obstaculo; data[9].elemento[3][3]=obstaculo; data[9].elemento[3][4]=obstaculo; data[9].elemento[4][1]=obstaculo; data[9].elemento[4][3]=obstaculo; data[9].elemento[4][4]=obstaculo; data[9].elemento[5][0]=obstaculo; data[9].elemento[6][0]=obstaculo; data[9].elemento[6][1]=obstaculo; data[9].elemento[4][5]=obstaculo; data[9].elemento[4][6]=obstaculo; /* Tabuleiro Nro.: 10 0 1 2 3 4 5 6 7 +-----------------+ 0 | o # # # # # # P | 1 | . # . . # . # . | 2 | . . . # . . . . | 3 | . # . # # . . . | 4 | . # . # # . . . | 5 | . . . . # . . . | 6 | . . . . # . . # | 7 | . . . . . . . . | +-----------------+ */ data[10].numero=10; data[10].robo.x=0; data[10].robo.y=0; data[10].destino.x=7; data[10].destino.y=0; data[10].elemento[1][0]=obstaculo; data[10].elemento[2][0]=obstaculo; data[10].elemento[3][0]=obstaculo; data[10].elemento[4][0]=obstaculo; data[10].elemento[1][1]=obstaculo; data[10].elemento[1][3]=obstaculo; data[10].elemento[1][4]=obstaculo; data[10].elemento[3][2]=obstaculo; data[10].elemento[3][3]=obstaculo; data[10].elemento[3][4]=obstaculo; data[10].elemento[4][1]=obstaculo; data[10].elemento[4][3]=obstaculo; data[10].elemento[4][4]=obstaculo; data[10].elemento[5][0]=obstaculo; data[10].elemento[6][0]=obstaculo; data[10].elemento[6][1]=obstaculo; data[10].elemento[4][5]=obstaculo; data[10].elemento[4][6]=obstaculo; data[10].elemento[7][6]=obstaculo; /* Tabuleiro Nro.: 11 0 1 2 3 4 5 6 7 +-----------------+ 0 | o # # # # # # P | 1 | . # . . # . # # | 2 | . . . # . . . . | 3 | . # . # # . . . | 4 | . # . # # . . . | 5 | . . . . # . . . | 6 | . . . . # . . . | 7 | . . . . . . . . | +-----------------+ */ data[11].numero=11; data[11].robo.x=0; data[11].robo.y=0; data[11].destino.x=7; data[11].destino.y=0; data[11].elemento[1][0]=obstaculo; data[11].elemento[2][0]=obstaculo; data[11].elemento[3][0]=obstaculo; data[11].elemento[4][0]=obstaculo; data[11].elemento[1][1]=obstaculo; data[11].elemento[1][3]=obstaculo; data[11].elemento[1][4]=obstaculo; data[11].elemento[3][2]=obstaculo; data[11].elemento[3][3]=obstaculo; data[11].elemento[3][4]=obstaculo; data[11].elemento[4][1]=obstaculo; data[11].elemento[4][3]=obstaculo; data[11].elemento[4][4]=obstaculo; data[11].elemento[5][0]=obstaculo; data[11].elemento[6][0]=obstaculo; data[11].elemento[6][1]=obstaculo; data[11].elemento[4][5]=obstaculo; data[11].elemento[4][6]=obstaculo; data[11].elemento[7][1]=obstaculo; } TABULEIRO init_tabuleiro(int id) { TABULEIRO tabuleiro_local; tabuleiro_local=data[id]; return tabuleiro_local; } ///////////////////////////////////////////////////////////////////// // Funcao: init_caminho // // Descricao: Inicializa um caminho com valores "dummy" // // Parametros: - // // Retorno: Caminho inicializado // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// CAMINHO init_caminho(void) { int i; CAMINHO caminho_local; for(i=0;i<caminhos_max;i++) { caminho_local.pos[i].x=dummy; caminho_local.pos[i].y=dummy; } return caminho_local; } ///////////////////////////////////////////////////////////////////// // Funcao: mostra_tabuleiro // // Descricao: Mostra o tabuleiro na tela // // Parametros: Tabuleiro a ser mostrado, Definicao se visao atual // // do robo e os giros achados devem ser mostrados // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void mostra_tabuleiro(TABULEIRO tabuleiro_local, BOOL visao, BOOL giros) { int i, j; setcolor(XFOREGROUND_WHITE | XBACKGROUND_BLACK); janela(x_start,y_start,x_max*2,y_max); gotoxy(x_start+2,y_start); printf(" %i ",tabuleiro_local.numero); for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { gotoxy(x_start+(i*2)+1,y_start+j+1); if(tabuleiro_local.elemento[i][j]==obstaculo) { if(visao && tabuleiro_local.visao[i][j]) cor_visao(obstaculo); else setcolor(XFOREGROUND_LIGHTRED | XBACKGROUND_BLACK); printf("%c%c",obstaculo_ch,obstaculo_ch); } else if(visao && tabuleiro_local.visao[i][j]) { cor_visao(vazio); printf(" "); } } setcolor( XFOREGROUND_LIGHTGRAY | XBACKGROUND_BLUE ); gotoxy(6,11); printf("( DEBUG INFO"); gotoxy(6,13); printf("Visao......: %i ",gera_codigo_visao(tabuleiro_local)); gotoxy(6,14); printf("Obstaculos.: %i ) ",gera_codigo_obstaculos(tabuleiro_local)); if(giros) { setcolor(XFOREGROUND_YELLOW | XBACKGROUND_BLACK); for(i=0;i<x_max*y_max;i++) { if(tabuleiro_local.giro[i].x!=dummy) { gotoxy(x_start+tabuleiro_local.giro[i].x*2+1,y_start+tabuleiro_local.giro[i].y+1); printf("%i%c",i,down_ch); } } // gotoxy(1,16); // for(i=0;i<x_max*y_max;i++) // { // if(tabuleiro_local.giro[i].x!=dummy) // { // printf("%i:%i,%i; ",i,tabuleiro_local.giro[i].x,tabuleiro_local.giro[i].y); // } // } } if(visao) cor_visao(robo); else setcolor(XFOREGROUND_LIGHTBLUE | XBACKGROUND_BLACK); gotoxy(x_start+(tabuleiro_local.robo.x)*2+1,y_start+tabuleiro_local.robo.y+1); printf("%s",robo_ch); if(visao && tabuleiro_local.visao[tabuleiro_local.destino.x][tabuleiro_local.destino.y]) cor_visao(destino); else setcolor(XFOREGROUND_LIGHTGREEN | XBACKGROUND_BLACK); gotoxy(x_start+(tabuleiro_local.destino.x)*2+1,y_start+tabuleiro_local.destino.y+1); if(tabuleiro_local.destino.x==tabuleiro_local.robo.x && tabuleiro_local.destino.y==tabuleiro_local.robo.y) printf("OK"); else printf("%s",destino_ch); cor_padrao(); gotoxy(x_start+1,y_start-1); for(i=0;i<x_max;i++) printf("%i ",i); for(i=0;i<y_max;i++) { gotoxy(x_start-2,y_start+1+i); printf("%i",i); } } ///////////////////////////////////////////////////////////////////// // Funcao: estabelece_visao // // Descricao: Rotina para definir as possibilidades de visao do // // robo em uma determinada situacao no tabuleiro // // Parametros: Tabuleiro para estabelecer a visao // // Retorno: Tabuleiro com visualizacao da visao // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// TABULEIRO estabelece_visao(TABULEIRO tabuleiro_local) { int i, j, limite_x_cima_dir, limite_x_cima_esq, limite_x_baixo_dir, limite_x_baixo_esq; tabuleiro_local.visao[tabuleiro_local.robo.x][tabuleiro_local.robo.y]=True; // visao para cima if(tabuleiro_local.robo.y>-1) { i=tabuleiro_local.robo.y; limite_x_cima_dir=x_max; limite_x_cima_esq=-1; do { if(tabuleiro_local.elemento[tabuleiro_local.robo.x][i]!=obstaculo) { tabuleiro_local.visao[tabuleiro_local.robo.x][i]=True; j=tabuleiro_local.robo.x; if(j>limite_x_cima_esq) { while(j>limite_x_cima_esq && tabuleiro_local.elemento[j][i]!=obstaculo) { tabuleiro_local.visao[j][i]=True; j--; } } limite_x_cima_esq=j; j=tabuleiro_local.robo.x; if(j<limite_x_cima_dir) { while(j<limite_x_cima_dir && tabuleiro_local.elemento[j][i]!=obstaculo) { tabuleiro_local.visao[j][i]=True; j++; } } limite_x_cima_dir=j; } i--; } while(i>-1 && tabuleiro_local.elemento[tabuleiro_local.robo.x][i]!=obstaculo); } // visao para baixo if(tabuleiro_local.robo.y<y_max) { i=tabuleiro_local.robo.y; limite_x_baixo_dir=x_max; limite_x_baixo_esq=-1; do { if(tabuleiro_local.elemento[tabuleiro_local.robo.x][i]!=obstaculo) { tabuleiro_local.visao[tabuleiro_local.robo.x][i]=True; j=tabuleiro_local.robo.x; if(j>limite_x_baixo_esq) { while(j>limite_x_baixo_esq && tabuleiro_local.elemento[j][i]!=obstaculo) { tabuleiro_local.visao[j][i]=True; j--; } } limite_x_baixo_esq=j; j=tabuleiro_local.robo.x; if(j<limite_x_baixo_dir) { while(j<limite_x_baixo_dir && tabuleiro_local.elemento[j][i]!=obstaculo) { tabuleiro_local.visao[j][i]=True; j++; } } limite_x_baixo_dir=j; } i++; } while(i<y_max && tabuleiro_local.elemento[tabuleiro_local.robo.x][i]!=obstaculo); } return tabuleiro_local; } ///////////////////////////////////////////////////////////////////// // Funcao: estabelece_giros // // Descricao: Rotina que determina local e numero de giros a // // partir de uma determinada situacao // // Parametros: Tabuleiro para definicao dos giros // // Retorno: Tabuleiro com pontos de giro definidos // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// TABULEIRO estabelece_giros(TABULEIRO tabuleiro_local) { int i, j; BOOL ja_marcado; for(i=0;i<x_max*y_max;i++) { tabuleiro_local.giro[i].x=dummy; tabuleiro_local.giro[i].x=dummy; } tabuleiro_local.giros_pos=0; for (i=0;i<x_max;i++) for (j=0;j<y_max;j++) { if(tabuleiro_local.visao[i][j]) { ja_marcado=False; if(i>0) if(tabuleiro_local.elemento[i-1][j]==vazio && tabuleiro_local.visao[i-1][j]==False) { tabuleiro_local.giro[tabuleiro_local.giros_pos].x=i; tabuleiro_local.giro[tabuleiro_local.giros_pos].y=j; tabuleiro_local.giros_pos++; ja_marcado=True; } if(i<x_max-1 && ja_marcado==False) if(tabuleiro_local.elemento[i+1][j]==vazio && tabuleiro_local.visao[i+1][j]==False) { tabuleiro_local.giro[tabuleiro_local.giros_pos].x=i; tabuleiro_local.giro[tabuleiro_local.giros_pos].y=j; tabuleiro_local.giros_pos++; ja_marcado=True; } if(j>0 && ja_marcado==False) if(tabuleiro_local.elemento[i][j-1]== vazio && tabuleiro_local.visao[i][j-1]==False) { tabuleiro_local.giro[tabuleiro_local.giros_pos].x=i; tabuleiro_local.giro[tabuleiro_local.giros_pos].y=j; tabuleiro_local.giros_pos++; ja_marcado=True; } if(j<y_max-1 && ja_marcado==False) if(tabuleiro_local.elemento[i][j+1]==vazio && tabuleiro_local.visao[i][j+1]==False) { tabuleiro_local.giro[tabuleiro_local.giros_pos].x=i; tabuleiro_local.giro[tabuleiro_local.giros_pos].y=j; tabuleiro_local.giros_pos++; } } } return tabuleiro_local; } int gera_codigo_visao(TABULEIRO tabuleiro_local) { int i, j, k, codigo; codigo=0; k=1; for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { if(tabuleiro_local.visao[i][j])//tabuleiro_local.elemento[i][j]==obstaculo) codigo=codigo+k; k++; } codigo=(int((k*tan(codigo)))); if(codigo>0) while(codigo>64) codigo=codigo-64; if(codigo<0) while(codigo<-64) codigo=codigo+64; return codigo; } int gera_codigo_obstaculos(TABULEIRO tabuleiro_local) { int i, j, k, codigo; BOOL adicionar_obstaculo; codigo=0; k=1; for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { adicionar_obstaculo=False; if(tabuleiro_local.elemento[i][j]==obstaculo) { if(i>0) if(tabuleiro_local.visao[i-1][j]==True) adicionar_obstaculo=True; if(i<x_max-1) if(tabuleiro_local.visao[i+1][j]==True) adicionar_obstaculo=True; if(j>0) if(tabuleiro_local.visao[i][j-1]==True) adicionar_obstaculo=True; if(j<y_max-1) if(tabuleiro_local.visao[i][j+1]==True) adicionar_obstaculo=True; } if(adicionar_obstaculo==True) codigo++; k++; } //gotoxy(1,2); //printf("obstaculos: %i",codigo); codigo=(int((k*tan(codigo)))); if(codigo>0) while(codigo>64) codigo=codigo-64; if(codigo<0) while(codigo<-64) codigo=codigo+64; return codigo; } ///////////////////////////////////////////////////////////////////// // Funcao: anti_loop // // Descricao: Rotina para eliminacao de "loops" nos caminhos // // achados que fatalmente resultariam em "stack // // overflow", demora e caminhos ineficientes // // Parametros: Posicao a ser analisada e caminho a ser comparado // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// BOOL anti_loop(XY test_pos, CAMINHO cam_local) { int c; BOOL flag; flag=False; for(c=0;c<(x_max*y_max);c++) { if(test_pos.x==cam_local.pos[c].x && test_pos.y==cam_local.pos[c].y) flag=True; } return flag; } ///////////////////////////////////////////////////////////////////// // Funcao: conta_elementos // // Descricao: Conta os pontos dentro de um caminho // // Parametros: Caminho a ser analisado // // Retorno: Numero de elementos // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// int conta_elementos(CAMINHO cam_local) { int flag; flag=0; if(cam_local.pos[0].x==dummy) return 999; // para nao retornar 0 e provocar que o algoritmo pense // que seja o menor caminho!!! while(cam_local.pos[flag].x!=dummy) flag++; return flag; } ///////////////////////////////////////////////////////////////////// // Funcao: calcula distancia // // Descricao: Calcula a distancia total percorrida em um // // determinado caminho (levando em consideracao que // // o robo nao se movimentara diagonalmente) // // Parametros: Caminho a ser analisado // // Retorno: Distancia em numero de casas percorridas // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// int calcula_distancia(CAMINHO cam_local) { int flag, m; flag=0; if(cam_local.pos[0].x==dummy || cam_local.pos[1].x==dummy) return 0; m=1; while(cam_local.pos[m].x!=dummy && m<x_max*y_max) { flag=flag+abs(cam_local.pos[m].x-cam_local.pos[m-1].x); flag=flag+abs(cam_local.pos[m].y-cam_local.pos[m-1].y); m++; } return flag; } ///////////////////////////////////////////////////////////////////// // Funcao: algoritmo_simbolico // // Descricao: Gerenciador recursivo do algoritmo simbolico // // (abre um diagrama de arvore) // // Parametros: Proxima posicao do caminho, tabuleiro e caminho // // atual // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// CAMINHO algoritmo_simbolico(XY nova_pos, TABULEIRO tab_local, CAMINHO rota) { int a, b; tab_local.robo.x=nova_pos.x; tab_local.robo.y=nova_pos.y; b=0; while(tab_local.cam_mem.pos[b].x!=dummy) b++; tab_local.cam_mem.pos[b].x=nova_pos.x; tab_local.cam_mem.pos[b].y=nova_pos.y; tab_local=estabelece_visao(tab_local); tab_local=estabelece_giros(tab_local); // if(debug) // mostra_tabuleiro(tab_local,True,True); // debug if(tab_local.visao[tab_local.destino.x][tab_local.destino.y]==False && conta_elementos(tab_local.cam_mem)<conta_elementos(rota)) // destino nao foi achado ainda!! { a=0; while(tab_local.giro[a].x!=dummy) { if(anti_loop(tab_local.giro[a],tab_local.cam_mem)==False) rota=algoritmo_simbolico(tab_local.giro[a],tab_local,rota); a++; } } else { b++; tab_local.cam_mem.pos[b].x=tab_local.destino.x; tab_local.cam_mem.pos[b].y=tab_local.destino.y; if((conta_elementos(tab_local.cam_mem)<conta_elementos(rota)) ||(conta_elementos(tab_local.cam_mem)==conta_elementos(rota) && calcula_distancia(tab_local.cam_mem)<calcula_distancia(rota))) { rota=tab_local.cam_mem; // if(debug) // output debug // { // gotoxy(1,21); // d=0; // printf("Caminho: "); // while(rota.pos[d].x!=dummy) // { // printf(" %i,%i -",rota.pos[d].x,rota.pos[d].y); // d++; // } // printf(" .. pos:%i dist:%i",conta_elementos(rota),calcula_distancia(rota)); // getch(); // } } } return rota; } void execute_caminho(TABULEIRO tabuleiro_local2, CAMINHO caminho_exec, BOOL esc_vis, BOOL esc_gir) { int p; p=0; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," ALGORITMO SIMBOLICO "); caixa_mensagem(simples,0,11,"Processando...."); while(caminho_exec.pos[p].x!=dummy) { tabuleiro_local2.robo.x=caminho_exec.pos[p].x; tabuleiro_local2.robo.y=caminho_exec.pos[p].y; tabuleiro_local2=estabelece_visao(tabuleiro_local2); tabuleiro_local2=estabelece_giros(tabuleiro_local2); mostra_tabuleiro(tabuleiro_local2,esc_vis,esc_gir); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," ALGORITMO SIMBOLICO "); caixa_mensagem(chave,0,11," Processando.. "); p++; } } MAPA init_mapa(void) { MAPA mapa_local2; int i2, j2; for(i2=0;i2<x_max;i2++) for(j2=0;j2<y_max;j2++) mapa_local2.preferencia[i2][j2]=0.0; return mapa_local2; } void aprende_caminho(TABULEIRO tabuleiro_local2, CAMINHO caminho_exec) { int p, p2, acertos; MAPA mapa_local; SAIDA saida_local; float maior_valor; int maior_ponto; XY maior_pos; p=0; acertos=0; while(caminho_exec.pos[p+1].x!=dummy && (caminho_exec.pos[p+1].x!=tabuleiro_local2.destino.x || caminho_exec.pos[p+1].y!=tabuleiro_local2.destino.y)) { tabuleiro_local2.robo.x=caminho_exec.pos[p].x; tabuleiro_local2.robo.y=caminho_exec.pos[p].y; tabuleiro_local2=estabelece_visao(tabuleiro_local2); tabuleiro_local2=estabelece_giros(tabuleiro_local2); //mostra_tabuleiro(tabuleiro_local2,True,True); //getch(); rede=feedforward(tabuleiro_local2,rede); saida_local=extrai_saidas(rede); mapa_local=cria_mapa_das_saidas(saida_local); p2=1; maior_pos.x=tabuleiro_local2.giro[0].x; maior_pos.y=tabuleiro_local2.giro[0].y; maior_valor=mapa_local.preferencia[tabuleiro_local2.giro[0].x][tabuleiro_local2.giro[0].y]; //printf("\n\nPONTOS DE GIROS\n"); //printf("pos:%i\n\n",tabuleiro_local2.giros_pos); //printf("%i,%i - %f\n",tabuleiro_local2.giro[0].x,maior_pos.y=tabuleiro_local2.giro[0].y, // mapa_local.preferencia[tabuleiro_local2.giro[0].x][tabuleiro_local2.giro[0].y]); while(p2<tabuleiro_local2.giros_pos) { if(mapa_local.preferencia[tabuleiro_local2.giro[p2].x][tabuleiro_local2.giro[p2].y]>maior_valor) { maior_pos.x=tabuleiro_local2.giro[p2].x; maior_pos.y=tabuleiro_local2.giro[p2].y; maior_valor=mapa_local.preferencia[tabuleiro_local2.giro[p2].x][tabuleiro_local2.giro[p2].y]; maior_ponto=p2; // printf("%i,%i - %f\n",tabuleiro_local2.giro[p2].x,maior_pos.y=tabuleiro_local2.giro[p2].y, // mapa_local.preferencia[tabuleiro_local2.giro[p2].x][tabuleiro_local2.giro[p2].y]); } p2++; } //printf("\n\nESCOLHIDO\n"); //printf("[%i %i %f - %i %i]\n",maior_pos.x,maior_pos.y,maior_valor,caminho_exec.pos[p+1].x,caminho_exec.pos[p+1].y); //getch(); if(maior_pos.x!=caminho_exec.pos[p+1].x || maior_pos.y!=caminho_exec.pos[p+1].y) { p2=0; while(p2<tabuleiro_local2.giros_pos) { if(p2!=maior_ponto) taxa_erro=taxa_erro+mapa_local.preferencia[tabuleiro_local2.giro[p2].x][tabuleiro_local2.giro[p2].y]; mapa_local.preferencia[tabuleiro_local2.giro[p2].x][tabuleiro_local2.giro[p2].y]=0.0; p2++; } taxa_erro=float(taxa_erro+(1.0-mapa_local.preferencia[caminho_exec.pos[p+1].x][caminho_exec.pos[p+1].y])); mapa_local.preferencia[caminho_exec.pos[p+1].x][caminho_exec.pos[p+1].y]=1.0; // mostra_mapa(mapa_local); // mostra_tabuleiro(tabuleiro_local2,True,True); saida_local=cria_saidas_do_mapa(mapa_local); // printf("learn!\n"); rede=backpropagation(rede,saida_local); } else acertos++; p++; } //printf("[ "); if(acertos<p) setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE ); else setcolor( XFOREGROUND_LIGHTGREEN | XBACKGROUND_BLUE ); printf("%c%c",s4,s4); cor_padrao(); printf(" "); printf("(%i / %i)",acertos,p); if(acertos<p) todos_ok=False; total_acertos=total_acertos+acertos; total_giros=total_giros+p; // getch(); // clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); } void use_algoritmo_simbolico(void) { TABULEIRO tabuleiro_local; CAMINHO caminho_certo; int i, escolha_processamento; BOOL escolha_visao, escolha_giros; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," ALGORITMO SIMBOLICO "); escolha_processamento=escolha(0,10,vision); switch(escolha_processamento) { case 0: escolha_visao=False; escolha_giros=False; break; case 1: escolha_visao=True; escolha_giros=False; break; case 2: escolha_visao=False; escolha_giros=True; break; case 3: escolha_visao=True; escolha_giros=True; } for(i=0;i<max_tabuleiros;i++) { caminho_certo=init_caminho(); tabuleiro_local=init_tabuleiro(i); caminho_certo=algoritmo_simbolico(tabuleiro_local.robo,tabuleiro_local,caminho_certo); if(caminho_certo.pos[0].x!=dummy) execute_caminho(tabuleiro_local,caminho_certo,escolha_visao,escolha_giros); else { clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," ALGORITMO SIMBOLICO "); mostra_tabuleiro(tabuleiro_local,escolha_visao,escolha_giros); caixa_mensagem(alerta,0,21," Nao ha caminho nesta posicao! "); } } } void use_rede_neural(void) { TABULEIRO tabuleiro_local; CAMINHO caminho_local; SAIDA saida_local; MAPA mapa_local; BOOL erro_no_processamento, escolha_visao, escolha_giros; int i, j, maior_pos, caminho_pos, escolha_processamento; float maior_valor; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," REDE NEURAL "); escolha_processamento=escolha(0,10,vision); switch(escolha_processamento) { case 0: escolha_visao=False; escolha_giros=False; break; case 1: escolha_visao=True; escolha_giros=False; break; case 2: escolha_visao=False; escolha_giros=True; break; case 3: escolha_visao=True; escolha_giros=True; } for(i=0;i<max_tabuleiros;i++) { clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," REDE NEURAL "); caminho_local=init_caminho(); tabuleiro_local=init_tabuleiro(i); caminho_pos=1; caminho_local.pos[0].x=tabuleiro_local.robo.x; caminho_local.pos[0].y=tabuleiro_local.robo.y; erro_no_processamento=False; while(tabuleiro_local.visao[tabuleiro_local.destino.x][tabuleiro_local.destino.y]==False && erro_no_processamento==False) { tabuleiro_local=estabelece_visao(tabuleiro_local); tabuleiro_local=estabelece_giros(tabuleiro_local); if(tabuleiro_local.giros_pos==0 && tabuleiro_local.visao[tabuleiro_local.destino.x][tabuleiro_local.destino.y]==False) erro_no_processamento=True; if(erro_no_processamento==False) { mostra_tabuleiro(tabuleiro_local,escolha_visao,escolha_giros); tecla(); rede=feedforward(tabuleiro_local,rede); saida_local=extrai_saidas(rede); mapa_local=cria_mapa_das_saidas(saida_local); maior_pos=0; maior_valor=mapa_local.preferencia[tabuleiro_local.giro[0].x][tabuleiro_local.giro[0].y]; if(tabuleiro_local.giros_pos>1) for(j=0;j<tabuleiro_local.giros_pos;j++) { if(mapa_local.preferencia[tabuleiro_local.giro[j].x][tabuleiro_local.giro[j].y]>maior_valor) { maior_valor=mapa_local.preferencia[tabuleiro_local.giro[j].x][tabuleiro_local.giro[j].y]; maior_pos=j; } } tabuleiro_local.robo.x=tabuleiro_local.giro[maior_pos].x; tabuleiro_local.robo.y=tabuleiro_local.giro[maior_pos].y; } } if(erro_no_processamento==False) { tabuleiro_local.robo.x=tabuleiro_local.destino.x; tabuleiro_local.robo.y=tabuleiro_local.destino.y; mostra_tabuleiro(tabuleiro_local,escolha_visao,escolha_giros); caixa_mensagem(aviso,0,21," O robo chegou ao ponto final. Labirinto resolvido com sucesso. "); } else { mostra_tabuleiro(tabuleiro_local,escolha_visao,escolha_giros); caixa_mensagem(alerta,0,21," Sem caminho ate o destino. A rede nao pode resolver esta situacao. "); } } } void aprende_caminhos(void) { TABULEIRO tabuleiro_local; int i, iteracao, progresso_pos; float percentagem; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); cor_padrao(); titulo(); caixa_mensagem(simples,0,6," APRENDIZADO DOS CAMINHOS "); gotoxy(2,10); caixa_mensagem(chave,0,10," Elaborando caminhos com algoritmo simbolico... "); progresso_pos=(80-(max_tabuleiros*2))/2; gotoxy(progresso_pos,14); for(i=0;i<max_tabuleiros;i++) printf("%c%c",s1,s1); gotoxy(progresso_pos,14); for(i=0;i<max_tabuleiros;i++) { cache.cam[i]=init_caminho(); tabuleiro_local=init_tabuleiro(i); cache.cam[i]=algoritmo_simbolico(tabuleiro_local.robo,tabuleiro_local,cache.cam[i]); printf("%c%c",s4,s4); } clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); cor_padrao(); titulo(); caixa_mensagem(simples,0,6," APRENDIZADO DOS CAMINHOS - MONITORAMENTO "); iteracao=0; todos_ok=False; //gotoxy(28,7); //printf("------------------------"); cor_padrao(); gotoxy(40,10); printf("Iteracao atual : _"); gotoxy(40,12); printf("Total acertos : ___"); percentagem=float(total_acertos*100.0/total_giros*1.0); gotoxy(40,14); printf("Percentagem : _______"); gotoxy(40,16); printf("Erro total : _______"); gotoxy(40,18); printf("Erro relativo : _______"); for(i=0;i<max_tabuleiros;i++) { gotoxy(10,10+i); if(i<10) printf("0"); printf("%i : __ _______",i); } caixa_mensagem(chave,0,22," Processando. Interromper com qualquer tecla. "); while(kbhit()) getch(); while(!kbhit() && todos_ok==False) { gotoxy(40,10); printf("Iteracao atual : %i\n\n",iteracao+1); todos_ok=True; total_giros=0; total_acertos=0; taxa_erro=0.0; for(i=0;i<max_tabuleiros;i++) { // caminho_certo=init_caminho(); tabuleiro_local=init_tabuleiro(i); // caminho_certo=algoritmo_simbolico(tabuleiro_local.robo,tabuleiro_local,caminho_certo); gotoxy(15,10+i); if(cache.cam[i].pos[0].x!=dummy) aprende_caminho(tabuleiro_local,cache.cam[i]); else { setcolor( XFOREGROUND_LIGHTBLUE | XBACKGROUND_BLUE ); printf("%c%c",s4,s4); printf(" (sem solucao)"); cor_padrao(); } } gotoxy(40,12); printf("Total acertos : %i / %i",total_acertos,total_giros); percentagem=float(total_acertos*100.0/total_giros*1.0); gotoxy(40,14); printf("Percentagem : "); if(percentagem<70.0) setcolor( XFOREGROUND_WHITE | XBACKGROUND_RED ); else if(percentagem<90.0) setcolor( XFOREGROUND_WHITE | XBACKGROUND_LIGHTBLUE ); else setcolor( XFOREGROUND_WHITE | XBACKGROUND_GREEN ); printf("%f",percentagem); cor_padrao(); gotoxy(40,16); printf("Erro total : "); //setcolor( XFOREGROUND_LIGHTPURPLE | XBACKGROUND_BLUE ); printf("%f ",taxa_erro); cor_padrao(); gotoxy(40,18); printf("Erro relativo : "); //setcolor( XFOREGROUND_LIGHTPURPLE | XBACKGROUND_BLUE ); printf("%f ",taxa_erro/total_giros*1.0); cor_padrao(); iteracao++; } while(kbhit()) getch(); if(todos_ok==True) caixa_mensagem(aviso,0,21," Finalizado (todos os caminhos aprendidos com sucesso)!! "); else caixa_mensagem(alerta,0,21," Aprendizado interrompido (os dados atuais serao mantidos). "); } ///////////////////////////////////////////////////////////////////// // Funcao: sigmoide // // Descricao: Funcao de ativacao dos neuronios da rede // // Parametros: Valor base para qual devera ser calculado o // // sigmoide // // Retorno: Sigmoide do valor base // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// float sigmoide(float valor) { valor=float(1.0/(1.0+exp(-valor))); // sigmoide:=1.0/(1.0+EXP(-soma)); return valor; } ///////////////////////////////////////////////////////////////////// // Funcao: init_rede // // Descricao: Inicializacao da rede neural // // Parametros: - // // Retorno: Rede inicializada // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// REDE_NEURAL init_rede(void) { REDE_NEURAL rede_local; int i, j; for(i=0;i<nr_entradas;i++) // inicializa entradas com 0 rede_local.entrada[i]=0; for(i=0;i<nr_escondidos;i++) // inicializa neuronios escondidos com 0 rede_local.escondido[i]=0; for(i=0;i<nr_saidas;i++) // inicializa saidas com 0 rede_local.saida[i]=0; for(i=0;i<nr_entradas;i++) // inicializa sinapses 1: valores de -0.1 a 0.1 for(j=0;j<nr_escondidos;j++) rede_local.sinapse1[i][j]=float(rand()/(RAND_MAX*5.0)-0.1); for(i=0;i<nr_escondidos;i++) // sinapses 2, dto. sinapses 1 for(j=0;j<nr_saidas;j++) rede_local.sinapse2[i][j]=float(rand()/(RAND_MAX*5.0)-0.1); return rede_local; } ///////////////////////////////////////////////////////////////////// // Funcao: dump_rede // // Descricao: Simples dump dos valores da rede para debug // // Parametros: Rede neural // // Retorno: - // // Versao: 0.2 (interface melhorada) // // Observacoes: - // ///////////////////////////////////////////////////////////////////// void dump_rede(REDE_NEURAL rede_local, BOOL apenas_entradas) { int i, j, k; cor_padrao(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - ENTRADAS "); gotoxy(16,10); for(i=0;i<nr_entradas;i++) { if(i%2==0) setcolor( XFOREGROUND_LIGHTGREEN | XBACKGROUND_BLUE); else setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE); printf("%i ",int(rede_local.entrada[i])); if((i+1)%16==0) gotoxy(16,10+(i+1)/16); } cor_padrao(); printf("\n\n\n"); tecla(); if(apenas_entradas==False) { clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - SINAPSES 1A. CAMADA "); gotoxy(2,10); setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE ); printf("[POSICAO: %i / %i] ",0,nr_entradas*nr_escondidos); cor_padrao(); k=1; for(i=0;i<nr_entradas;i++) { for(j=0;j<nr_escondidos;j++) { printf("%f ",rede_local.sinapse1[i][j]); if(k%80==0) { printf("\n\n\n"); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - SINAPSES 1A. CAMADA "); gotoxy(2,10); setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE ); printf("[POSICAO: %i / %i] ",k,nr_entradas*nr_escondidos); cor_padrao(); } k++; } } printf("\n\n\n"); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - NEURONIOS ESCONDIDOS "); gotoxy(2,10); for(i=0;i<nr_escondidos;i++) printf("%f ",rede_local.escondido[i]); printf("\n\n\n"); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - SINAPSES 2A. CAMADA "); gotoxy(2,10); setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE ); printf("[POSICAO: %i / %i] ",0,nr_escondidos*nr_saidas); cor_padrao(); k=1; for(i=0;i<nr_escondidos;i++) { for(j=0;j<nr_saidas;j++) { printf("%f ",rede_local.sinapse2[i][j]); if(k%80==0) { printf("\n\n\n"); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - SINAPSES 2A. CAMADA "); gotoxy(2,10); setcolor( XFOREGROUND_LIGHTRED | XBACKGROUND_BLUE ); printf("[POSICAO: %i / %i] ",k,nr_escondidos*nr_saidas); cor_padrao(); } k++; } } printf("\n\n\n"); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," DUMP DA REDE - SAIDAS "); gotoxy(2,10); for(i=0;i<nr_saidas;i++) { printf("%f ",rede_local.saida[i]); if((i+1)%150==0) getch(); } tecla(); } } ///////////////////////////////////////////////////////////////////// // Funcao: feedforward // // Descricao: Processamento da rede neural // // Parametros: Tabuleiro inicial a ser analisado e a rede neural // // em "estado cru" // // Retorno: Rede neural alterada pelo processamento // // Versao: 0.1 - Versao inicial // // Observacoes: // // -Topologia escolhida: Perceptron de 2 Camadas // // // // -Aprendizado escolhido: Backpropagation // // // // -O tabuleiro e mapeado para as entradas // // -Cada elemento do tabuleiro e codificado com 3 // // entradas para observar a caracteristica binaria // // -Todas as entradas estao conectadas com todos os // // neuronios da camada escondida // // -Todos os neuronios da camada escondida estao // // conectados com todas as saidas // // -Cada elemento da camada se saida corresponde a // // uma pontuacao de preferencia de um certo ponto // // de giro // // // // -Nao toda rede sera usada para avaliacao de uma // // situacao, ela serve apenas para decidir entre // // os possiveis pontos de giro a partir de uma // // situacao no tabuleiro // // // ///////////////////////////////////////////////////////////////////// REDE_NEURAL feedforward(TABULEIRO tabuleiro_local, REDE_NEURAL rede_local) { int i, j, k, x_mem, y_mem, codigo, codigo2; k=0; // E N T R A D A codigo=gera_codigo_visao(tabuleiro_local); codigo2=gera_codigo_obstaculos(tabuleiro_local); // mostra_tabuleiro(tabuleiro_local,True,True); // gotoxy(1,2); // printf("%i",codigo2); // tecla(); for(i=0;i<nr_entradas;i++) // inicializacao para nao ficar com restos de situacoes antigas na entrada rede_local.entrada[i]=False; for(j=0;j<y_max;j++) // situacao do tabuleiro para entradas da rede for(i=0;i<x_max;i++) { if(tabuleiro_local.visao[i][j]==True) { //rede_local.entrada[k*nro_codigos+elemento_visibilidade]=True; if(tabuleiro_local.elemento[i][j]!=vazio) rede_local.entrada[k*nro_codigos+elemento_obstaculo]=True; } if(codigo>0 && k<codigo) rede_local.entrada[k*nro_codigos+elemento_adicional]=True; if(codigo<0 && (63-k)<abs(codigo)) rede_local.entrada[k*nro_codigos+elemento_adicional]=True; if(i==tabuleiro_local.robo.x || j==tabuleiro_local.robo.y) { if(rede_local.entrada[k*nro_codigos+elemento_adicional]==True) rede_local.entrada[k*nro_codigos+elemento_adicional]=False; else rede_local.entrada[k*nro_codigos+elemento_adicional]=True; } if(codigo2>0 && k<codigo2) rede_local.entrada[k*nro_codigos+elemento_obstaculo]=True; if(codigo2<0 && (63-k)<abs(codigo2)) rede_local.entrada[k*nro_codigos+elemento_obstaculo]=True; k++; } // dump_rede(rede_local,True); x_mem=tabuleiro_local.robo.x; y_mem=tabuleiro_local.robo.y; // C A M A D A E S C O N D I D A for(i=0;i<nr_escondidos;i++) // inicializacao dos neuronios escondidos - necessaria por causa da soma a seguir rede_local.escondido[i]=0.0; for(i=0;i<nr_escondidos;i++) // entrada para dendritos neuronios escondidos for(j=0;j<nr_entradas;j++) rede_local.escondido[i]=rede_local.escondido[i]+rede_local.entrada[j]*rede_local.sinapse1[j][i]; for(i=0;i<nr_escondidos;i++) // dendritos escondidos para axonios (usando mesmo campo...) rede_local.escondido[i]=sigmoide(rede_local.escondido[i]); // S A I D A for(i=0;i<nr_saidas;i++) // inicializacao das saidas - necessaria por causa da soma a seguir rede_local.saida[i]=0.0; for(i=0;i<nr_saidas;i++) // escondidos para dendritos das saidas for(j=0;j<nr_escondidos;j++) rede_local.saida[i]=rede_local.saida[i]+rede_local.escondido[j]*rede_local.sinapse2[j][i]; for(i=0;i<nr_saidas;i++) // dendritos saidas para axonios (tambem usando mesmo campo...) rede_local.saida[i]=sigmoide(rede_local.saida[i]); return rede_local; } ///////////////////////////////////////////////////////////////////// // Funcao: backpropagation // // Descricao: Rotina para aprendizado da rede // // Parametros: Rede neural apos processamento e a saida desejada // // Retorno: Rede neural alterada pelo aprendizado // // Versao: 0.1 - Versao inicial // // Observacoes: // // Formulas aplicadas // // ------------------ // // // // 1.Erros na camada de saida // // // // o2[j]=o[j](1-o[j])(y[j]-o[j]) p/ j=0,...,C // // // // 2.Erros na camada escondida // // // // o1[j]=h[j](1-h[j]).soma3 // // // // onde soma3 = soma(i=1 a c)o2[i].w2[i][j] // // // // 3.Ajuste entre camada escondida e saida // // // // dw2[i][j]=n.o2[j].h[i] p/ i=0,...,B e // // j=0,...,C // // // // 4.Ajuste entre camada de entrada e camada escondida // // // // dw1[i][j]=n.o1[j].x[i] p/ i=0,...,A e // // j=0,...,B // // // // Legenda // // ------- // // // // A : nro de entradas // // B : nro de neuronios na camada escondida // // C : nro de saidas // // // // o : saida real da rede // // y : saida desejada // // h : axonios da camada escondida // // w2 : valor de sinapses entre camada // // escondida e saida // // n : taxa de aprendizado // // x : valor da entrada // // // // o2 : erro nas saidas // // o1 : erro na camada escondida // // dw2 : ajuste (diferenca) nas sinapses entre // // camada escondida e saida // // dw1 : ajuste (diferenca) nas sinapses entre // // entrada e camada escondida // // // ///////////////////////////////////////////////////////////////////// REDE_NEURAL backpropagation(REDE_NEURAL rede_local, SAIDA saida_local) { const int c = nr_saidas; // nro de unidades na camada de saida const int b = nr_escondidos; // elementos na camada escondida const int a = nr_entradas; // elementos na camada de entrada const float n = float(0.35); // taxa de aprendizado float o2[c], o1[b], soma3; // erros na saida float dw2[b][c], dw1[a][b]; // ajustes int i, j; ///////////////////////////////////////////////////////////////////// // 1.Erros na camada de saida // // // // o2[j]=o[j](1-o[j])(y[j]-o[j]) p/ j=0,...,C // ///////////////////////////////////////////////////////////////////// for(i=0;i<c;i++) o2[i]=float(rede_local.saida[i]*(1.0-rede_local.saida[i])* (saida_local.valor[i]-rede_local.saida[i])); // if(debug) // { // printf("O2\n\n"); // for(i=0;i<c;i++) // printf("%f\n",o2[i]); // getch(); // } ///////////////////////////////////////////////////////////////////// // 2.Erros na camada escondida // // // // o1[j]=h[j](1-h[j]).soma3 // // // // onde soma3 = soma(i=1 a c)o2[i].w2[i][j] // ///////////////////////////////////////////////////////////////////// for(j=0;j<b;j++) { soma3=0.0; for(i=0;i<c;i++) soma3=soma3+(o2[i]*rede_local.sinapse2[j][i]); // soma3 para cada passo o1[j]=float(rede_local.escondido[j]*(1.0-rede_local.escondido[j])*soma3); } // if(debug) // { // printf("O1\n\n"); // for(i=0;i<c;i++) // printf("%f\n",o1[i]); // getch(); // } ///////////////////////////////////////////////////////////////////// // 3.Ajuste entre camada escondida e saida // // // // dw2[i][j]=n.o2[j].h[i] p/ i=0,...,B e // // j=0,...,C // ///////////////////////////////////////////////////////////////////// for(i=0;i<b;i++) for(j=0;j<c;j++) { dw2[i][j]=n*o2[j]*rede_local.escondido[i]; // calculo dos ajustes entre camada escondida e saida rede_local.sinapse2[i][j]=rede_local.sinapse2[i][j]+dw2[i][j]; // executar ajustes aproveitando o mesmo laco } ///////////////////////////////////////////////////////////////////// // 4.Ajuste entre camada de entrada e camada escondida // // // // dw1[i][j]=n.o1[j].x[i] p/ i=0,...,A e // // j=0,...,B // ///////////////////////////////////////////////////////////////////// for(i=0;i<a;i++) for(j=0;j<b;j++) { dw1[i][j]=n*o1[j]*rede_local.entrada[i]; // calculo dos ajustes entre camada de entrada e escondida rede_local.sinapse1[i][j]=rede_local.sinapse1[i][j]+dw1[i][j]; // executar ajustes aproveitando o mesmo laco } return rede_local; } ///////////////////////////////////////////////////////////////////// // Funcao: extrai_saidas // // Descricao: Rotina em si completamente banal que extrai as // // saidas isolando-as numa variavel // // Parametros: Rede neural (com as saidas a serem trabalhadas) // // Retorno: Saidas em forma de array // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// SAIDA extrai_saidas(REDE_NEURAL rede_local) { int i; SAIDA saida_local; for(i=0;i<nr_saidas;i++) saida_local.valor[i]=rede_local.saida[i]; return saida_local; } ///////////////////////////////////////////////////////////////////// // Funcao: cria_mapa_das_saidas // // Descricao: Rotina para apresentacao das saidas da rede em // // forma da matriz inicial // // Parametros: Saida isolada da rede // // Retorno: Saidas em forma de matriz // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// MAPA cria_mapa_das_saidas(SAIDA saida_local) { int i, j, k; MAPA mapa_local; k=0; for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { mapa_local.preferencia[i][j]=saida_local.valor[k]; k++; } return mapa_local; } ///////////////////////////////////////////////////////////////////// // Funcao: cria_saidas_do_mapa // // Descricao: Rotina inversa da anterior para criacao da saida // // na forma da rede a partir da matriz // // Parametros: Saida da rede em forma de matriz // // Retorno: Saidas em forma sequencial // // Versao: 0.1 - Versao inicial // // Observacoes: - // ///////////////////////////////////////////////////////////////////// SAIDA cria_saidas_do_mapa(MAPA mapa_local) { int i, j, k; SAIDA saida_local; k=0; for(i=0;i<x_max;i++) for(j=0;j<y_max;j++) { saida_local.valor[k]=mapa_local.preferencia[i][j]; k++; } return saida_local; } void modificar_tabuleiro(void) { char entrada; int cur_x, cur_y, tabuleiro_nr; TABULEIRO tabuleiro_local; tabuleiro_local=init_tabuleiro(0); tabuleiro_local.robo.x=dummy; tabuleiro_local.robo.y=dummy; tabuleiro_local.destino.x=dummy; tabuleiro_local.destino.y=dummy; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," MODIFICACAO TABULEIRO "); tabuleiro_nr=escolha(0,10,labirinto); tabuleiro_local=data[tabuleiro_nr]; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," MODIFICACAO TABULEIRO "); setcolor( XFOREGROUND_WHITE | XBACKGROUND_BLACK ); caixa_mensagem(simples,0,21," r = robo, d = destino, o = obstaculo, . = vazio, enter = fim. "); setcolor( XFOREGROUND_WHITE | XBACKGROUND_BLACK ); cur_x=0; cur_y=0; while(entrada!=char(13)) { mostra_tabuleiro(tabuleiro_local,False,False); gotoxy(x_start+1+(cur_x*2),y_start+1+cur_y); entrada=getch(); switch(entrada) { case 'o': if(((cur_x!=tabuleiro_local.destino.x) || (cur_y!=tabuleiro_local.destino.y)) && ((cur_x!=tabuleiro_local.robo.x) || (cur_y!=tabuleiro_local.robo.y))) tabuleiro_local.elemento[cur_x][cur_y]=obstaculo; break; case '.': tabuleiro_local.elemento[cur_x][cur_y]=vazio; break; case 'r': tabuleiro_local.robo.x=cur_x; tabuleiro_local.robo.y=cur_y; break; case 'd': tabuleiro_local.destino.x=cur_x; tabuleiro_local.destino.y=cur_y; break; case char(72) : if(cur_y>0) cur_y--; break; case char(80) : if(cur_y<y_max-1) cur_y++; break; case char(75) : if(cur_x>0) cur_x--; break; case char(77) : if(cur_x<x_max-1) cur_x++; break; } } cor_padrao(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); titulo(); caixa_mensagem(simples,0,6," MODIFICACAO TABULEIRO "); if(tabuleiro_local.destino.x==dummy || tabuleiro_local.robo.x==dummy) { caixa_mensagem(alerta,0,13," Erro em coordenadas de robo ou destino. "); return; } mostra_tabuleiro(tabuleiro_local,False,False); if(caixa_mensagem(pergunta,0,21," Substituir tabuleiro original? ")==True) data[tabuleiro_nr]=tabuleiro_local; } void mostra_tabuleiros(void) { TABULEIRO tabuleiro_local; int i; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); cor_padrao(); caixa_mensagem(simples,0,6," LABIRINTOS ATIVOS "); titulo(); for(i=0;i<max_tabuleiros;i++) { tabuleiro_local=init_tabuleiro(i); // tabuleiro_local=estabelece_visao(tabuleiro_local); // tabuleiro_local=estabelece_giros(tabuleiro_local); mostra_tabuleiro(tabuleiro_local,False,False); tecla(); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); caixa_mensagem(simples,0,6," LABIRINTOS ATIVOS "); titulo(); } } ///////////////////////////////////////////////////////////////////// // Funcao: mostra_saida // // Descricao: Mostra a saida em forma de array // // Parametros: Saida da rede em forma de array // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: apenas para debug das funcoes de conversao // ///////////////////////////////////////////////////////////////////// void mostra_saida(SAIDA saida_local) { int i; clrscr( XFOREGROUND_WHITE | XBACKGROUND_BLUE ); printf("DUMP DE ARRAY DE SAIDAS\n\n"); for(i=0;i<nr_saidas;i++) printf("%f - ",saida_local.valor[i]); getch(); } ///////////////////////////////////////////////////////////////////// // Funcao: mostra_mapa // // Descricao: Mostra a matriz da saida // // Parametros: Saida da rede em forma de matriz // // Retorno: - // // Versao: 0.1 - Versao inicial // // Observacoes: apenas para debug das funcoes de conversao // ///////////////////////////////////////////////////////////////////// void mostra_mapa(MAPA mapa_local) { int i, j; printf("DUMP DE MATRIZ DE SAIDAS\n\n"); for(i=0;i<y_max;i++) { for(j=0;j<x_max;j++) printf("%f - ",mapa_local.preferencia[j][i]); printf("\n"); } getch(); } ///////////////////////////////////////////////////////////////////// // Funcao: gera_saida_para_teste // // Descricao: Rotina para teste do algoritmo de aprendizado // // Parametros: Os pontos a ficarem ligados na saida // // Retorno: Saida em forma de array // // Versao: 0.1 - Versao inicial // // Observacoes: apenas para debug // ///////////////////////////////////////////////////////////////////// SAIDA gera_saida_para_teste(int positivo1, int positivo2) { SAIDA saida_local; int i; for(i=0;i<nr_saidas;i++) saida_local.valor[i]=0.0; saida_local.valor[positivo1]=1.0; saida_local.valor[positivo2]=1.0; return saida_local; } void testa_teclado(void) { char ch_local; ch_local='+'; while(ch_local!='x') { ch_local=getch(); printf("%i ",abs(ch_local)); } }
true
1c947a7c6ac3b83bdfbbe000fe70d6ac469c7fcd
C++
sersajur/QPentago
/src/PentagoLib/include/PentagoLib/Board.h
UTF-8
901
2.65625
3
[]
no_license
/* * Board.h * * Created on: 10 лист. 2013 * Author: Gasper */ #ifndef BOARD_H #define BOARD_H #include <PentagoLib/serialization.h> class Board : public IOriginator { public: enum class RotateDirection { Left, Right }; enum class Quadrant { I = 1, II, III, IV, V, VI, VII, VIII, IX }; Board(unsigned _rowCount = 6, unsigned _colCount = 6); virtual ~Board() { } bool putStone(short, short, short); void Rotate(Quadrant, RotateDirection); const short& operator()(short, short); vector<short>& operator[](short); void Clear(); unsigned getRowCount() { return rowCount; } unsigned getColCount() { return colCount; } virtual GameState SaveGame(); virtual void RestoreGame(GameState&); private: typedef vector<vector<short>> TheBoard; TheBoard board; unsigned rowCount, colCount; unsigned stepNum; }; #endif /* BOARD_H */
true
d4622028629eaa02880f4951765d851aa2287614
C++
joiiewang/pa02_cs130a
/minHeap.cpp
UTF-8
6,268
3.25
3
[]
no_license
#include <vector> #include <string> #include "minHeap.h" #include "Node.h" #include <iostream> using namespace std; Node* minHeap::getMin(){ return v[0]; } pair<string,Node*> minHeap::changeMin(string s, int c){ string temp = v[0]->word; v[0]->word = s; v[0]->frequency++; v[0]->counter = c; int current =0; while(1){ Node* rightChild = 2*current+2 < v.size() ? v[2*current+2] : nullptr; Node* leftChild = 2*current+1 <v.size() ? v[2*current+1] : nullptr; if(!rightChild && !leftChild) break; else if(!rightChild){ if(v[current]->frequency>leftChild->frequency){ //swap nodes Node* temp = v[current]; v[current] = v[leftChild->index]; v[leftChild->index] = temp; current = leftChild->index; //swapping index int num = leftChild->index; leftChild->index = temp->index; temp->index = num; } break; } else{ Node* lowerFreq; if(leftChild->frequency<rightChild->frequency){ lowerFreq = leftChild; } else if(leftChild->frequency==rightChild->frequency){ lowerFreq = leftChild->counter<rightChild->counter ? rightChild:leftChild; } else lowerFreq = rightChild; if(lowerFreq->frequency<v[current]->frequency){ Node* temp = v[current]; v[current] = v[lowerFreq->index]; v[lowerFreq->index] = temp; current = lowerFreq->index; //swapping index int num = lowerFreq->index; lowerFreq->index = temp->index; temp->index = num; } else break; } } return make_pair(temp,v[current]); } Node* minHeap::insert(string s, int c){ Node* n = new Node(v.size(), s, 1, c); v.push_back(n); int compare = ((v.size()-1)-1)/2; int current = v.size()-1; if(v.size() > 1){ while(v[current]->frequency <= v[compare]->frequency){ Node* temp = v[compare]; v[compare] = v[current]; v[current] = temp; int num = temp->index; temp->index = v[compare]->index; v[compare]->index = num; current = compare; if(compare ==0) break; compare = (compare-1)/2; if(compare < 0) break; } } return n; } void minHeap::increaseFrequency(Node* n){ n->frequency++; //n->counter = c; int current = n->index; while(1){ Node* rightChild = 2*current+2 < v.size() ? v[2*current+2] : nullptr; Node* leftChild = 2*current+1 <v.size() ? v[2*current+1] : nullptr; if(!rightChild && !leftChild) break; else if(!rightChild){ if(v[current]->frequency>leftChild->frequency || v[current]->counter < leftChild->counter){ //swap nodes Node* temp = v[current]; v[current] = v[leftChild->index]; v[leftChild->index] = temp; current = leftChild->index; //swapping index int num = leftChild->index; leftChild->index = temp->index; temp->index = num; } break; } else{ Node* lowerFreq; if(leftChild->frequency<rightChild->frequency){ lowerFreq = leftChild; } else if(leftChild->frequency==rightChild->frequency){ lowerFreq = leftChild->counter<rightChild->counter ? rightChild:leftChild; } else lowerFreq = rightChild; if(lowerFreq->frequency<v[current]->frequency || (lowerFreq->frequency == v[current]->frequency && lowerFreq->counter > v[current]->counter)){ Node* temp = v[current]; v[current] = v[lowerFreq->index]; v[lowerFreq->index] = temp; current = lowerFreq->index; //swap index int num = temp->index; temp->index = lowerFreq->index; lowerFreq->index = num; } else{ break; } } } } void minHeap::removeMin(){ v[0] = v[v.size()-1]; v[0]->index = 0; v.pop_back(); int current =0; while(1){ Node* rightChild = 2*current+2 < v.size() ? v[2*current+2] : nullptr; Node* leftChild = 2*current+1 <v.size() ? v[2*current+1] : nullptr; if(!rightChild && !leftChild) break; else if(!rightChild){ if(v[current]->frequency>leftChild->frequency || (v[current]->frequency == leftChild->frequency && v[current]->counter < leftChild->counter)){ //swap nodes Node* temp = v[current]; v[current] = v[leftChild->index]; v[leftChild->index] = temp; current = leftChild->index; //swapping index int num = leftChild->index; leftChild->index = temp->index; temp->index = num; } break; } else{ Node* lowerFreq; if(leftChild->frequency<rightChild->frequency){ lowerFreq = leftChild; } else if(leftChild->frequency==rightChild->frequency){ lowerFreq = leftChild->counter<rightChild->counter ? rightChild:leftChild; } else lowerFreq = rightChild; if((lowerFreq->frequency<v[current]->frequency)|| (lowerFreq->frequency==v[current]->frequency&&lowerFreq->counter>v[current]->counter)){ Node* temp = v[current]; v[current] = v[lowerFreq->index]; v[lowerFreq->index] = temp; current = lowerFreq->index; //swapping index int num = lowerFreq->index; lowerFreq->index = temp->index; temp->index = num; } else break; } } }
true
47c0e0605490bc1ec6915825dd2380562f901825
C++
CknightX/Ryugu
/Ryugu/net/Poller.h
UTF-8
1,161
2.578125
3
[]
no_license
/* Poller 抽象系统底层的IO复用机制 */ #pragma once #include <set> #include <atomic> #include <stdint.h> #include "Ryugu/net/Netheaders.h" namespace ryugu { namespace net { class Epoll; class Channel; const int cstMaxChannels = 20; // IO复用器基类 class Poller { public: int64_t id; int lastActive; Poller() :lastActive(-1), id(_id++) { } virtual void addChannel(Channel* event) = 0; virtual void removeChannel(Channel* event) = 0; virtual void updateChannel(Channel* event) = 0; virtual void loopOnce(int waitMs) = 0; virtual ~Poller() {} private: static std::atomic<int64_t> _id; }; // Linux下的Epoll模型 class Epoll final : public Poller { public: Epoll(); ~Epoll(); int epollFd; std::set<Channel*> liveChannels; epoll_event activeChannels[cstMaxChannels]; void addChannel(Channel* ch) override; void removeChannel(Channel* ch) override; void updateChannel(Channel* ch) override; void loopOnce(int waitMs) override; }; class PollerFactory { public: static Poller* getPoller() { return new Epoll(); } }; } }
true
7a2bc834ccd810a2dce0cb584691fcfda906c113
C++
youoj/Algorithm
/Baekjoon/[5427]불.cpp
UTF-8
2,519
3.265625
3
[]
no_license
/* 5427번 불(DFS/BFS) * https://www.acmicpc.net/problem/5427 */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <vector> #include <queue> using namespace std; int inputW = 0, inputH = 0; int dir_x[4] = { 1, 0, -1, 0 }; int dir_y[4] = { 0, 1, 0, -1 }; enum Form { wall, fire, space, person }; struct Node { Node(int x, int y, int form) : node_x(x), node_y(y), node_form(form) {} int node_x, node_y, node_form; }; bool isInsideBoundary(int x, int y) { if (x >= 0 && x < inputH && y >= 0 && y < inputW) return true; else return false; } void bfs(vector<vector<int> > &map, queue<Node> &queue) { vector<vector<int> > day(inputH, vector<int>(inputW, 0)); bool escape = false; while (!queue.empty() && !escape) { int x = queue.front().node_x, y = queue.front().node_y, form = queue.front().node_form; queue.pop(); if (form == person) { if (x == 0 || x == inputH - 1 || y == 0 || y == inputW - 1) { cout << day[x][y] + 1 << endl; escape = true; break; } } if (form == person && map[x + 1][y] == wall && map[x][y + 1] == wall && map[x - 1][y] == wall && map[x][y - 1] == wall) break; if (form == person && map[x + 1][y] == fire && map[x][y + 1] == fire && map[x - 1][y] == fire && map[x][y - 1] == fire) break; for (int i = 0; i < 4 && !escape; i++) { int newX = x + dir_x[i], newY = y + dir_y[i]; if (form == fire && isInsideBoundary(newX, newY) && map[newX][newY] != fire && map[newX][newY] != wall) { map[newX][newY] = fire; queue.push(Node(newX, newY, fire)); } if (form == person &&isInsideBoundary(newX, newY) && map[newX][newY] == space) { map[newX][newY] = person; day[newX][newY] = day[x][y] + 1; queue.push(Node(newX, newY, person)); } } } if (!escape) cout << "IMPOSSIBLE" << endl; } int main() { int inputT = 0; cin >> inputT; for (int t = 0; t < inputT; t++) { cin >> inputW >> inputH; vector<vector<int> > map(inputH, vector<int>(inputW, 0)); queue<Node> queue; for (int i = 0; i < inputH; i++) { string s; cin >> s; for (int j = 0; j < inputW; j++) { if (s[j] == '#') { map[i][j] = wall; } else if (s[j] == '*') { map[i][j] = fire; queue.push(Node(i, j, fire)); } else if (s[j] == '.') { map[i][j] = space; } else if (s[j] == '@') { map[i][j] = person; } } } for (int i = 0; i<inputH; i++) for (int j = 0; j<inputW; j++) if (map[i][j] == person) queue.push(Node(i, j, person)); bfs(map, queue); } return 0; }
true
54afb76583af641e2196024f8397837aceac368a
C++
A284Philipi/2388_Tacografo_Cpp
/main.cpp
UTF-8
347
2.859375
3
[]
no_license
#include <iostream> using namespace std; int main() { int cont = 0, tempo, velocidade, casos, distancia = 0; cin >> casos; while (cont < casos){ cin >> tempo; cin >> velocidade; distancia = distancia + (velocidade * tempo); cont++; } cout << distancia <<endl; return 0; }
true
414ae358618cba77d08443b40e0aa2cfa7553cdb
C++
abhishek9897/Data-Structures-And-Algorithms-using-cpp
/Print Subsequences.cpp
UTF-8
472
2.984375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void printSubsequences(string str,string subseq,int i,int n) { if(i==n) { cout<<subseq<<endl; return; } // include in subsequence printSubsequences(str,subseq+str[i],i+1,n); // not include in subsequence printSubsequences(str,subseq,i+1,n); } int main() { string str; cout<<"Enter String For subsequences: "; cin>>str; int n=str.length(); printSubsequences(str,"",0,n); return 0; }
true
62321dc80124eedbf2a8f277fa72698a2ea9961e
C++
jeongbbn/Algorithm
/BOJ/17025.cpp
UTF-8
1,336
2.546875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define INF 1e9 typedef pair<int, int>pi; typedef pair<pair<int, int>, int>pii; typedef long long ll; int n; char arr[1005][1005]; int dx[] = { 1,-1,0,0 }; int dy[] = { 0,0,1,-1}; bool visit[1005][1005]; queue<pii>q; pi ans; bool outrange(int x, int y) { if (x < 0 || y < 0 || x >= n || y >= n) return 1; return 0; } pi bfs() { int p = 0; //perimeter int a = 1; //area while (!q.empty()) { int x = q.front().first.first; int y = q.front().first.second; int dist = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if (outrange(nx, ny)) { p++; continue;} if (visit[nx][ny]) continue; if (arr[nx][ny] == '.') { p++; continue; } a++; visit[nx][ny] = 1; q.push({ {nx, ny}, dist + 1 }); } } return { a,p }; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { scanf(" %c", &arr[i][j]); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (arr[i][j] == '#' && !visit[i][j]) { q.push({ { i,j }, 1 }); visit[i][j] = 1; pi tmp = bfs(); if (ans.first < tmp.first) ans = tmp; else if (ans.first == tmp.first && ans.second > tmp.second) ans = tmp; } } } printf("%d %d", ans.first, ans.second); }
true
6ea8ad6b29f74d8824d5cca81b6e11d80cf46e53
C++
JPcarbonell/Algoritmos2E2
/Entrega2/Framework/Prueba.h
UTF-8
714
2.5625
3
[]
no_license
#pragma once class Cadena; class ConductorPrueba; class EstadisticaPrueba; #include "Puntero.h" #include "TipoRetorno.h" class Prueba abstract { public: Prueba(); virtual ~Prueba(); void CorrerPrueba(Puntero<ConductorPrueba> conductor); protected: virtual void CorrerPruebaConcreta() abstract; virtual Cadena GetNombre() const abstract; Puntero<EstadisticaPrueba>& GetEstadisticaPrueba(); void Verificar(TipoRetorno retorno, TipoRetorno retornoEsperado, Cadena comentario); void IniciarSeccion(Cadena nombreSeccion, TipoRetorno tipoPrueba = OK); void CerrarSeccion(); private: Puntero<EstadisticaPrueba> m_EstadisticaPrueba; Puntero<ConductorPrueba> m_Conductor; };
true
0078c46ccbac75021a0384c89ce1f4555c167c3f
C++
mengzhangjian/c-_thread_reading
/chapter-02/accumulate.cpp
UTF-8
1,781
3.484375
3
[]
no_license
// // Created by Zhang,Jian(SEC) on 2020/12/3. // #include <thread> #include <iostream> #include <numeric> #include <vector> template<typename Iterator, typename T> struct accumulate_block { void operator()(Iterator it, Iterator last, T& result) { result = std::accumulate(it, last, result); } }; template<typename Iterator, typename T> T parallel_accumulate(Iterator first, Iterator last, T init) { unsigned long const length = std::distance(first, last); if(!length) return init; unsigned long const min_per_thread = 25; unsigned long const max_threads = (length + min_per_thread - 1) / min_per_thread; unsigned long const hardware_threads = std::thread::hardware_concurrency(); unsigned long const num_threads = std::min(hardware_threads != 0 ? hardware_threads: 2, max_threads); unsigned long const block_size = length / num_threads; std::vector<T> results(num_threads); std::vector<std::thread> threads(num_threads - 1); Iterator block_start = first; for(unsigned long i = 0; i < (num_threads - 1); ++i) { Iterator block_end = block_start; std::advance(block_end, block_size); threads[i] = std::thread(accumulate_block<Iterator, T>(), block_start, block_end, std::ref(results[i])); block_start = block_end; } accumulate_block<Iterator, T>()(block_start, last, results[num_threads - 1]); std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join)); return std::accumulate(results.begin(), results.end(), init); }; int main(){ std::vector<int> elements{1, 2,3,4,5,6,7,8,9,10}; int result = parallel_accumulate(elements.begin(), elements.end(), 0); std::cout << "result is: " << result << std::endl; return 0; }
true
77f5304ebe2656d48c6790501b2e527fdf09090b
C++
Astarx1/cluster
/source/worker/network/interfaces/structures/answer.hpp
UTF-8
285
2.875
3
[ "MIT" ]
permissive
#ifndef ANSWER_HPP #define ANSWER_HPP typedef struct Answer { Answer() : status (1) { ; } Answer(int s) : status(s) { ; } Answer(std::string ret) : status(2), data(ret) { ; } int status; // 0 = Not Ok, 1 = Ok without answer, 2 = Ok with answer std::string data; } Answer; #endif
true
90e32dcc7866d54d52959b27e094966eaa875c4c
C++
SonbolYb/Stream-ANCFIS-FeedForward
/inputVector.h
UTF-8
925
2.78125
3
[]
no_license
/* * inputVector.h * * Created on: Jun 10, 2015 * Author: sonbol * * This class is a child class of commandLine. * * It has a member variable that is a reference because we want to use a dataset from main and we want to prevent copying it, so pass it by refrence. * */ #ifndef INPUTVECTOR_H_ #define INPUTVECTOR_H_ #include "header.h" #include "commandLine.h" class inputVector: public commandLine { private: std::vector<double> input; std::vector<double> target; /* std::vector<double> & pinput; std::vector<double> & ptarget;*/ public: inputVector(); std::vector<double> * const readInput(); std::vector<double>* const readTarget(); void readData(const std::vector<double>&); friend void inputVector_test(std::vector<double> ); /* std::vector<double> & readInput(); std::vector<double>& readTarget();*/ }; void inputVector_test(std::vector<double>); #endif /* INPUTVECTOR_H_ */
true
70a749d33164e22915d976c70db5e2dfebf5bac5
C++
aleksei-glitch/RFReceiver
/RFReceiver.ino
UTF-8
11,001
2.546875
3
[ "MIT" ]
permissive
/* Simple RF receiver and poster to thingspeak.com Receives date from RF transpotter [RFTransmitter.ino] and posts it to thingspeak.com using ethernet. To see debug messages set variable serialInit to true. Will initiate Serial and prinr messages. For standalone mode set serialInit=false; Arduino pinout ------------------------------- +5v -> RF receiver Vcc PIN 12 -> RF receiver Data pin GND -> RF receiver GND PIN 13 -> Receive LED indicator PIN 2 -> RELAY for reating ------------------------------- Created By: Aleksei Ivanov Creation Date: 2015/05/23 Last Updated Date:2021/01/02 */ #include <avr/wdt.h> #include <SPI.h> #include <Ethernet.h> #include <HttpClient.h> #include <VirtualWire.h> //Library Required boolean serialInit = true; long RELAY_SET_TIME; // relay status change timestamp millis() long AWAKE_H = 12L*60L*60L; long AWAKE_MIN = 0L*60L; long AWAKE_SEC= 0L; long MODULE_REBOOT_LIMIT = 1000L*(AWAKE_H + AWAKE_MIN + AWAKE_SEC);//reboot every minute long RELAY_DELAY_LIMIT = 1000L*60L*5L; //relay on for 5 min if no further signals arrive int HEATING_RELAY_PIN = 2;//Relay pin to set high in order to close relay and set low to open/disconnect String sFields; char t_buffer[10]; String temp; int RX_PIN = 12;// Tell Arduino on which pin you would like to receive data NOTE should be a PWM Pin int RX_ID = 3;// Recever ID address int TX_ID; //Data Structure typedef struct roverRemoteData { int TX_ID; // Initialize a storage place for the incoming TX ID float Sensor1Data;// Initialize a storage place for the first integar that you wish to Receive float Sensor2Data;// Initialize a storage place for the Second integar that you wish to Receive float Sensor3Data;// Initialize a storage place for the Third integar that you wish to Receive float Sensor4Data;// Initialize a storage place for the Forth integar that you wish to Receive float Sensor5Data;// Initialize a storage place for the Forth integar that you wish to Receive String API_KEY; //Posting to server key }; // MAC address for your Ethernet shield byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // Your ThingsSpeak API key to let you upload data String sApiKeys[] = {"APIKEY0","APIKEY1","APIKEY12","APIKEY13"}; long lThingTimers[] = {0,0,0,0}; long lDelayLimit=25000L; //send sensor data to web not more often than every 25sec EthernetClient client; /*--------------------------------------------------------------------------------- -- setup ---------------------------------------------------------------------------------*/ void setup() { if (serialInit)Serial.begin(9600);// Begin Serial port at a Buad speed of 9600bps if (serialInit)Serial.println("Setup start"); pinMode(13, OUTPUT); pinMode(HEATING_RELAY_PIN,OUTPUT); if (serialInit)Serial.println("Set Relay OFF..."); setRelayOFF();//initially RELAY OFF - open if (serialInit)Serial.println("Start radio communication..."); //vw_set_ptt_inverted(true); // Required for DR3100 vw_set_rx_pin(RX_PIN);// Set RX Pin vw_setup(4000);// Setup and Begin communication over the radios at 2000bps( MIN Speed is 1000bps MAX 4000bps) vw_rx_start(); if (serialInit)Serial.println("Connect Ethernet..."); //Ethernet.begin(mac,ip); if(Ethernet.begin(mac)==1) { if (serialInit)Serial.println("Ethernet connect Successful"); if (serialInit)Serial.print("IP:"); if (serialInit)Serial.println(Ethernet.localIP()); } else{ if (serialInit)Serial.println("Error getting IP address via DHCP, try again by resetting..."); } } /*--------------------------------------------------------------------------------- -- loop ---------------------------------------------------------------------------------*/ void loop(){ long myTime=millis(); if (serialInit)Serial.print("millis / reboot limit / countdown : "); if (serialInit)Serial.print(myTime); if (serialInit)Serial.print(" / "); if (serialInit)Serial.print(MODULE_REBOOT_LIMIT); if (serialInit)Serial.print(" / "); if (serialInit)Serial.println(myTime-MODULE_REBOOT_LIMIT); if (myTime-MODULE_REBOOT_LIMIT>0) reboot(); //reboot periodically whole module to avoid millis overflow //delay(10000); sFields=""; //digitalWrite(13,LOW); //relay reset setRelayReset(); struct roverRemoteData receivedData; uint8_t rcvdSize = sizeof(receivedData);//Incoming data size vw_wait_rx();// Start to Receive data now if (vw_get_message((uint8_t *)&receivedData, &rcvdSize)) // Check if data is available { //digitalWrite(13,HIGH); if (receivedData.TX_ID == 3 or receivedData.TX_ID == 2 or receivedData.TX_ID == 1) //radio signal recieved from basement { sFields="&1="+getFString(receivedData.Sensor1Data); sFields=sFields+"&2="+getFString(receivedData.Sensor2Data); sFields=sFields+"&3="+getFString(receivedData.Sensor3Data); sFields=sFields+"&4="+getFString(receivedData.Sensor4Data); // RELAY control based on battery powered temperature sensor if (receivedData.TX_ID == 2 ){ // if((receivedData.Sensor1Data) == 1.0) { //turn relay on for 30sec setRelayON(); }else{ //turn relay off for other cases setRelayOFF(); } } if (receivedData.API_KEY != ""){ sendHttpGet(receivedData.API_KEY, sFields,0); //send to ThingsSpeak } else{ if (receivedData.TX_ID==1)sendHttpGet("", sFields,1); //send to ThingsSpeak if (receivedData.TX_ID==2)sendHttpGet("", sFields,2); //send to ThingsSpeak if (receivedData.TX_ID==3)sendHttpGet("", sFields,3); //send to ThingsSpeak } // If data was Recieved print it to the serial monitor. if (serialInit)Serial.println("------------------------New MSG-----------------------"); if (serialInit)Serial.print("TX ID:"); if (serialInit)Serial.println(receivedData.TX_ID); if (serialInit)Serial.print("Sensor1Data:"); if (serialInit)Serial.println(receivedData.Sensor1Data); if (serialInit)Serial.print("Sensor2Data:"); if (serialInit)Serial.println(receivedData.Sensor2Data); if (serialInit)Serial.print("Sensor3Data:"); if (serialInit)Serial.println(receivedData.Sensor3Data); if (serialInit)Serial.print("Sensor4Data:"); if (serialInit)Serial.println(receivedData.Sensor4Data); if (serialInit)Serial.print("Sensor5Data:"); if (serialInit)Serial.println(receivedData.Sensor5Data); if (serialInit)Serial.print("API_KEY:"); if (serialInit)Serial.println(receivedData.API_KEY); if (serialInit)Serial.println("-----------------------End of MSG--------------------"); } else { if (serialInit)Serial.println(" ID Does not match waiting for next transmission "); } //digitalWrite(13,LOW); } } void reboot(){ if (serialInit)Serial.println(""); if (serialInit)Serial.println("... REBOOT ..."); if (serialInit)Serial.println(""); if (serialInit)Serial.flush(); wdt_disable(); wdt_enable(WDTO_15MS); while (1) {} } /*--------------------------------------------------------------------------------- -- setRelayON -- - set RELAY ON - closed status ---------------------------------------------------------------------------------*/ void setRelayON(){ digitalWrite(HEATING_RELAY_PIN,LOW); RELAY_SET_TIME = millis(); if (serialInit)Serial.println(" --> RELAY SET ON"); } /*--------------------------------------------------------------------------------- -- setRelayOFF -- - set RELAY OFF - open status ---------------------------------------------------------------------------------*/ void setRelayOFF(){ digitalWrite(HEATING_RELAY_PIN,HIGH); RELAY_SET_TIME = millis(); if (serialInit)Serial.println(" --> RELAY SET OFF"); } /*--------------------------------------------------------------------------------- -- setRelayReset -- - after given delay_limit reset RELAY OFF - open status ---------------------------------------------------------------------------------*/ void setRelayReset(){ //relay reset long myTime=millis(); if(myTime - RELAY_SET_TIME > RELAY_DELAY_LIMIT){ setRelayOFF(); } } /*--------------------------------------------------------------------------------- -- getFString -- - Converts float to string ---------------------------------------------------------------------------------*/ String getFString(float pFloat){ temp=dtostrf(pFloat,0,5,t_buffer); return temp; } int iHTTPfaiCount=0; /*--------------------------------------------------------------------------------- -- sendHttpGet -- - sends data to thingspeak ---------------------------------------------------------------------------------*/ void sendHttpGet(String pApiKey, String pFields,int n){ long myTime = millis(); if (serialInit)Serial.println(pApiKey+": "+pFields); if(myTime - lThingTimers[n] > lDelayLimit || myTime - lThingTimers[n] < 0L){ lThingTimers[n]=millis(); }else{ return; } if (client.connect("api.thingspeak.com", 80)) { if (serialInit)Serial.println("connected to thingspeak.."); if (serialInit)Serial.println("GET /update?api_key="+sApiKeys[n]+pFields+" HTTP/1.1"); //client.println("GET /update?key="+pApiKey+pFields+" HTTP/1.1");//sApiKeys(2) //client.println("GET /update?key="+sApiKeys[n]+pFields+" HTTP/1.1");// client.println("GET /update?api_key="+sApiKeys[n]+pFields+" HTTP/1.1");// client.println("Host: api.thingspeak.com"); //client.println("Host: 184.106.153.149"); client.println("Connection: close"); client.println(); /* client.print("POST /update HTTP/1.1\n"); //client.print("Host: api.thingspeak.com\n"); client.println("Host: 184.106.153.149"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: " + pApiKey + "\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(pFields.length()); client.print("\n\n"); client.print(pFields); */ delay(1000); if (client.connected()) { if (serialInit)Serial.println("ok"); iHTTPfaiCount = 0; while (client.available()) { char c = client.read(); if (serialInit)Serial.print(c); } } else { if (serialInit)Serial.println("FAIL"); iHTTPfaiCount++; } } else{ if (serialInit)Serial.println("thingspeak connect FAILED"); iHTTPfaiCount++; if(iHTTPfaiCount>2){ iHTTPfaiCount=0; client.stop(); if(Ethernet.begin(mac)==1) { if (serialInit)Serial.println("Ethernet connect Successful"); } else{ if (serialInit)Serial.println("Error getting IP address via DHCP, try again by re..."); } } } }
true
58caaba80b5a735c0e29bfebadf3a94b6f85e9fb
C++
invor/space-lion
/src/EngineCore/BillboardComponentManager.hpp
UTF-8
1,359
2.65625
3
[]
no_license
#ifndef BillboardComponentManager_hpp #define BillboardComponentManager_hpp #include <mutex> #include <string> #include <unordered_map> #include <vector> #include "BaseSingleInstanceComponentManager.hpp" #include "EntityManager.hpp" // TODO: documentation namespace EngineCore { class WorldState; namespace Animation { /** * Entities with billboard component will turn their z axis towards the designated target entity */ class BillboardComponentManager : public BaseSingleInstanceComponentManager { private: struct Data { Data(Entity entity, Entity target) : entity(entity), target(target) {} Entity entity; ///< The entity that gets rotated towards the target Entity target; ///< The entity that will be faced by the billboard }; std::vector<Data> m_billboard_data; std::shared_mutex m_billboard_data_access_mutex; public: BillboardComponentManager() = default; ~BillboardComponentManager() = default; void addComponent(Entity entity, Entity target); // TODO: deleteComponent?? std::vector<Data> getBillboardComponentDataCopy(); }; } } #endif // !BillboardComponentManager_hpp
true
3d0c852960ad5472ed442902e47e2d9ac2ee5f88
C++
FeiZhan/Algo-Collection
/answers/codeforces/534B Covered Path.cpp
UTF-8
794
2.671875
3
[ "MIT" ]
permissive
//@type greedy, DP //@result 12964986 2015-09-11 22:53:08 zetta217 534B - Covered Path GNU C++ Accepted 15 ms 0 KB // I don't use DP #include <iostream> using namespace std; int main() { int begin(0); int end(0); while (cin >> begin >> end) { if (begin > end) { int temp = begin; begin = end; end = temp; } int time(0); int change(0); cin >> time >> change; int current(begin); int distance(begin); for (int i = 1; i + 1 < time; ++ i) { current = current + change; if (current > end && current - change * (time - 1 - i) > end) { current = end + change * (time - 1 - i); } distance += current; //cout << "test " << i << " " << current << " " << distance << endl; } cout << distance + end << endl; } return 0; }
true
ad10953d8bf1dd2b54e385a03f7e7d14f4759c2c
C++
infinityhao/CPP
/sizeof_data_types.cpp
UTF-8
671
3.28125
3
[]
no_license
#include <iostream> using namespace std; char c; int i; float f; double d; bool b; wchar_t w; double s[10]; int main() { cout << "The size of char: " << sizeof(c) << "kb" << endl; cout << "The size of int: " << sizeof(i) << "kb" << endl; cout << "The size of float: " << sizeof(f) << "kb" << endl; cout << "The size of double: " << sizeof(d) << "kb" << endl; cout << "The size of boolean: " << sizeof(b) << "kb" << endl; cout << "The size of wchar_t: " << sizeof(w) << "kb" << endl; cout << "The size of double[10]: " << sizeof(s) << "kb" << endl; cout << "The size of double[10] / double[0]: " << sizeof(s) / sizeof(s[0]) << "kb" << endl; }
true
697a89b783d2a09c58191767c211b5eec6de4c39
C++
chaiyujin/ThreadedDepthCleaner
/src/main.cpp
UTF-8
7,220
2.609375
3
[ "MIT" ]
permissive
// Libraries #include <librealsense2/rs.hpp> // Include RealSense Cross Platform API #include <opencv2/opencv.hpp> // Include OpenCV API #include <opencv2/rgbd.hpp> // OpenCV RGBD Contrib package // STD #include <string> #include <thread> #include <atomic> #include <queue> using namespace cv; #define SCALE_FACTOR 1 /* * Class for enqueuing and dequeuing cv::Mats efficiently * Thanks to this awesome post by PKLab * http://pklab.net/index.php?id=394&lang=EN */ class QueuedMat{ public: Mat img; // Standard cv::Mat QueuedMat(){}; // Default constructor // Destructor (called by queue::pop) ~QueuedMat(){ img.release(); }; // Copy constructor (called by queue::push) QueuedMat(const QueuedMat& src){ src.img.copyTo(img); }; }; /* * Awesome method for visualizing the 16bit unsigned depth data using a histogram, slighly modified (: * Thanks to @Catree from https://stackoverflow.com/questions/42356562/realsense-opencv-depth-image-too-dark */ void make_depth_histogram(const Mat &depth, Mat &normalized_depth, int coloringMethod) { normalized_depth = Mat(depth.size(), CV_8U); int width = depth.cols, height = depth.rows; static uint32_t histogram[0x10000]; memset(histogram, 0, sizeof(histogram)); for(int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { ++histogram[depth.at<ushort>(i,j)]; } } for(int i = 2; i < 0x10000; ++i) histogram[i] += histogram[i-1]; // Build a cumulative histogram for the indices in [1,0xFFFF] for(int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { if (uint16_t d = depth.at<ushort>(i,j)) { int f = histogram[d] * 255 / histogram[0xFFFF]; // 0-255 based on histogram location normalized_depth.at<uchar>(i,j) = static_cast<uchar>(f); } else { normalized_depth.at<uchar>(i,j) = 0; } } } // Apply the colormap: applyColorMap(normalized_depth, normalized_depth, coloringMethod); } int main(int argc, char * argv[]) try { //Create a depth cleaner instance rgbd::DepthCleaner* depthc = new rgbd::DepthCleaner(CV_16U, 7, rgbd::DepthCleaner::DEPTH_CLEANER_NIL); // A librealsense class for mapping raw depth into RGB (pretty visuals, yay) rs2::colorizer color_map; // Declare RealSense pipeline, encapsulating the actual device and sensors rs2::pipeline pipe; //Create a configuration for configuring the pipeline with a non default profile rs2::config cfg; //Add desired streams to configuration cfg.enable_stream(RS2_STREAM_DEPTH, 640, 480, RS2_FORMAT_Z16, 30); // Start streaming with default recommended configuration pipe.start(cfg); // openCV window const auto window_name_source = "Source Depth"; namedWindow(window_name_source, WINDOW_AUTOSIZE); const auto window_name_filter = "Filtered Depth"; namedWindow(window_name_filter, WINDOW_AUTOSIZE); // Atomic boolean to allow thread safe way to stop the thread std::atomic_bool stopped(false); // Declaring two concurrent queues that will be used to push and pop frames from different threads std::queue<QueuedMat> filteredQueue; std::queue<QueuedMat> originalQueue; // The threaded processing thread function std::thread processing_thread([&]() { while (!stopped){ rs2::frameset data = pipe.wait_for_frames(); // Wait for next set of frames from the camera rs2::frame depth_frame = data.get_depth_frame(); //Take the depth frame from the frameset if (!depth_frame) // Should not happen but if the pipeline is configured differently return; // it might not provide depth and we don't want to crash //Save a reference rs2::frame filtered = depth_frame; // Query frame size (width and height) const int w = depth_frame.as<rs2::video_frame>().get_width(); const int h = depth_frame.as<rs2::video_frame>().get_height(); //Create queued mat containers QueuedMat depthQueueMat; QueuedMat cleanDepthQueueMat; // Create an openCV matrix from the raw depth (CV_16U holds a matrix of 16bit unsigned ints) Mat rawDepthMat(Size(w, h), CV_16U, (void*)depth_frame.get_data()); // Create an openCV matrix for the DepthCleaner instance to write the output to Mat cleanedDepth(Size(w, h), CV_16U); //Run the RGBD depth cleaner instance depthc->operator()(rawDepthMat, cleanedDepth); const unsigned char noDepth = 0; // change to 255, if values no depth uses max value Mat temp, temp2; // Downsize for performance, use a smaller version of depth image (defined in the SCALE_FACTOR macro) Mat small_depthf; resize(cleanedDepth, small_depthf, Size(), SCALE_FACTOR, SCALE_FACTOR); // Inpaint only the masked "unknown" pixels inpaint(small_depthf, (small_depthf == noDepth), temp, 5.0, INPAINT_TELEA); // Upscale to original size and replace inpainted regions in original depth image resize(temp, temp2, cleanedDepth.size()); temp2.copyTo(cleanedDepth, (cleanedDepth == noDepth)); // add to the original signal // Use the copy constructor to copy the cleaned mat if the isDepthCleaning is true cleanDepthQueueMat.img = cleanedDepth; //Use the copy constructor to fill the original depth coming in from the sensr(i.e visualized in RGB 8bit ints) depthQueueMat.img = rawDepthMat; //Push the mats to the queue originalQueue.push(depthQueueMat); filteredQueue.push(cleanDepthQueueMat); } }); Mat filteredDequeuedMat(Size(1280, 720), CV_16UC1); Mat originalDequeuedMat(Size(1280, 720), CV_8UC3); //Main thread function while (waitKey(1) < 0 && cvGetWindowHandle(window_name_source) && cvGetWindowHandle(window_name_filter)){ //If the frame queue is not empty pull a frame out and clean the queue while(!originalQueue.empty()){ originalQueue.front().img.copyTo(originalDequeuedMat); originalQueue.pop(); } while(!filteredQueue.empty()){ filteredQueue.front().img.copyTo(filteredDequeuedMat); filteredQueue.pop(); } Mat coloredCleanedDepth; Mat coloredOriginalDepth; make_depth_histogram(filteredDequeuedMat, coloredCleanedDepth, COLORMAP_JET); make_depth_histogram(originalDequeuedMat, coloredOriginalDepth, COLORMAP_JET); imshow(window_name_filter, coloredCleanedDepth); imshow(window_name_source, coloredOriginalDepth); } // Signal the processing thread to stop, and join stopped = true; processing_thread.join(); return EXIT_SUCCESS; } catch (const rs2::error & e){ std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl; return EXIT_FAILURE; } catch (const std::exception& e){ std::cerr << e.what() << std::endl; return EXIT_FAILURE; }
true
8890379be2b4aaeb884ad6aa1e57fef186bcd1d0
C++
TanmoyPaul1/CSCI235
/BSTree/BSTree.h
UTF-8
571
2.671875
3
[]
no_license
#pragma once #include <iostream> #include "Node.h" class BSTree{ private: Node *root; public: BSTree(); void insert(int d); int search(int value); void deleteNode(int d); Node *deleteNode(Node *n, int d); int treesum(); int treesumHelper(Node *n); int numNodes(); int numNodesHelper(Node *n); int numLeaves(); int numLeavesHelper(Node *n); int nodesum(int d); int height(); int heightHelper(Node *n); std::string get_debug_string(); std::string get_debug_stringHelper(Node *n); void setup(); };
true
0252af8e1f98aa91a26f7b06bc39d3ebf32684e5
C++
sleepy-juan/false-positive-speech-data
/src/fitness/incomprehensibility.hpp
UTF-8
691
2.59375
3
[]
no_license
/* incomprehensibility.hpp - incomprehensibility fitness Created by Sungwoo Jeon Modified by Juan Lee */ #include <string> #include <vector> #include "../wav/wav.hpp" #ifndef __INCOMPREHENSIBILITY_HPP__ #define __INCOMPREHENSIBILITY_HPP__ /* Class incomprehensibility - Wave incomprehensibility */ class Incomprehensibility { private: std::vector<Wav> originals; float _fitness; float min_fitness; char smallest(char A, char B, char C); bool evaluateFitness(int sampleRate, Wav &original, Wav &modified); public: Incomprehensibility(std::vector<Wav> &originals); bool evaluate(int sampleRate, Wav &modified); float fitness(); }; #endif
true
8e0fd819d046f10ecbe643777dad3144f805a7c5
C++
psyzemin/DataStructure
/C/Tree_Array.cpp
UTF-8
377
2.96875
3
[]
no_license
#include "Tree_Array.h" #include<stdio.h> #include<stdlib.h> ATree InitTree(int x) { ATree t = (ATree)malloc(sizeof(struct Tree_Array) + sizeof(struct TreeNode)*x); if (t == NULL) { perror("Out of space!"); } t->nodes = (TNode)malloc(sizeof(TNode)*x); t->num = 0; t->root = 0; t->size = x; return t; } int isEmpty(ATree t) { return t->num == 0; }
true
fa893dba90629fc00105586b2f38f1604b5f2e00
C++
1panpan1/second-filesystem
/project/src/Bitmap.cpp
UTF-8
1,329
2.921875
3
[]
no_license
#include"Bitmap.h" #include"FileSystem.h" #include<cstring> #include<iostream> using namespace std; extern FileSystem g_fileSystem; Bitmap::Bitmap() { bsize = (512 - sizeof(int) * 2) * 8; memset((unsigned char *)bmap, 0, 512 - sizeof(int) * 2); } Bitmap::Bitmap(int _start ,int size) :start(_start) , bsize(size) { memset((unsigned char *)bmap, 0, 512 - sizeof(int) *2); } int Bitmap::get(int pos_index) { //pos_index -= 1; if ((pos_index >> OFFSET) > bsize) return BITMAP_ERRO; else return (bmap[pos_index >> OFFSET] & ( 0x1 << (pos_index & 0x1F))) == 0 ? 0 : 1; } int Bitmap::set(int pos_index) { //pos_index -= 1; int ret = 0; if ((pos_index >> OFFSET) > bsize) ret = BITMAP_ERRO; else ret = bmap[pos_index >> OFFSET] |= (0X1 << (pos_index & 0X1F)); g_fileSystem.updateBitmap(); return ret; } int Bitmap::reset(int pos_index) { //pos_index -= 1; int ret = 0; if ((pos_index >> OFFSET) > bsize) ret = BITMAP_ERRO; else ret = bmap[pos_index >> OFFSET] &= ~(0X1 << (pos_index & 0x1F)); g_fileSystem.updateBitmap(); return ret; } int Bitmap::alloc() { int ret = 0; int i = 0; for (i = this->start; i < this->bsize; i++) { if ((this->get(i)) == 0) { ret = i; this->set(i); break; } } if(i == this->bsize) ret = BITMAP_ERRO; g_fileSystem.updateBitmap(); return ret; }
true
aab1e6f9fde1cf7f0a8999a5f20e566674117014
C++
zzqboy/algorithm
/src/sort/heap_sort.cc
UTF-8
946
3.578125
4
[]
no_license
//author: zzq //堆排序 #include <iostream> void heapAdjust(int heap[], int length, int p_i) { int temp = heap[p_i]; int min_i = 2 * p_i + 1; while(min_i < length) { if((min_i + 1) < length && heap[min_i] > heap[min_i + 1]) min_i++; if(temp < heap[min_i]) break; heap[p_i] = heap[min_i]; p_i = min_i; min_i = 2 * p_i + 1; } heap[p_i] = temp; } void heapSort(int data[], int length) { if(data == NULL || length <= 0) return; for(int i = length/2 - 1; i >= 0; i--) { heapAdjust(data, length, i); } for(int i = length - 1; i >= 0; --i) { std::swap(data[0], data[i]); heapAdjust(data, i, 0); } } int main() { int data[] = {97, 76, 65, 49, 49, 38, 27, 13}; heapSort(data, sizeof(data) / sizeof(data[0])); for(int i = 0; i < sizeof(data)/sizeof(data[0]); i++) { std::cout << data[i] << std::endl; } }
true
5ab79f7e2be383756405f6503f9c60cf773de131
C++
BLumia/MidiUtils
/src/MidiHeader.cpp
UTF-8
978
2.53125
3
[ "BSD-2-Clause" ]
permissive
#include <iostream> #include <string> #include <cstring> #include "midiutils/MidiHeader.hpp" #include "midiutils/MidiUtils.hpp" using namespace std; namespace MidiUtils { MidiHeader::MidiHeader() {} int MidiHeader::read(istream& istream) { std::string rawMThd(14, ' '); istream.read(&rawMThd[0], 14); if (rawMThd.substr(0, 4) != "MThd") { throw "Not a MIDI file!"; } memcpy(&this->header, rawMThd.c_str(), 14); return 0; } int MidiHeader::write(ostream& ostream) { ostream.write((char*)&this->header, 14); return 0; } int MidiHeader::getFormat() const { return byte2_to_uint16(header.midiFormat); } int MidiHeader::getTrackCount() const { return byte2_to_uint16(this->header.midiTrackCnt); } int MidiHeader::getDeltaTime() const { return byte2_to_uint16(this->header.midiDeltaTime); } }
true
5dc43a47e5fdbdbab63bea0e341d85ad8f59fc8b
C++
for-l00p/TestCses
/TestCses/pb_grid_unsolved.cpp
IBM852
2,658
2.859375
3
[]
no_license
#include <iostream> #include <algorithm> #include <string> #include <fstream> #include <vector> #include <set> #include <sstream> #include <chrono> #ifdef MY_INPUT #define FILE_INPUT "input.txt" #define STREAM_IN my_file #define OPEN_IN std::fstream my_file(FILE_INPUT); if (!my_file.good()) { std::cout << "Error opening " << FILE_INPUT; return -1; } #else #define STREAM_IN std::cin #define OPEN_IN #endif typedef long long int ull_type; std::vector<std::string> solutions; int pos; char* current_path; char* grid; #define GRID(X,Y) (grid[(X)+((Y)<<3)]) void move(int x, int y) { if (pos == 7 && current_path[pos - 1] != 'R') { pos--; return; } if (pos == 14 && current_path[pos - 1] != 'U') { pos--; return; } if (pos == 41 && current_path[pos - 1] != 'L') { pos--; return; } if (pos == 42 && current_path[pos - 1] != 'D') { pos--; return; } if (pos == 47 && current_path[pos - 1] != 'D') { pos--; return; } if (x == 0 && y == 6) // Target { if (pos == 48) { auto s = std::string(current_path, pos); solutions.push_back(s); //std::cout << s << " " << solutions.size() << std::endl; } pos--; return; } GRID(x, y) = 1; // Left if (x > 0 && GRID(x - 1, y) == 0) { current_path[pos++] = 'L'; move(x - 1, y); } // Up if (y > 0 && GRID(x, y - 1) == 0) { current_path[pos++] = 'U'; move(x, y - 1); } // Right if (x < 6 && GRID(x + 1, y) == 0) { current_path[pos++] = 'R'; move(x + 1, y); } // Down if (y < 6 && GRID(x, y + 1) == 0) { current_path[pos++] = 'D'; move(x, y + 1); } GRID(x, y) = 0; pos--; } int pbgrid_main() { OPEN_IN; std::string s; STREAM_IN >> s; //std::cout << s; #ifdef MY_INPUT std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); #endif grid = new char[8 * 7]; memset(grid, 0, 8 * 7); pos = 0; current_path = new char[48]; move(0, 0); std::cout << solutions.size() << std::endl; int count = 0; for (const auto& sol : solutions) { bool match = true; for (int i = 0; i < s.length(); i++) if ((s[i] != '?') && s[i] != sol[i]) match = false; if (match) count++; } std::cout << count; // Generer tous les chemins upperleft to lowerleft on 7x7 grid // + match pattern #ifdef MY_INPUT std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); //std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[s]" << std::endl; std::cout << std::endl << "Time difference = " << std::chrono::duration_cast<std::chrono::seconds> (end - begin).count() << " s" << std::endl; #endif return 0; }
true
77231a83631695a984a603250a40e23c5e6be4d8
C++
swardhan/competetive
/eminence/numberTheory/freeCube.cpp
UTF-8
786
2.765625
3
[]
no_license
#include<bits/stdc++.h> #define MAX 1000000 typedef long long ll; using namespace std; int main(){ int t,tc = 1; cin >> t; //Create Array bool isFreeCube[MAX]; isFreeCube[0] = false; for(int i = 1; i < MAX; i++){ isFreeCube[i] = true; } for(int i = 2; i*i*i < MAX; i++){ if(isFreeCube[i]){ for(int j = i*i*i; j < MAX; j+=i*i*i){ isFreeCube[j] = false; } } } int counter = 0; int a[1000000]; for(int i=1; i < MAX; i++){ if(isFreeCube[i]){ counter++; a[i]=counter; }else { a[i]=-1; } } while(t--){ int n; cin >> n; int ans = a[n]; cout << "Case " << tc++ << ": "; if(ans == -1){ cout << "Not Cube Free"; }else { cout << ans; } cout << endl; } }
true
593469a09fcc81c9375e417a30136b19e2643d92
C++
yku/Competition
/TopCoder/srm305/MultiRead.cpp
UTF-8
2,287
3.09375
3
[]
no_license
#include <iostream> #include <sstream> #include <cstring> #include <algorithm> #include <string> #include <vector> using namespace std; class MultiRead { public: int minCycles(string trace, int procs) { int clk = 0; int reads = 0; for(int i = 0; i < trace.size(); i++) { if(trace[i] == 'W') { clk++; if(reads > 0) { while(reads > 0){ clk++; reads -= procs; } reads = 0; } }else { reads++; } } while(reads > 0){ clk++; reads -= procs; } return clk; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "RWWRRR"; int Arg1 = 3; int Arg2 = 4; verify_case(0, Arg2, minCycles(Arg0, Arg1)); } void test_case_1() { string Arg0 = "RWWRRRR"; int Arg1 = 3; int Arg2 = 5; verify_case(1, Arg2, minCycles(Arg0, Arg1)); } void test_case_2() { string Arg0 = "WWWWW"; int Arg1 = 5; int Arg2 = 5; verify_case(2, Arg2, minCycles(Arg0, Arg1)); } void test_case_3() { string Arg0 = "RRRRRRRRRR"; int Arg1 = 4; int Arg2 = 3; verify_case(3, Arg2, minCycles(Arg0, Arg1)); } void test_case_4() { string Arg0 = "RWRRWWRWRWRRRWWRRRRWRRWRRWRRRRRRRRRWRWRWRRRRWRRRRR"; int Arg1 = 4; int Arg2 = 30; verify_case(4, Arg2, minCycles(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { MultiRead ___test; ___test.run_test(-1); } // END CUT HERE
true
789cee6123338ba7848d7c1f84e81ff064503489
C++
Nimmel/x2
/include/Memory.h
UTF-8
10,104
2.703125
3
[]
no_license
#ifndef MemoryManager_h #define MemoryManager_h #include <List.h> #include <Locator.h> #include <def.h> //#include <Kernel.h> #if defined(CODE32) //new & delete AS_MACRO void* operator new(size_t size){return NULL;} AS_MACRO void operator delete(void *p){} //全局方法: placement new和placement delete // Default placement versions of operator new. AS_MACRO void* operator new(size_t, void* __p){ return __p; }; AS_MACRO void* operator new[](size_t, void* __p){ return __p; }; // Default placement versions of operator delete. AS_MACRO void operator delete (void*, void*){}; AS_MACRO void operator delete[](void*, void*){}; #elif defined(CODE64) #include <new> #include <cstdio> #endif /** * This is simple enough,and should not be modified any longer. */ class LinearSourceDescriptor{ public: AS_MACRO LinearSourceDescriptor(); public: AS_MACRO LinearSourceDescriptor(size_t start,size_t limit); //done AS_MACRO ~LinearSourceDescriptor();//done AS_MACRO size_t getStart() const ;//done AS_MACRO size_t getLimit() const ;//done AS_MACRO bool isAllocable() const;//done,always return true; AS_MACRO void setStart(size_t start);//done AS_MACRO void setLimit(size_t limit);//done AS_MACRO bool contains(const LinearSourceDescriptor& b)const;//done AS_MACRO bool contains(size_t start,size_t limit)const;//done /** * 逻辑相等而非全等 */ AS_MACRO bool operator==(const LinearSourceDescriptor& b)const;//done AS_MACRO bool operator!=(const LinearSourceDescriptor& b)const;//done protected: size_t start; size_t limit; }; class MemoryDescriptor:public LinearSourceDescriptor{ public: AS_MACRO MemoryDescriptor(size_t start,size_t limit,bool allocable=true);//done AS_MACRO ~MemoryDescriptor();//done AS_MACRO bool isAllocable()const; //此方法仅对同层以及上层的节点有意义 done AS_MACRO void setAllocable(bool allocable);//这是指是否用于父类的分配,还是用于自己的分配 done AS_MACRO bool operator==(const MemoryDescriptor& b)const;//done AS_MACRO bool operator!=(const MemoryDescriptor& b)const;//done //const static MemoryDescriptor NULL_DESCRIPTOR; protected: bool allocable; }; /** * What this manager manages must provide a way to get start and limit. * There are two types of LinearSourceManager * 1.All nodes inside are equal to each other . * If the allocated nodes have specific use,they are different from each other * 2. * It does not assume the managed node is a subclass of a certain class or not.It just assume it provides some methods that is required by it. * Remember that if the structure of a class is not really necessary,do not use extend. * * _NodeAllocator must provide a function for condition that space is not enough * */ template <class _LinearSourceDescriptor,template <class> class _NodeAllocator> class LinearSourceManager:public LocateableLinkedList<_LinearSourceDescriptor,Locator<_LinearSourceDescriptor>::DISCARD,_NodeAllocator >{ public: typedef LinearSourceManager<_LinearSourceDescriptor,_NodeAllocator> This; typedef LocateableLinkedList<_LinearSourceDescriptor,Locator<_LinearSourceDescriptor>::DISCARD,_NodeAllocator > Father; typedef ListNode<_LinearSourceDescriptor> NodeType; LinearSourceManager(); public: LinearSourceManager(_NodeAllocator< ListNode<_LinearSourceDescriptor> >*smm,size_t start,size_t size);//done ~LinearSourceManager();//done AS_MACRO const _LinearSourceDescriptor & getSpace()const; //These are for continuous memory allocation void* mnew(size_t start,size_t size);//done void* mnew(size_t size);//done void* extend(size_t start,size_t size,int extsize,char *realBase=NULL,bool moveData=false); void mdelete(void* p,size_t size);//done /** * Currently,this manager does not support withdrawing a pointer without size,so this is deprecated or incomplete */ DEPRECATED void mdelete(void *p);//done //These are for linked memory allocation /** * The 'eachSectionExtraSize' is the extra size for each section. */ bool mnewLinked(size_t size,LinkedList<LinearSourceDescriptor,_NodeAllocator> &list,size_t eachSectionExtraSize=0);//list must be empty void mdeleteLinked(LinkedList<LinearSourceDescriptor,_NodeAllocator> &ist); protected: _LinearSourceDescriptor allocOutNode(ListNode<_LinearSourceDescriptor> *avlNode,size_t start,size_t len);//done /** * This method is not needed */ DEPRECATED void withdrawNode(ListNode<_LinearSourceDescriptor> *exactNode);//done bool checkRange(size_t start,size_t size);//done bool checkRange(size_t start);//done static bool checkPrevious(ListNode<_LinearSourceDescriptor> *prev, size_t start);//done static bool checkNext(ListNode<_LinearSourceDescriptor>* nxt, size_t start,size_t len);//done protected: _LinearSourceDescriptor space; }; /** *类的实现: * 大量使用链表这种结构 * 也使用树这种结构 * 资源的分配很适合使用树来描述 * MemoryManager mm(34*512,0xffff); MemoryManager mmIDT,mmGDT; mmIDT=mm.allocFree(0,50*8); //base作为零基址 mmGDT=mm.allocFree(50*8,100*8); * * 从哪个管理器上分配的空间,就由哪个管理器负责,以体现层级关系 * 本质上,所有的管理器都是共用一棵树 * * change log: * 2017-02-26 03:11:12: 分配的管理器只有在其上调用了alloc/new函数之后,才会向下复制自己并把alloc标志位置为1,在此基础上进行分配。下级的节点不关心上级的状态。因此添加“分配时复制”函数 * */ template <template <class> class _DescriptorAllocator> class MemoryManager:public Tree<MemoryDescriptor,_DescriptorAllocator>{ public: typedef MemoryManager<_DescriptorAllocator> This; typedef TreeNode<MemoryDescriptor> NodeType; typedef SimpleMemoryManager<NodeType> SimpleAllocator; public: MemoryManager()=default; MemoryManager(_DescriptorAllocator<TreeNode<MemoryDescriptor> > *smm);//done MemoryManager(_DescriptorAllocator<TreeNode<MemoryDescriptor> > *smm,size_t start,size_t len,bool fatherAllocable=1); //以典型的内存描述建立管理器,但这不是唯一的初始化方式,因为开始和结束可以由内部节点指定,实际上开始和结束可以完全没有必要在初始化中指定 //done ~MemoryManager(); //注意:不能在父类管理器中 MemoryManager<_DescriptorAllocator> allocFreeStart(size_t start,size_t len); //从父级管理器衍生,done MemoryManager<_DescriptorAllocator> allocFree(size_t len);//done TreeNode<MemoryDescriptor> *copyOnAllocation(TreeNode<MemoryDescriptor> *head);//复制后的allocable标志位与父节点相反,这从根本上保证了内存的一致性 done //operator new and delete void* mnew(size_t start,size_t size);//done void* mnew(size_t size);//done void* mnewAlign(size_t size,size_t alignment); /* * if returned true,then the it worked * else not worked,nothing effected * * Note: if extsize = 0,do nothing * else if extsize < 0,trim the original allocated space,if extsize+size=0,then delete the original memory * else realloc new space. * Note: if realBase=0,it still works.The realBase is used to memory move. */ void* extend(size_t start,size_t size,int extsize,char *realBase=NULL,bool moveData=false);//similar to realloc void mdelete(void* p,size_t size);//查找p开始的连续个大小,看是否能满足要求,使用locateForDelete,withdrawNode协同完成,done void mdelete(void *p);//done void withdrawToParent(); //回收到父级管理器,当其撤销的时候,必须将子类移动到父类的子类中,done //=========getter & setter AS_MACRO size_t getBase()const; AS_MACRO size_t getLimit()const; //===support for List static TreeNode<MemoryDescriptor> *findFirstStart(TreeNode<MemoryDescriptor>* loc,size_t start,size_t len);//done static TreeNode<MemoryDescriptor> *findFirstLen(TreeNode<MemoryDescriptor>* loc,size_t len);//done static TreeNode<MemoryDescriptor>*findFirstLenAlign(TreeNode<MemoryDescriptor>* loc, size_t len,size_t &extra,size_t alignment); static TreeNode<MemoryDescriptor> *locateForInsertation(TreeNode<MemoryDescriptor>* loc,TreeNode<MemoryDescriptor> *son); static TreeNode<MemoryDescriptor> *locateForDelete(TreeNode<MemoryDescriptor>* loc,size_t start,size_t len,bool allocable);//done static TreeNode<MemoryDescriptor>* locateForDeleteStart(TreeNode<MemoryDescriptor>* loc,size_t start,bool allocable);//done /** * 1 success * 0 failed */ static int addToTree(TreeNode<MemoryDescriptor> *root,TreeNode<MemoryDescriptor> *son); static TreeNode<MemoryDescriptor> *nextAllocable(TreeNode<MemoryDescriptor> *node);//done int isNullManager();//done void setNull();//done protected: TreeNode<MemoryDescriptor> * allocOutNode(TreeNode<MemoryDescriptor> *avlNode,size_t start,size_t len);//done void withdrawNode(TreeNode<MemoryDescriptor> *exactNode);//done /** * Note: extsize is size_t,it cannot be less than 0.if it is 0,then returned false. * if not found,return false * if found at original,return true * if found at somewhere not corrupted with the original,return true+1 */ char findExtend(size_t start,size_t size,size_t extsize,TreeNode<MemoryDescriptor> * &rtnode)const; protected: //SimpleMemoryManager<TreeNode<MemoryDescriptor> > *smm; //the base class already has one private: }; //================High Level Memory Allocation==================== /** * Just a wrapper of MemoryManager.It directly interact with theKernel,and cast whatever it returns */ template <class T> class HighLevelSimpleMemoryManager{ }; /***************CLASS DEFINITION END***********************/ #endif //Memory_h__
true
14ab951c8906d0a897ca3fbace3c87b3c6797acb
C++
Ruthietta/Infinite-coders-competition
/Task 4/Solution2/fibonacci.cpp
UTF-8
442
3.1875
3
[]
no_license
#include "fibonacci.hpp" long long fibRecursive(int n) { if (n <= 1) return n; return fibRecursive(n - 1) + fibRecursive(n - 2); } long long fibIterative(int n) { if (n <= 1) return n; long long last = 1; long long nextToLast = 1; long long result = 1; for (int i = 2; i < n; ++i) { result = last + nextToLast; nextToLast = last; last = result; } return result; }
true
0d33f5c64d9d2fadf6e0eaa381bc15b982d61c0f
C++
DosDevs/zoom-zoom
/newfs/Octet.h
UTF-8
444
2.75
3
[ "BSD-3-Clause" ]
permissive
#ifndef OCTET_H__INCLUDED #define OCTET_H__INCLUDED #include <string> namespace NewFs { using std::string; class Octet { private: unsigned char _value; public: Octet(unsigned char value = 0): _value(value) {} operator unsigned char() const { return int(_value) < 256? _value: 255; } }; // Octet } #endif // OCTET_H__INCLUDED
true
01dedad1a909f4700a4d716638129d1ffc8a3579
C++
sirdyf/ENEV_2_261
/TESTS/NETWORK/client/client/client.cpp
UTF-8
971
2.5625
3
[]
no_license
// client.cpp : Defines the entry point for the console application. // #include <conio.h> #include <iostream> #include "tNetworkClient.h" using namespace std; class tMain : public tINetworkClient{ int FormatDataForSend(char*){return 0;} void ClientReciveData(const char* ,int){;} }; int main(int argc, char* argv[]){ boost::intrusive_ptr<tMain> tstMain(new tMain); tNetworkClient tstClient; cout << "\t\tStart program.\n\n"; tstClient.Init(tstMain); cout << "Run network engine...\n"; tstClient.Run(); cout << "Wait 5 sec..\n"; ::Sleep(5000); std::cout << "\n\tResult:\n Packet Send:" << tstClient._mNetStat.GetNumPacketSend() << " Packed recv:" << tstClient._mNetStat.GetNumPacketRecv() << " Total:" << tstClient._mNetStat.GetNumPackets() << "\n\t\tTrafic:" << tstClient._mNetStat.GetTrafic()<< "Kbit in sec\n"; cout << "Stop network engine.\n"; tstClient.Stop(); tstClient.Release(); cout << "\n\n\t\tEnd program.\n"; getch(); return 0; }
true
984599d728ee676457f1df5550d383ca89ca0256
C++
Nub-Team/Simple_Production
/CUDA_Nub/Image_Processing/src/main.cpp
UTF-8
1,398
2.828125
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <string> #include "../include/imageProcess.h" int main(int argc, char *argv[]){ if (argc < 3) std::cerr << "Usage: " << argv[0] << " <operation> <inputfile1> [inputfile2]" << std::endl; else{ std::string operation(argv[1]); std::string input_file(argv[2]); std::string other_file; if (argc > 3) other_file = std::string(argv[3]); std::string output_file = "output/output.png"; if (operation == "grayscale") convert_grayscale(input_file, output_file); else if (operation == "blur") gaussian_blur(input_file, output_file); else if (operation == "tonemap") tonemap_HDR(input_file, output_file); else if (operation == "redeye") if (argc > 3) remove_redeye(input_file, other_file, output_file); else std::cerr << "redeye requires a second input template file" << std::endl; else if (operation == "clone") if (argc > 3) seamless_clone(input_file, other_file, output_file); else std::cerr << "clone requires a second input source file" << std::endl; else std::cerr << "Unknown operation - options: grayscale, blur, tonemap, redeye, clone" << std::endl; } }
true
5ddd1b31fce660fc9ff0611dbf11cc3fc70b156f
C++
mmorri22/cse20312
/Lecture19/include/Graph1.h
UTF-8
1,033
3.453125
3
[]
no_license
#ifndef GRAPH1_H #define GRAPH1_H #include "Vertex2.h" #include "DynArr.h" #include <iostream> template<class T> class Graph{ private: DynArr< Vertex< T > > vertices; // Adjacency Lisy public: // Constructor Graph( ) : vertices() {} // Add a vertex prior to any edges void add_vertex( T vertexData ){ Vertex<T> theVertex( vertexData ); vertices.push_back( theVertex ); } // Add Edge from Origin to Destination, with weight void add_edge(unsigned int origin, unsigned int destin, int weight ){ if( origin < vertices.length() && destin < vertices.length() ){ vertices[origin].add_edge( destin, weight ); } } // Overloaded Operator friend std::ostream& operator<<( std::ostream& output, const Graph<T>& theGraph ){ for( unsigned int iter = 0; iter < theGraph.vertices.length(); iter++ ){ output << iter << ": " << theGraph.vertices[ iter ] << std::endl; } return output; } }; #endif
true
1fff9b8dc685b2a6f64791a49b5a64af37fddefe
C++
pmdp/P3_1_IG
/Chasis.cpp
UTF-8
11,854
2.875
3
[]
no_license
/* * Chasis.cpp * * Created on: Jan 26, 2016 * Author: pepc */ #include "Chasis.h" Chasis::Chasis() { numTexturas=1; colourMaterial = true; //Crea Malla del Chasis numVertices = 42; numCaras = 27; numNormales = numCaras; vertice = new PV3D*[numVertices]; normal = new PV3D*[numNormales]; cara = new Cara*[numCaras]; //Vertices vertice[0] = new PV3D(-11.0, 0.0, 4.0, 1); vertice[1] = new PV3D(-8.0, 0.0, 4.0, 1); vertice[2] = new PV3D(-7.5, 1.2, 4.0, 1); vertice[3] = new PV3D(-7.5, 3.0, 4.0, 1); vertice[4] = new PV3D(-11.0, 3.0, 4.0, 1); vertice[5] = new PV3D(-5.5, 1.2, 4.0, 1); vertice[6] = new PV3D(-5.5, 3.0, 4.0, 1); vertice[7] = new PV3D(-5.0, 0.0, 4.0, 1); vertice[8] = new PV3D(-3.0, 0.0, 4.0, 1); vertice[9] = new PV3D(-3.0, 3.0, 4.0, 1); vertice[10] = new PV3D(3.0, 6.0, 4.0, 1); vertice[11] = new PV3D(-1.0, 6.0, 4.0, 1); vertice[12] = new PV3D(3.0, 0.0, 4.0, 1); vertice[13] = new PV3D(5.0, 0.0, 4.0, 1); vertice[14] = new PV3D(5.5, 1.2, 4.0, 1); vertice[15] = new PV3D(7.5, 1.2, 4.0, 1); vertice[16] = new PV3D(7.5, 3.0, 4.0, 1); vertice[17] = new PV3D(6.5, 6.0, 4.0, 1); vertice[18] = new PV3D(8.0, 0.0, 4.0, 1); vertice[19] = new PV3D(11.0, 0.0, 4.0, 1); vertice[20] = new PV3D(11.0, 3.0, 4.0, 1); vertice[21] = new PV3D(-11.0, 0.0, -4.0, 1); vertice[22] = new PV3D(-11.0, 3.0, -4.0, 1); vertice[23] = new PV3D(-7.5, 3.0, -4.0, 1); vertice[24] = new PV3D(-7.5, 1.2, -4.0, 1); vertice[25] = new PV3D(-8.0, 0.0, -4.0, 1); vertice[26] = new PV3D(-5.5, 1.2, -4.0, 1); vertice[27] = new PV3D(-5.5, 3.0, -4.0, 1); vertice[28] = new PV3D(-5.0, 0.0, -4.0, 1); vertice[29] = new PV3D(-3.0, 0.0, -4.0, 1); vertice[30] = new PV3D(-3.0, 3.0, -4.0, 1); vertice[31] = new PV3D(-1.0, 6.0, -4.0, 1); vertice[32] = new PV3D(3.0, 6.0, -4.0, 1); vertice[33] = new PV3D(3.0, 0.0, -4.0, 1); vertice[34] = new PV3D(5.0, 0.0, -4.0, 1); vertice[35] = new PV3D(5.5, 1.2, -4.0, 1); vertice[36] = new PV3D(7.5, 1.2, -4.0, 1); vertice[37] = new PV3D(7.5, 3.0, -4.0, 1); vertice[38] = new PV3D(6.5, 6.0, -4.0, 1); vertice[39] = new PV3D(11.0, 3.0, -4.0, 1); vertice[40] = new PV3D(11.0, 0.0, -4.0, 1); vertice[41] = new PV3D(8.0, 0.0, -4.0, 1); //Cara 0 VerticeNormal** vn0 = new VerticeNormal*[5]; vn0[0] = new VerticeNormal(0, 0); vn0[1] = new VerticeNormal(1, 0); vn0[2] = new VerticeNormal(2, 0); vn0[3] = new VerticeNormal(3, 0); vn0[4] = new VerticeNormal(4, 0); cara[0] = new Cara(5, vn0); PV3D* v0 = CalculoVectorNormalPorNewell(cara[0]); //Newell normal[0] = v0; //Cara 1 VerticeNormal** vn1 = new VerticeNormal*[4]; vn1[0] = new VerticeNormal(2, 1); vn1[1] = new VerticeNormal(5, 1); vn1[2] = new VerticeNormal(6, 1); vn1[3] = new VerticeNormal(3, 1); cara[1] = new Cara(4, vn1); PV3D* v1 = CalculoVectorNormalPorNewell(cara[1]); //Newell normal[1] = v1; //Cara 2 VerticeNormal** vn2 = new VerticeNormal*[5]; vn2[0] = new VerticeNormal(5, 2); vn2[1] = new VerticeNormal(7, 2); vn2[2] = new VerticeNormal(8, 2); vn2[3] = new VerticeNormal(9, 2); vn2[4] = new VerticeNormal(6, 2); cara[2] = new Cara(5, vn2); PV3D* v2 = CalculoVectorNormalPorNewell(cara[2]); //Newell normal[2] = v2; //Cara 3 VerticeNormal** vn3 = new VerticeNormal*[7]; vn3[0] = new VerticeNormal(12, 3); vn3[1] = new VerticeNormal(13, 3); vn3[2] = new VerticeNormal(14, 3); vn3[3] = new VerticeNormal(15, 3); vn3[4] = new VerticeNormal(16, 3); vn3[5] = new VerticeNormal(17, 3); vn3[6] = new VerticeNormal(10, 3); cara[3] = new Cara(7, vn3); PV3D* v3 = CalculoVectorNormalPorNewell(cara[3]); //Newell normal[3] = v3; //Cara 4 VerticeNormal** vn4 = new VerticeNormal*[5]; vn4[0] = new VerticeNormal(15, 4); vn4[1] = new VerticeNormal(18, 4); vn4[2] = new VerticeNormal(19, 4); vn4[3] = new VerticeNormal(20, 4); vn4[4] = new VerticeNormal(16, 4); cara[4] = new Cara(5, vn4); PV3D* v4 = CalculoVectorNormalPorNewell(cara[4]); //Newell normal[4] = v4; //Cara 5 VerticeNormal** vn5 = new VerticeNormal*[5]; vn5[0] = new VerticeNormal(21, 5); vn5[1] = new VerticeNormal(22, 5); vn5[2] = new VerticeNormal(23, 5); vn5[3] = new VerticeNormal(24, 5); vn5[4] = new VerticeNormal(25, 5); cara[5] = new Cara(5, vn5); PV3D* v5 = CalculoVectorNormalPorNewell(cara[5]); //Newell normal[5] = v5; //Cara 6 VerticeNormal** vn6 = new VerticeNormal*[4]; vn6[0] = new VerticeNormal(24, 6); vn6[1] = new VerticeNormal(23, 6); vn6[2] = new VerticeNormal(27, 6); vn6[3] = new VerticeNormal(26, 6); cara[6] = new Cara(4, vn6); PV3D* v6 = CalculoVectorNormalPorNewell(cara[6]); //Newell normal[6] = v6; //Cara 7 VerticeNormal** vn7 = new VerticeNormal*[5]; vn7[0] = new VerticeNormal(29, 7); vn7[1] = new VerticeNormal(28, 7); vn7[2] = new VerticeNormal(26, 7); vn7[3] = new VerticeNormal(27, 7); vn7[4] = new VerticeNormal(30, 7); cara[7] = new Cara(5, vn7); PV3D* v7 = CalculoVectorNormalPorNewell(cara[7]); //Newell normal[7] = v7; //Cara 8 VerticeNormal** vn8 = new VerticeNormal*[7]; vn8[0] = new VerticeNormal(33, 8); vn8[1] = new VerticeNormal(32, 8); vn8[2] = new VerticeNormal(38, 8); vn8[3] = new VerticeNormal(37, 8); vn8[4] = new VerticeNormal(36, 8); vn8[5] = new VerticeNormal(35, 8); vn8[6] = new VerticeNormal(34, 8); cara[8] = new Cara(7, vn8); PV3D* v8 = CalculoVectorNormalPorNewell(cara[8]); //Newell normal[8] = v8; //Cara 9 VerticeNormal** vn9 = new VerticeNormal*[5]; vn9[0] = new VerticeNormal(40, 9); vn9[1] = new VerticeNormal(41, 9); vn9[2] = new VerticeNormal(36, 9); vn9[3] = new VerticeNormal(37, 9); vn9[4] = new VerticeNormal(39, 9); cara[9] = new Cara(5, vn9); PV3D* v9 = CalculoVectorNormalPorNewell(cara[9]); //Newell normal[9] = v9; //Cara 10 VerticeNormal** vn10 = new VerticeNormal*[8]; vn10[0] = new VerticeNormal(4, 10); vn10[1] = new VerticeNormal(3, 10); vn10[2] = new VerticeNormal(6, 10); vn10[3] = new VerticeNormal(9, 10); vn10[4] = new VerticeNormal(30, 10); vn10[5] = new VerticeNormal(27, 10); vn10[6] = new VerticeNormal(23, 10); vn10[7] = new VerticeNormal(22, 10); cara[10] = new Cara(8, vn10); PV3D* v10 = CalculoVectorNormalPorNewell(cara[10]); //Newell normal[10] = v10; //Cara 11 VerticeNormal** vn11 = new VerticeNormal*[4]; vn11[0] = new VerticeNormal(9, 11); vn11[1] = new VerticeNormal(11, 11); vn11[2] = new VerticeNormal(31, 11); vn11[3] = new VerticeNormal(30, 11); cara[11] = new Cara(4, vn11); PV3D* v11 = CalculoVectorNormalPorNewell(cara[11]); //Newell normal[11] = v11; //Cara 12 VerticeNormal** vn12 = new VerticeNormal*[4]; vn12[0] = new VerticeNormal(11, 12); vn12[1] = new VerticeNormal(10, 12); vn12[2] = new VerticeNormal(32, 12); vn12[3] = new VerticeNormal(31, 12); cara[12] = new Cara(4, vn12); PV3D* v12 = CalculoVectorNormalPorNewell(cara[12]); //Newell normal[12] = v12; //Cara 13 VerticeNormal** vn13 = new VerticeNormal*[4]; vn13[0] = new VerticeNormal(10, 13); vn13[1] = new VerticeNormal(17, 13); vn13[2] = new VerticeNormal(38, 13); vn13[3] = new VerticeNormal(32, 13); cara[13] = new Cara(4, vn13); PV3D* v13 = CalculoVectorNormalPorNewell(cara[13]); //Newell normal[13] = v13; //Cara 14 VerticeNormal** vn14 = new VerticeNormal*[4]; vn14[0] = new VerticeNormal(17, 14); vn14[1] = new VerticeNormal(16, 14); vn14[2] = new VerticeNormal(37, 14); vn14[3] = new VerticeNormal(38, 14); cara[14] = new Cara(4, vn14); PV3D* v14 = CalculoVectorNormalPorNewell(cara[14]); //Newell normal[14] = v14; //Cara 15 VerticeNormal** vn15 = new VerticeNormal*[4]; vn15[0] = new VerticeNormal(16, 15); vn15[1] = new VerticeNormal(20, 15); vn15[2] = new VerticeNormal(39, 15); vn15[3] = new VerticeNormal(37, 15); cara[15] = new Cara(4, vn15); PV3D* v15 = CalculoVectorNormalPorNewell(cara[15]); //Newell normal[15] = v15; //Cara 16 VerticeNormal** vn16 = new VerticeNormal*[4]; vn16[0] = new VerticeNormal(0, 16); vn16[1] = new VerticeNormal(1, 16); vn16[2] = new VerticeNormal(25, 16); vn16[3] = new VerticeNormal(21, 16); cara[16] = new Cara(4, vn16); PV3D* v16 = CalculoVectorNormalPorNewell(cara[16]); //Newell normal[16] = v16; //Cara 17 VerticeNormal** vn17 = new VerticeNormal*[4]; vn17[0] = new VerticeNormal(1, 17); vn17[1] = new VerticeNormal(2, 17); vn17[2] = new VerticeNormal(24, 17); vn17[3] = new VerticeNormal(25, 17); cara[17] = new Cara(4, vn17); PV3D* v17 = CalculoVectorNormalPorNewell(cara[17]); //Newell normal[17] = v17; //Cara 18 VerticeNormal** vn18 = new VerticeNormal*[4]; vn18[0] = new VerticeNormal(2, 18); vn18[1] = new VerticeNormal(5, 18); vn18[2] = new VerticeNormal(26, 18); vn18[3] = new VerticeNormal(24, 18); cara[18] = new Cara(4, vn18); PV3D* v18 = CalculoVectorNormalPorNewell(cara[18]); //Newell normal[18] = v18; //Cara 19 VerticeNormal** vn19 = new VerticeNormal*[4]; vn19[0] = new VerticeNormal(5, 19); vn19[1] = new VerticeNormal(7, 19); vn19[2] = new VerticeNormal(28, 19); vn19[3] = new VerticeNormal(26, 19); cara[19] = new Cara(4, vn19); PV3D* v19 = CalculoVectorNormalPorNewell(cara[19]); //Newell normal[19] = v19; //Cara 20 VerticeNormal** vn20 = new VerticeNormal*[8]; vn20[0] = new VerticeNormal(7, 20); vn20[1] = new VerticeNormal(8, 20); vn20[2] = new VerticeNormal(12, 20); vn20[3] = new VerticeNormal(13, 20); vn20[4] = new VerticeNormal(34, 20); vn20[5] = new VerticeNormal(33, 20); vn20[6] = new VerticeNormal(29, 20); vn20[7] = new VerticeNormal(28, 20); cara[20] = new Cara(8, vn20); PV3D* v20 = CalculoVectorNormalPorNewell(cara[20]); //Newell normal[20] = v20; //Cara 21 VerticeNormal** vn21 = new VerticeNormal*[4]; vn21[0] = new VerticeNormal(13, 21); vn21[1] = new VerticeNormal(14, 21); vn21[2] = new VerticeNormal(35, 21); vn21[3] = new VerticeNormal(34, 21); cara[21] = new Cara(4, vn21); PV3D* v21 = CalculoVectorNormalPorNewell(cara[21]); //Newell normal[21] = v21; //Cara 22 VerticeNormal** vn22 = new VerticeNormal*[4]; vn22[0] = new VerticeNormal(14, 22); vn22[1] = new VerticeNormal(15, 22); vn22[2] = new VerticeNormal(36, 22); vn22[3] = new VerticeNormal(35, 22); cara[22] = new Cara(4, vn22); PV3D* v22 = CalculoVectorNormalPorNewell(cara[22]); //Newell normal[22] = v22; //Cara 23 VerticeNormal** vn23 = new VerticeNormal*[4]; vn23[0] = new VerticeNormal(15, 23); vn23[1] = new VerticeNormal(18, 23); vn23[2] = new VerticeNormal(41, 23); vn23[3] = new VerticeNormal(36, 23); cara[23] = new Cara(4, vn23); PV3D* v23 = CalculoVectorNormalPorNewell(cara[23]); //Newell normal[23] = v23; //Cara 24 VerticeNormal** vn24 = new VerticeNormal*[4]; vn24[0] = new VerticeNormal(18, 24); vn24[1] = new VerticeNormal(19, 24); vn24[2] = new VerticeNormal(40, 24); vn24[3] = new VerticeNormal(41, 24); cara[24] = new Cara(4, vn24); PV3D* v24 = CalculoVectorNormalPorNewell(cara[24]); //Newell normal[24] = v24; //Cara 25 VerticeNormal** vn25 = new VerticeNormal*[4]; vn25[0] = new VerticeNormal(0, 25); vn25[1] = new VerticeNormal(4, 25); vn25[2] = new VerticeNormal(22, 25); vn25[3] = new VerticeNormal(21, 25); cara[25] = new Cara(4, vn25); PV3D* v25 = CalculoVectorNormalPorNewell(cara[25]); //Newell normal[25] = v25; //Cara 26 VerticeNormal** vn26 = new VerticeNormal*[4]; vn26[0] = new VerticeNormal(40, 26); vn26[1] = new VerticeNormal(39, 26); vn26[2] = new VerticeNormal(20, 26); vn26[3] = new VerticeNormal(19, 26); cara[26] = new Cara(4, vn26); PV3D* v26 = CalculoVectorNormalPorNewell(cara[26]); //Newell normal[26] = v26; } Chasis::~Chasis() { // TODO Auto-generated destructor stub }
true
7eeec0a382b2212f78e6f8b732402ab17f169586
C++
CJHMPower/Fetch_Leetcode
/data/Submission/526 Beautiful Arrangement/Beautiful Arrangement_1.cpp
UTF-8
882
2.765625
3
[]
no_license
//-*- coding:utf-8 -*- // Generated by the Fetch-Leetcode project on the Github // https://github.com/CJHMPower/Fetch-Leetcode/ // 526 Beautiful Arrangement // https://leetcode.com//problems/beautiful-arrangement/description/ // Fetched at 2018-07-24 // Submitted 3 months, 1 week ago // Runtime: 140 ms // This solution defeats 17.78% cpp solutions class Solution { public: int helper(int start, int N, vector<bool>& used) { if (start > N) { return 1; } int ret = 0; for (int i = 1; i <= N; i++) { if (used[i] == false && (i % start == 0 || start % i == 0)) { used[i] = true; ret += helper(start + 1, N, used); used[i] = false; } } return ret; } int countArrangement(int N) { vector<bool> nums; for (int i = 0; i <= N; i++) { nums.push_back(false); } return helper(1, N, nums); } };
true
cbe292282890325691e57a4aa40c7864509bdab4
C++
Nickchooshin/HUGP2_1week
/PC/Project-FW/DataLoader.cpp
UTF-8
2,979
3.1875
3
[]
no_license
#include "DataLoader.h" #include <string> CDataLoader::CDataLoader() : m_pFile(NULL) { } CDataLoader::~CDataLoader() { CloseData() ; } const bool CDataLoader::OpenData(char *filepath) { if(m_pFile!=NULL) return false ; m_pFile = fopen(filepath, "r") ; if(m_pFile==NULL) return false ; return true ; } const bool CDataLoader::CloseData() { if(m_pFile==NULL) return false ; fclose(m_pFile) ; m_pFile = NULL ; return true ; } const bool CDataLoader::GetItem(char *item) { std::string data="" ; char key=NULL ; bool comment=false ; bool bracket=false ; while(1) { key = fgetc(m_pFile) ; if(key==EOF) break ; if(comment) { if(key==10) comment = false ; } else if(key=='#') { comment = true ; } else if(key==10 || key==' ') { continue ; } else { if(!bracket && key=='<') { bracket = true ; } else if(bracket) { if(key=='>') break ; if(key>='a' && key<='z') key -= 32 ; char temp[] = { key, NULL } ; data.append(temp) ; } } } if(key==EOF && data.empty()) return false ; strcpy(item, data.c_str()) ; return true ; } const bool CDataLoader::GetCommand(char *command) { std::string data="" ; char key=NULL ; bool comment=false ; while(1) { key = fgetc(m_pFile) ; if(key==EOF) break ; if(comment) { if(key==10) comment = false ; } else if(key=='#') { comment = true ; } else if(key==10 || key==' ') { if(data=="") continue ; else break ; } else { if(key>='a' && key<='z') key -= 32 ; char temp[] = { key, NULL } ; data.append(temp) ; } } if(key==EOF && data.empty()) return false ; strcpy(command, data.c_str()) ; return true ; } void CDataLoader::GetString(char *str) { std::string data="" ; char key=NULL ; bool blank=true ; bool quotation_mark=false ; while(1) { key = fgetc(m_pFile) ; if(key==EOF) break ; if(!quotation_mark && key=='\"') { quotation_mark = true ; } else if(quotation_mark) { if(key=='\"') break ; char temp[] = { key, NULL } ; data.append(temp) ; } } strcpy(str, data.c_str()) ; } void CDataLoader::GetValue(int &value) { std::string data="" ; char key=NULL ; bool blank=true ; while(1) { key = fgetc(m_pFile) ; if(key==EOF) break ; if(blank && (key!=10 && key!=' ' && key!=',')) blank = false ; if(!blank) { if(key==10 || key==' ' || key==',') break ; char temp[] = { key, NULL } ; data.append(temp) ; } } value = atoi(data.c_str()) ; } void CDataLoader::GetValue(float &value) { std::string data="" ; char key=NULL ; bool blank=true ; while(1) { key = fgetc(m_pFile) ; if(key==EOF) break ; if(blank && (key!=10 && key!=' ' && key!=',')) blank = false ; if(!blank) { if(key==10 || key==' ' || key==',') break ; char temp[] = { key, NULL } ; data.append(temp) ; } } value = (float)strtod(data.c_str(), NULL) ; }
true
bf1a530b3934fb40fa86dac7bafa2552c6d7b478
C++
jaylenjf34/CS202
/Prog3nHashTable/table.cpp
UTF-8
11,289
3.53125
4
[]
no_license
#include "table.h" table :: table () { hash_table_size = 60001; // set size of hash table hash_table = new node * [hash_table_size]; // allocate hash table for(int i = 0; i < hash_table_size ; ++i) // initialize each element int table to NULL { hash_table[i] = NULL; } } input :: input () { // initialize input1 = NULL; input2 = NULL; input3 = NULL; input4 = NULL; input5 = NULL; } node :: node () { // initialize next = NULL; } concert :: concert () { // initalize band = NULL; event = NULL; date = NULL; time = NULL; price = NULL; } /* cleans up the object so previous are not a problem when grabbing information from the user. */ void input :: clean (void) { if(input1 != NULL) { delete [] input1; input1 = NULL; } if(input2 != NULL) { delete [] input2; input2 = NULL; } if(input3 != NULL) { delete [] input3; input3 = NULL; } if(input4 != NULL) { delete [] input4; input4 = NULL; } if(input5 != NULL) { delete [] input5; input5 = NULL; } return; } /* This funtion is for the concert struct and siply outputs the information stored in the the dynamic arrays of the object */ int concert :: display (void) const { if(band == NULL) // if there is nothing stored return 0; cout << " Artist: " << band << endl; cout << " Description: " << event << endl; cout << " Date: " << date << endl; cout << " Time: " << time << endl; cout << " Price: " << price << endl; return 1; } /* this function allocates the details for the object by passing in a object of input into the function. first it cleans the data in struct your allocating data into, then it copies details from entry into the concert object. */ int concert :: create_event (const input & entry) { clean_junk(); // clean up junk values band = new char [strlen(entry.input1) + 1]; strcpy(band, entry.input1); event = new char [strlen(entry.input2) + 1]; strcpy(event, entry.input2); date = new char [strlen(entry.input3) + 1]; strcpy(date, entry.input3); time = new char [strlen(entry.input4) + 1]; strcpy(time, entry.input4); price = new char [strlen(entry.input5) + 1]; strcpy(price, entry.input5); return 1; }; /* This functio is used for copying data into the objects in the table, as well as hard copying. this is used ervytime we add an element to our list or retrieve an element. copy_from is a concert element tat is passed in that is used to copy from. */ int concert :: copy_concert(const concert & copy_from) { if(!copy_from.band) // if there is no data in copy_from { return 0; } // gets rid of junk values clean_junk(); band = new char [strlen(copy_from.band) + 1]; strcpy(band, copy_from.band); event = new char [strlen(copy_from.event) + 1]; strcpy(event, copy_from.event); date = new char [strlen(copy_from.date) + 1]; strcpy(date, copy_from.date); time = new char [strlen(copy_from.time) + 1]; strcpy(time, copy_from.time); price = new char [strlen(copy_from.price) + 1]; strcpy(price, copy_from.price); return 1; } /* Cleans up previous entries inside of the concert object. checks to see if they are not null, then deletes the memory and the sets it to NULL. */ void concert :: clean_junk(void) { if(band != NULL) { delete [] band; band = NULL; } if(event != NULL) { delete [] event; event = NULL; } if(date != NULL) { delete [] date; date = NULL; } if(time != NULL) { delete [] time; time = NULL; } if(price != NULL) { delete [] price; price = NULL; } return; } /* This hash_function is used everytime we add, remove, build, or do any modification to our table. it takes a array if characters as a key to go to a certain index in out hash table through a set of mathematical operations. */ int table :: hash_function(char * key) { int sum = 0; for(int i = 0; i < strlen(key); ++i) // operation to create index for table insert { if(key[i] < 0) // if the ascii value is negative { key[i] = -key[i]; // make it positive } sum += key[i]; // add up all ascii values together } sum = sum % hash_table_size; // take the remainder of the sum from the hash_table size return sum; // return index vlaue } /* this is the wrapper part for the build function. it frist sets upt the file to read from, check if it exists, the proceeeds to call the second function where we read the data. */ int table :: build ( concert & add, input & entry) { infile.open("event.txt"); if(!infile) return 0; build_two( add, entry); // call the sedcond function return 1; } /* This is the second part to the build function. This function reads in all of the elements from the text file to fill in the hash table with these elements in a while loop. after it has fully filled a input object, it calls create_concert with an object of concert to create something to hard copy into the hash_table itself. */ int table :: build_two ( concert & add, input & entry) { int i = 0; // used to add concerts iteratively char detail_i[1000] = {'\0'}; char detail [1000] = {'\0'}; // array to get details of concert char detail_two[1000] = {'\0'}; char detail_three [1000] = {'\0'}; char detail_four [1000] = {'\0'}; char detail_five [1000] = {'\0'}; entry.clean(); // clean input struct add.clean_junk(); // clean up previous entries // prime the pump infile.get(detail_i, 1000,'|' ); infile.ignore(100, '\n'); entry.input1 = new char [strlen(detail_i) + 1]; strcpy(entry.input1, detail_i); while (infile && !infile.eof() && i < hash_table_size) // not end of file { // second element infile.get(detail_two, 1000, '|'); infile.ignore(100, '\n'); entry.input2 = new char [strlen(detail_two) + 1]; strcpy(entry.input2, detail_two); // third element infile.get(detail_three, 1000, '|'); infile.ignore(100, '\n'); entry.input3 = new char [strlen(detail_three) + 1]; strcpy(entry.input3, detail_three); // fourth element infile.get(detail_four, 1000, '|'); infile.ignore(100, '\n'); entry.input4 = new char [strlen(detail_four) + 1]; strcpy(entry.input4, detail_four); // fifth element infile.get(detail_five, 1000, '|'); infile.ignore(100, '\n'); entry.input5 = new char [strlen(detail_five) + 1]; strcpy(entry.input5, detail_five); add.create_event(entry); // hard copy elements insert(entry.input1, add); // insert into hash table entry.clean(); // clean input struct add.clean_junk(); // clean up previous entries for(int k = 0; k < 1000 ; ++k) // clean up previous entries { detail[k] = '\0'; detail_two[k] = '\0'; detail_three[k] = '\0'; detail_four[k] = '\0'; detail_five[k] = '\0'; } ++i; // first element infile.get(detail, 1000,'|' ); infile.ignore(100, '\n'); entry.input1 = new char [strlen(detail) + 1]; strcpy(entry.input1, detail); } infile.close(); // close the file infile.clear(); // to reuse file return 1; } /* this function inserts a element into the hash table based on a index created from the name of the band playing that is passed into the hash function. it also take a concert element that is used to hard copy an object into the hash table. */ int table :: insert( char * key_value, const concert & to_add) { int index = 0; // get index to insert at index = hash_function(key_value); // call the hash function if(!hash_table[index]) // no node at index { hash_table[index] = new node; hash_table[index]->a_concert.copy_concert(to_add); hash_table[index]->next = NULL; return 1; } // exisiting node at spot insert at beginning node * temp = hash_table[index]; hash_table[index] = new node; hash_table[index]->a_concert.copy_concert(to_add); hash_table[index]->next = temp; return 1; } /* first part of the display function. has a integer initialized to zero passed in to goe through the idices of the hash table using recursion. Once it reaches the hash_table last index it kicks out of the function. */ int table :: display ( int index ) { if(index < hash_table_size )// if the index is within the bounds of the table { if(hash_table[index] != NULL) // if index if filled { display_two(hash_table[index]); // display } return display(index+1); // call function again } return 1; } /* This is the second part that displays all of the nodes in the index. It uses recusion to travel to the end of the chain the returns bacl to the first display to go to the next hash table index. */ int table :: display_two ( node * link) { if(!link) return 0; // if link is NULL get out link->a_concert.display(); // display concert cout << endl; // space return display_two(link->next); // return with next node } /* This function takes in a character array that is used to call the hash function, the goes to the index found by the hash function. If there is no data there it returns. If there is a node there it deletes the elements in the index */ int table :: remove( char * key) { int index = 0; index = hash_function(key); if(hash_table[index] == NULL) return 0; // if there it no data if(hash_table[index]->next == NULL) // there is one element { delete hash_table[index]; hash_table[index] = NULL; return 1; } if(hash_table[index]->next != NULL) // there is mutiple nodes { node * temp = hash_table[index]->next; delete hash_table[index]; hash_table[index] = NULL; return 1; } } /* This function finds an elemtent in the table by using a character array and once it find the elemtn at the indes it returns the element back to the user by hardcopying data into the parameter found. */ int table :: search( char * find, concert & found) { int index = 0; index = hash_function(find); // get index if(hash_table[index] == NULL) return 0; // if there is no data allocated else { found.copy_concert(hash_table[index]->a_concert); // copy element into the found object return 1; } } input :: ~input () { // delete all elements in the input object if(input1) { delete [] input1; input1 = NULL; } if(input2) { delete [] input2; input2 = NULL; } if(input3) { delete [] input3; input3 = NULL; } if(input4) { delete [] input4; input4 = NULL; } if(input5) { delete [] input5; input5 = NULL; } } node :: ~ node () { // delete next element connceted to node if(next) { delete next; } } concert :: ~concert () { // delete all dynamic memory in the object if(band) { delete [] band; band = NULL; } if(event) { delete [] event; event = NULL; } if(date) { delete [] date; date = NULL; } if(time) { delete [] time; time = NULL; } if(price) { delete [] price; price = NULL; } } table :: ~table () { // if we allcated a table if(hash_table) { for(int i = 0; i < hash_table_size; ++i) // loop thourgh the whole table { delete hash_table[i] ; // delete the node at the index hash_table[i] = NULL; // set that index pointer to null } delete [] hash_table; // get rid of hash table } hash_table_size = 0; }
true
aeb4dca2845be54d759a8991edc824b76b5e1478
C++
aft3rthought/ATLGraphics
/flat_textured_renderer.h
UTF-8
4,553
2.53125
3
[]
no_license
#pragma once #include "ATLUtil/math2d.h" #include "ATLUtil/color.h" #include "ATF/ATLGLResource.h" #include "ATF/NomRenderingHeaders.h" #include "ATF/NomFiles.h" namespace atl_graphics_namespace_config { struct application_folder; struct shared_renderer_state; struct flat_textured_vertex { atl::point2f position; atl::point2f texture_coordinates; atl::color color_multiply; atl::color color_lerp; }; enum class flat_textured_renderer_status { waiting_to_load, loading, ready, failed }; template <size_t max_vertices, size_t max_indices> struct flat_textured_renderer_working_space { flat_textured_vertex vertices[max_vertices]; size_t num_vertices = 0; flat_textured_vertex * vertex_begin() { return vertices; } flat_textured_vertex * vertex_end() { return vertices + max_vertices; } flat_textured_vertex * vertex_current() { return vertices + num_vertices; } const flat_textured_vertex * vertex_begin() const { return vertices; } const flat_textured_vertex * vertex_end() const { return vertices + max_vertices; } const flat_textured_vertex * vertex_current() const { return vertices + num_vertices; } GLuint indices[max_indices]; size_t num_indices = 0; GLuint * index_begin() { return indices; } GLuint * index_end() { return indices + max_indices; } GLuint * index_current() { return indices + num_indices; } const GLuint * index_begin() const { return indices; } const GLuint * index_end() const { return indices + max_indices; } const GLuint * index_current() const { return indices + num_indices; } void clear() { num_indices = 0; num_vertices = 0; } }; struct flat_textured_renderer_prepared_data { vertex_array_resource vbo; buffer_resource vertex_buffer; buffer_resource index_buffer; size_t num_indices = 0; }; struct flat_textured_renderer { private: shared_renderer_state & internal_shared_renderer_state; atl::box2f internal_current_screen_bounds; GLuint internal_current_texture; shader_program_resource internal_program; flat_textured_renderer_status internal_status; file_data internal_vertex_shader_file; file_data internal_fragment_shader_file; // Constants // Uniform index. enum ShaderUniforms { UNIFORM_SCREEN_DIM, NUM_UNIFORMS }; int internal_shader_uniforms[NUM_UNIFORMS]; enum VertexAttributes { ATTRIBUTE_POSITION, ATTRIBUTE_TEXTURE_COORDINATES, ATTRIBUTE_COLOR_MULTIPLY, ATTRIBUTE_COLOR_LERP, NUM_ATTRIBUTES }; void internal_bind_buffers_and_vertex_attributes(const buffer_resource & in_vertex_buffer, const buffer_resource & in_index_buffer); public: flat_textured_renderer(shared_renderer_state & in_rendererState); ~flat_textured_renderer(); flat_textured_renderer_status status() const { return internal_status; } void incremental_load(const application_folder & in_application_folder); template <size_t max_vertices, size_t max_indices> void prepare(flat_textured_renderer_prepared_data & in_data_to_prepare, const flat_textured_renderer_working_space<max_vertices, max_indices> & in_data, const bool in_use_static_buffers) { prepare(in_data_to_prepare, in_data.vertex_begin(), in_data.index_begin(), in_data.num_vertices, in_data.num_indices, in_use_static_buffers); } void prepare(flat_textured_renderer_prepared_data & in_data_to_prepare, const flat_textured_vertex * in_vertices, const GLuint * in_indices, const size_t in_num_vertices, const size_t in_num_indices, const bool in_use_static_buffers); void render(const flat_textured_renderer_prepared_data & in_prepared_data, const GLuint in_texture); }; }
true
a535211f0e3a9af46b00cda76f70cf013440c110
C++
fooofei/leetcode
/cn-058-last-word-len/main.cc
UTF-8
1,140
3
3
[]
no_license
#include <algorithm> #include <array> #include <bitset> #include <chrono> #include <iostream> #include <limits> #include <list> #include <map> #include <stack> #include <string> #include <thread> #include <vector> using namespace std; // 058 https://leetcode-cn.com/problems/length-of-last-word/ class Solution { public: int lengthOfLastWord(string s) { size_t wordEnd = s.find_last_not_of(" "); size_t wordBegin = s.find_last_of(" ", wordEnd); if (wordEnd < s.size()) { // " aaa" if (wordBegin < s.size()) { return wordEnd - wordBegin; } // "aaa" return wordEnd + 1; // 错误点: 漏考虑 } return 0; } }; void testf(string s, int expect) { Solution a; auto r = a.lengthOfLastWord(s); std::cout << "result of \"" << s << "\" = " << r << "expect = " << expect << endl; ; } int main() { Solution a; (void)a; testf("Hello World", 6); testf("Hello World ", 6); testf(" ", 0); testf("a", 1); testf("a ", 1); std::cout << "main exit\n"; return 0; }
true
f365f26ca4dd15df1e074f429c7ba405038da441
C++
tcannon686/gnidEngine
/src/tests/phongshader.cpp
UTF-8
1,493
2.53125
3
[]
no_license
#include "gnid/phongshader.hpp" #include "gnid/gamebase.hpp" #include "gnid/matrix/matrix.hpp" #include <cassert> #include <iostream> using namespace tmat; using namespace std; using namespace gnid; static int t = 0; static shared_ptr<PhongShader> phongShader; static shared_ptr<PhongMaterial> phongMaterial; class TestGame : public GameBase { public: shared_ptr<Scene> scene; TestGame() : GameBase("Test Phong", 32, 32), scene(nullptr) { } const shared_ptr<Scene> &currentScene() const override { return scene; } void init() override { cout << "init() called" << endl; phongShader = make_shared<PhongShader>(); phongShader->init(); } void loadContent() override { cout << "loadContent() called" << endl; phongMaterial = PhongMaterial::Builder() .shader(phongShader) .diffuse(1, 0, 0) .specular(0, 1, 0) .shininess(100.0f) .build(); } void postLoadContent() override { /* postLoadContent should happen after loadContent. */ cout << "postLoadContent() called" << endl; } void update(float dt) override { cout << "update() called" << endl; phongShader->use(); phongMaterial->bind(); /* Stop immediately. */ stop(); } }; int main(int argc, char *argv[]) { TestGame game; game.start(); }
true
46bd6719521ab9a4f3c5d0e98aef4b890fc7d4cb
C++
MrEngineerET/roboClean
/Code/Node MCU ESP8266/NodeVrAndVlAndW/NodeVrAndVlAndW.ino
UTF-8
2,973
2.65625
3
[]
no_license
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include<SoftwareSerial.h> SoftwareSerial arduinoSerial(D1,D2); const char* ssid = "RoboClean"; const char* password = "qazwsxedc"; IPAddress local_ip(192,168,1,1); IPAddress gateway(192,168,1,1); IPAddress subnet_mask(255,255,255,0); ESP8266WebServer server(80); // variables for data send from arduino String Vr,Vl,V,w,t,message; const char motor_speed_form[] PROGMEM = R"rawliteral( <!DOCTYPE html> <html> <head> <title>Testing the motor of speeds</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <h2>Robo Clean Speed Test</h2> <form action="/motorSpeedgetSpeedValue" , method="post"> <label>Speed in cm/s</label> <input type="number" step="1" name="motorSpeed" /> <input type="submit" value="RUN" name= "run" /> <input type="submit" value="STOP" name= "stop" /> </form> </body> </html> )rawliteral"; void setup() { // put your setup code here, to run once: Serial.println("Serial connection with PC is working"); arduinoSerial.begin(9600); WiFi.softAP(ssid,password); WiFi.softAPConfig(local_ip, gateway, subnet_mask); delay(100); server.on("/motorSpeed",handleMotorTest); server.on("/motorSpeedgetSpeedValue",handleMotorSpeedGetValue); // endpoint for matlab and processing to get all the speed value and angular velocity server.on("/velocities",handleGetVelocity); server.begin(); } void loop() { // put your main code here, to run repeatedly: server.handleClient(); if(arduinoSerial.available()>0){ Serial.println("message recieved"); message = arduinoSerial.readStringUntil('\n'); int ind1 = message.indexOf(','); Vr = message.substring(0,ind1); int ind2 = message.indexOf(',',ind1+1); Vl = message.substring(ind1+1,ind2); int ind3 = message.indexOf(',',ind2+1); V = message.substring(ind2+1,ind3); int ind4 = message.indexOf(',',ind3+1); w = message.substring(ind3+1,ind4); int ind5 = message.indexOf(',',ind4+1); t = message.substring(ind4+1,ind5); } } void handleGetVelocity(){ String ptr = "{\"Vr\":"+ Vr +",\n"; ptr += "\"Vl\":"+ Vl +",\n"; ptr += "\"V\":"+ V +",\n"; ptr += "\"w\":"+ w +",\n"; ptr += "\"t\":"+ t +"}"; server.send(200,"application/json",ptr); } void handleMotorTest(){ server.send(200,"text/html",motor_speed_form); } void handleMotorSpeedGetValue(){ if(server.method() == HTTP_POST){ for (uint8_t i = 0; i < server.args(); i++) { // message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; if(server.argName(i) == "motorSpeed"){ arduinoSerial.println(server.arg(i)); }else if(server.argName(i) == "stop"){ arduinoSerial.println("0"); Serial.println("stop is pressed"); } } // Serial.println(message); server.send(200,"text/html",motor_speed_form); } }
true
3c28ba0e2a913ca14568f586cee774f096ee7df7
C++
heretique/cuteboxLegacy
/src/common/genpublicstrings.cpp
UTF-8
2,005
2.734375
3
[]
no_license
#include <QObject> #include "genpublicstrings.h" //Main screen QString GenPublicStrings::STR_TEST = ""; QString GenPublicStrings::STR_WELCOME = ""; QString GenPublicStrings::STR_CHOOSE_DOWNLOAD_FILES = ""; QString GenPublicStrings::STR_CONFIRM_DOWNLOAD_FILES = ""; QString GenPublicStrings::STR_CHOOSE_FILES = ""; QString GenPublicStrings::STR_CONFIRM_COPY_FILES = ""; QString GenPublicStrings::STR_CONFIRM_MOVE_FILES = ""; QString GenPublicStrings::STR_CONFIRM_DELETE_FILES = ""; QString GenPublicStrings::STR_CONFIRM_UPLOAD_FILES = ""; QString GenPublicStrings::STR_UPLOAD_SELECTED_COUNT = ""; QString GenPublicStrings::STR_CHOOSE_UPLOAD_FILES = ""; QString GenPublicStrings::STR_CREATING_FOLDER = ""; QString GenPublicStrings::STR_CHOOSE_NEW_DOWNLOAD_LOCATION = ""; QString GenPublicStrings::STR_ANOTHER_ACTION_IN_PROGRESS = ""; GenPublicStrings::GenPublicStrings() { retranslateStrings(); } void GenPublicStrings::retranslateStrings() { //Main screen STR_TEST = QObject::tr("TEST", ""); STR_WELCOME = QObject::tr("Welcome"); STR_CHOOSE_DOWNLOAD_FILES = QObject::tr("Choose the files you want to download."); STR_CONFIRM_DOWNLOAD_FILES = QObject::tr("Download %1 file(s)?"); STR_CHOOSE_FILES = QObject::tr("Choose the files or folders and then chose your action."); STR_CONFIRM_COPY_FILES = QObject::tr("Copy %1 file(s) to: %2 ?"); STR_CONFIRM_MOVE_FILES = QObject::tr("Move %1 file(s) to: %2 ?"); STR_CONFIRM_DELETE_FILES = QObject::tr("Delete %1 file(s) ?"); STR_CHOOSE_UPLOAD_FILES = QObject::tr("Choose the files you want to upload."); STR_UPLOAD_SELECTED_COUNT = QObject::tr("%1 file(s) selected for upload."); STR_CONFIRM_UPLOAD_FILES = QObject::tr("Upload %1 file(s) to: %2 ?"); STR_CREATING_FOLDER = QObject::tr("Creating folder..."); STR_CHOOSE_NEW_DOWNLOAD_LOCATION = QObject::tr("Choose new download location"); STR_ANOTHER_ACTION_IN_PROGRESS = QObject::tr("<b>!</b>Another action already in progress"); }
true
0e81a9ac1512ff045f9edd59eca33eadd9e322ae
C++
felipepiovezan/ine5420
/lib/cg/Viewport.cpp
UTF-8
5,761
2.703125
3
[]
no_license
#include "cg/Viewport.h" #include <iostream> #include <cassert> #include <ctime> namespace CG { Coordinate Viewport::transformCoordinate(const Coordinate& c) const { int width = getWidth(); int height = getHeight(); double x = width * (c.x - _window.xmin()) / (_window.xmax() - _window.xmin()); double y = height * (1 - ((c.y - _window.ymin()) / (_window.ymax() - _window.ymin()))); return Coordinate(x, y); } GObject::Coordinates Viewport::transformCoordinates(const GObject::Coordinates& coords) const { CG::GObject::Coordinates vwCoordinates; for (const auto &c : coords) vwCoordinates.push_back(transformCoordinate(c)); return vwCoordinates; } double Viewport::screenToWindowTransformX(double x_screen) { int width = getWidth(); return (x_screen / width) * _window.width() * (_window.xmax() - _window.xmin()); } double Viewport::screenToWindowTransformY(double y_screen) { int height = getHeight(); return (y_screen / height) * _window.height() * (_window.ymax() - _window.ymin()); } void Viewport::changeWindowZoom(double step){ if(_window.zoom(step)){ _window.updateMatrix(); transformAndClipAll(_window.wo2wiMatrix()); redraw(); } } void Viewport::changeWindowPosition(double dx, double dy, double dz){ _window.move(dx, dy, dz); _window.updateMatrix(); transformAndClipAll(_window.wo2wiMatrix()); redraw(); } void Viewport::rotateWindow(double thetaX, double thetaY, double thetaZ){ _window.rotateX(Transformation::toRadians(thetaX)); _window.rotateY(Transformation::toRadians(thetaY)); _window.rotateZ(Transformation::toRadians(thetaZ)); _window.updateMatrix(); transformAndClipAll(_window.wo2wiMatrix()); redraw(); } void Viewport::onObjectCreation(const std::string& name, ObjRef object) { assert(!_windowObjects.exists(name)); auto windowObj = _windowObjects.add(name, object->clone()); transformAndClip(windowObj, _window.wo2wiMatrix()); drawObject(*windowObj); // Draw only the inserted object } void Viewport::onObjectCreation(const std::string& baseName, const std::vector<ObjRef> &objects) { int i=0; for(const auto obj : objects) { auto name = baseName + std::to_string(i++); assert(!_windowObjects.exists(name)); auto windowObj = _windowObjects.add(name, obj->clone()); transformAndClip(windowObj, _window.wo2wiMatrix()); } redraw(); } void Viewport::onObjectChange(const std::string& name, ObjRef object) { auto itWindow = _windowObjects.findObject(name); assert(_windowObjects.isValidIterator(itWindow)); itWindow->second = object->clone(); transformAndClip(itWindow->second, _window.wo2wiMatrix()); redraw(); } void Viewport::onObjectRemoval(const std::string& name) { assert(_windowObjects.exists(name)); _windowObjects.remove(name); redraw(); } std::ostream& operator<<(std::ostream& os, const GObject& rhs){ for(const auto& p : rhs.coordinates()) os << "(" << p.x << ", " << p.y << ", " << p.y << std::endl; return os; } void Viewport::transformAndClip(ObjRef obj, const Transformation &t) { bool draw = true; obj->transform(t); if (behindCamera(obj)) { obj->coordinates().clear(); return; } obj->applyPerspective(_window.d()); switch (obj->type()) { case GObject::Type::OBJECT: break; case GObject::Type::POINT: draw = _clippingStrategy.clip(*static_cast<GPoint*> (obj.get()), clippingRect); break; case GObject::Type::LINE: draw = _clippingStrategy.clip(*static_cast<GLine*> (obj.get()), clippingRect); break; case GObject::Type::POLYGON: draw = _clippingStrategy.clip(*static_cast<GPolygon*> (obj.get()), clippingRect); break; case GObject::Type::_3D_OBJECT: draw = _clippingStrategy.clip(*static_cast<G3dObject*> (obj.get()), clippingRect); break; case GObject::Type::BEZIER_CURVE: case GObject::Type::SPLINE_CURVE: { Curve* curve = static_cast<Curve*> (obj.get()); double step = _window.width() / 1000.0; curve->regeneratePath(step); draw = _clippingStrategy.clip(*curve, clippingRect); break; } case GObject::Type::SURFACE: { GSurface *surface = static_cast<GSurface*>(obj.get()); surface->regeneratePath(50, 50); bool any = false; for(auto& curve : surface->curves()){ any |= _clippingStrategy.clip(curve, clippingRect); } draw = any; break; } } if (!draw) { obj->coordinates().clear(); } } void Viewport::transformAndClipAll(const Transformation &t){ clock_t time = clock(); { _windowObjects.objects().clear(); for(auto &obj : _world->getObjects()){ ObjRef winObj = obj.second->clone(); _windowObjects.objects()[obj.first] = winObj; transformAndClip(winObj, t); } } time = clock() - time; double s = ((double)time)/CLOCKS_PER_SEC; std::cout << "Took me " << time << " clock ticks ("<< s << " seconds or " << 1/s << "draws/s) at " << CLOCKS_PER_SEC << "Hz to transform and clip all objects" << std::endl; } bool Viewport::behindCamera(ObjRef obj) { unsigned int frontCamera = 0; // Number of points in front of camera for(auto &c : obj->coordinates()) { if (c.z >= 0) { frontCamera++; } } return frontCamera == 0; } Viewport::Border::Border(const ClippingRect& rect) { addCoordinate(Coordinate(rect.minX, rect.minY)); addCoordinate(Coordinate(rect.minX, rect.maxY)); addCoordinate(Coordinate(rect.maxX, rect.maxY)); addCoordinate(Coordinate(rect.maxX, rect.minY)); decoration.setLineColor(Color(1, 0, 0)); decoration.setLineWidth(3.0); } }
true
dce3f476b69ec6a09ad8f6d937f21ac943a54344
C++
seedChen/leetcode
/restoreIpAddresses/ans.cpp
UTF-8
2,416
3.609375
4
[]
no_license
/** * @file ans.cpp * @brief * Given a string containing only digits, restore it by returning all possible * valid IP address combinations. * * For example: * Given "25525511135", * * return ["255.255.11.135", "255.255.111.35"]. (Order does not matter) * * @version * @date 2015-06-19 09:21 * @author chen_juntao * @email chen_juntao@outlook.com */ #include <vector> #include <string> #include <stdlib.h> #include <iostream> using namespace std; class Solution { private: void helper(string s, int divisions, vector<string>& ret, vector<string>& ipSegments) { if (divisions == 1) { if (s.size() >= 2 && s[0] == '0') return; if (atoi(s.c_str()) <= 255) { string ip; for (int i = 0; i < (int)ipSegments.size(); i++) { ip = ip + ipSegments[i] + '.'; } ip += s; ret.push_back(ip); } } else { divisions--; if ((int)s.size() - 1 >= divisions) { ipSegments.push_back(s.substr(0, 1)); helper(s.substr(1), divisions, ret, ipSegments); ipSegments.pop_back(); } if (s[0] == '0') return; if ((int)s.size() - 2 >= divisions) { ipSegments.push_back(s.substr(0, 2)); helper(s.substr(2), divisions, ret, ipSegments); ipSegments.pop_back(); } if ((int)s.size() - 3 >= divisions) { string ipSegment = s.substr(0, 3); if (atoi(ipSegment.c_str()) <= 255) { ipSegments.push_back(ipSegment); helper(s.substr(3), divisions, ret, ipSegments); ipSegments.pop_back(); } } } } public: vector<string> restoreIpAddresses(string s) { vector<string> result; vector<string> ipSegments; if (s.size() < 4 || s.size() > 12) return result; helper(s, 4, result, ipSegments); return result; } }; int main(int argc, char *argv[]) { Solution s; vector<string> ret = s.restoreIpAddresses("010010"); for (auto i : ret) cout << i << endl; return 0; }
true
7303e9f5c5743de49063706f9b11b7fd373af863
C++
MAMEM/GazeTheWeb
/Browse/Client/src/State/Settings/Settings.h
UTF-8
3,493
2.53125
3
[ "MIT", "Apache-2.0" ]
permissive
//============================================================================ // Distributed under the Apache License, Version 2.0. // Author: Raphael Menges (raphaelmenges@uni-koblenz.de) //============================================================================ // Settings State. #ifndef SETTINGS_H_ #define SETTINGS_H_ #include "src/State/State.h" #include "plugins/Eyetracker/Interface/EyetrackerGeometry.h" class Settings : public State { public: // Constructor Settings(Master* pMaster); // Destructor virtual ~Settings(); // ############# // ### STATE ### // ############# // Update. Returns which state should be active in next time step virtual StateType Update(float tpf, const std::shared_ptr<const Input> spInput, std::shared_ptr<VoiceAction> spVoiceInput, bool &keyboardActive); // Draw virtual void Draw() const; // Activate virtual void Activate(); // Deactivate virtual void Deactivate(); // Get homepage URL std::string GetHomepage() const { return _webSetup.homepage; } // Get Firebase Email std::string GetFirebaseEmail() const { return _globalSetup.firebaseEmail; } // Get Firebase Password std::string GetFirebasePassword() const { return _globalSetup.firebasePassword; } // Get eyetracker geometry EyetrackerGeometry GetEyetrackerGeometry() const { return _globalSetup.eyetrackerGeometry; } // Store homepage URL void StoreHomepage(std::string URL) { _webSetup.homepage = URL; ApplySettings(true); } // Store global keyboard layout void StoreKeyboardLayout(eyegui::KeyboardLayout keyboardLayout) { _globalSetup.keyboardLayout = keyboardLayout, ApplySettings(true); } private: // Apply and maybe save settings void ApplySettings(bool save = true); // Save settings to hard disk. Returns whether successful bool SaveSettings() const; // Load settings from hard disk. Returns whether successful bool LoadSettings(); // Give listener full access friend class SettingsButtonListener; // Listener for GUI class SettingsButtonListener : public eyegui::ButtonListener { public: SettingsButtonListener(Settings* pSettings) { _pSettings = pSettings; } virtual void hit(eyegui::Layout* pLayout, std::string id) {} virtual void down(eyegui::Layout* pLayout, std::string id); virtual void up(eyegui::Layout* pLayout, std::string id); virtual void selected(eyegui::Layout* pLayout, std::string id) {} private: Settings* _pSettings; }; // Instance of listener std::shared_ptr<SettingsButtonListener> _spSettingsButtonListener; // Setup of global settings class GlobalSetup { public: bool showDescriptions = true; bool showGazeVisualization = false; bool adBlocking = true; eyegui::KeyboardLayout keyboardLayout = eyegui::KeyboardLayout::US_ENGLISH; std::string firebaseEmail = ""; std::string firebasePassword = ""; EyetrackerGeometry eyetrackerGeometry; }; // Setup of web settings class WebSetup { public: std::string homepage = "https://duckduckgo.com"; }; // Layouts eyegui::Layout* _pSettingsLayout; eyegui::Layout* _pGeneralLayout; eyegui::Layout* _pAdBlockingLayout; eyegui::Layout* _pInfoLayout; // Bool to remember whether to switch to Web in next frame bool _goToWeb = false; // Setups GlobalSetup _globalSetup; WebSetup _webSetup; // Fullpath to settings file std::string _fullpathSettings; }; #endif // SETTINGS_H_
true
a7a6cf4659f3a99b70092ec8d44fb29039923bce
C++
zqiu/codefor-----andgiggles
/IEDcode/withoutwirelesstest/withoutwirelesstest.ino
UTF-8
4,089
2.6875
3
[]
no_license
/* code for the microcontroller on the shirt */ #include <avr/sleep.h> #include <Adafruit_GFX.h> #include <Adafruit_SharpMem.h> #define SERIAL_BAUD 115200 #define READDELAY 5 //#of ms to wait between reading sensors #define READSBEFOREPRINT 10 #define TEMPPORT 0 #define RESPORT 1 #define HEARTRATEPORT 2 #define RESTHRESHOLD 2.86 //.02 resistance difference. need to find the threshold #define HEARTTHRESHOLD 2.56 //voltage value. need to find the threshold #define SCK 7 #define MOSI 8 #define SS 9 bool requestACK=false,resting=false,heartbeat=false; int temp,res,heart,temptot = 0,rescount = 0,heartcount = 0; Adafruit_SharpMem display(SCK, MOSI, SS); char screenread = 0; //set the ports for input and output void setup(){ Serial.begin(SERIAL_BAUD); //SPI.begin(); pinMode(TEMPPORT, INPUT); pinMode(RESPORT, INPUT); pinMode(HEARTRATEPORT, INPUT); display.begin(); display.clearDisplay(); printrhs(); display.refresh(); delay(500); } //will readin values for the sensor and communicate with the main board void loop(){ temp = analogRead(TEMPPORT); res = analogRead(RESPORT); heart = analogRead(HEARTRATEPORT); Serial.print("read in "); printinfo(temp,res,heart); Serial.println(); temptot += temp; if(resting && res > RESTHRESHOLD){ resting = false; rescount += 1; } if(!resting && res < RESTHRESHOLD){ resting = true; } if(heartbeat && heart > HEARTTHRESHOLD){ heartbeat = false; heartcount += 1; } if(!heartbeat && heart < HEARTTHRESHOLD){ heartbeat = true; } delay(READDELAY); screenread++; if(screenread > READSBEFOREPRINT){ screenread = 0; display.clearDisplay(); printrhs(); display.refresh(); } } void printinfo(int temperature, int resprate, int heartrate){ Serial.print("temp:"); Serial.print(temperature); Serial.print(",res:"); Serial.print(resprate); Serial.print(",heart:"); Serial.print(heartrate); } void printrhs(){ printheart(); printtemp(); printresp(); printcal(); } void printheart(){ colorblock(17,1,2,4); colorblock(27,1,2,4); colorblock(21,3,2,2); colorblock(25,3,2,2); colorblock(23,5,2,2); colorblock(15,3,10,2); colorblock(31,3,10,2); colorblock(17,13,2,2); colorblock(19,15,2,2); colorblock(21,17,2,2); colorblock(29,13,2,2); colorblock(27,15,2,2); colorblock(25,17,2,2); colorblock(22,19,2,4); } void printtemp(){ colorblock(16,26,3,16); colorblock(23,29,17,2); } void printresp(){ byte i; for(i = 0; i < 2; ++i){ colorblock(i*12 + 13,50,2,8); colorblock(i*12 + 13,52,18,2); colorblock(i*12 + 15,59,2,6); colorblock(i*12 + 20,52,7,2); colorblock(i*12 + 20,61,10,2); } } void printcal(){ colorblock(8,74,2,9); colorblock(8,76,17,2); colorblock(8,93,2,9); colorblock(23,74,2,2); colorblock(21,76,2,2); colorblock(25,76,2,2); colorblock(20,78,2,2); colorblock(26,78,2,2); colorblock(19,80,15,2); colorblock(27,80,15,2); colorblock(21,83,2,6); colorblock(31,74,19,2); colorblock(31,93,2,9); } void make_number(byte x, byte y, byte num){ //num = 0,2,3,5,6,7,8,9 if(num == 0 || num == 2 || num == 3 || num > 4){ colorblock(x+2,y,2,6); } //num = 2,3,4,5,6,8,9 if(num > 1 && num != 7){ colorblock(x+2,y+11,2,6); } //num = 0,2,3,5,6,8 if(num == 0 || (num > 1 && num < 7 && num != 4) || num == 8){ colorblock(x+2,y+21,2,6); } //num = 0,4,5,6,8,9 if(num == 0 || (num > 3 && num < 7) || num > 7){ colorblock(x,y+2,8,2); } //num = 0,2,6,8 if(num % 2 == 0 && num != 4){ colorblock(x,y+13,8,2); } //num = 0,1,2,3,4,7,8,9 if(num < 5 || num > 6){ colorblock(x+9,y+2,8,2); } //num = 0,1,3,4,5,6,7,8,9 if(num != 2){ colorblock(x+9,y+13,8,2); } } void colorblock(byte x, byte y, byte height, byte width){ byte i,j; for(i = 0; i < height; ++i){ for(j = 0; j < width; ++j){ color(x+j,y+i); } } } void color(byte x,byte y){ Serial.print(x); Serial.print(","); Serial.println(y); display.drawPixel(x,y, 0); }
true
730eada5a75ee30f6c2e8cf652696c5cf5b925c7
C++
GonzaloCirilo/UVa
/vol110/11090_GoingInCycle!!.cpp
UTF-8
3,469
2.515625
3
[]
no_license
#include <vector> #include <stdio.h> #include <algorithm> using namespace std; typedef vector<int>vi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<vii> graph; typedef vector<vi> matrix; graph g; vi visited; vector<double> pos; bool dfs(int ind, vi stack) { if (visited[ind] == 1) { return true; } visited[ind] = 1; for (int i = 0; i < g[ind].size(); i++) { ii adj = g[ind][i]; //printf("loop ind %d adj %d\n", ind, adj.first); stack.push_back(adj.first); auto ans = dfs(adj.first, stack); if (ans) return true; stack.pop_back(); } return false; } int main(){ int t, n, m, a, b, c; scanf("%d", &t); for (int i = 1; i <= t; i++) { printf("Case #%d: ", i); scanf("%d %d", &n, &m); graph aux = graph(n); g = graph(); for (int j = 0; j < m; j++) { scanf("%d %d %d", &a, &b, &c); a--, b--; aux[a].push_back({b, c}); } // reduce graph? for(int j = 0; j < n; j++) { sort(aux[j].begin(), aux[j].end()); vii reduced = vii(); int taken[51] = {}; for(int k = 0; k < aux[j].size(); k++) { if(!taken[aux[j][k].first]){ reduced.push_back(aux[j][k]); taken[aux[j][k].first] = 1; } } g.push_back(reduced); } // karps min mean cycle matrix dp = matrix(n+1); for (int j = 0; j < dp.size(); j++) { dp[j] = vi(n, -1); } for(int j = 0; j < n; j++) { dp[0][j] = 0; } for (int j = 1; j <= n; j++) { for (int k = 0; k < n; k++) { for (int l = 0; l < g[k].size(); l++) { //printf("\n||checking %d %d", j-1,g[k][l].first); if (dp[j-1][g[k][l].first] != -1) { int w = dp[j-1][g[k][l].first] + g[k][l].second; //printf("\n||preparing w %d", w); if (dp[j][k] == -1) { dp[j][k] = w; //printf("\n||dp j k is now %d", w); } else { dp[j][k] = min(dp[j][k], w); } } } } } vector<double> avgs = vector<double>(n, -1); for (int j = 0; j < n; j++) { if (dp[n][j] != -1) { for (int k = 0; k < n; k++) { if (dp[k][j] != -1) { avgs[j] = max(avgs[j], (dp[n][j] - dp[k][j]) * 1.0 / (n-k)); } } } } // check if has cycles visited = vi(n, 0); pos = vector<double>(); bool hasCycle = false; for (int j = 0; j < n; j++) { if (!visited[j]) { vi s = vi(); s.push_back(j); hasCycle |= dfs(j, s); } } double ans = 1e9; for(int j = 0; j < avgs.size(); j++) { double x = avgs[j]; if (x != -1 && x < ans) { ans = x; } } if (!hasCycle || ans == 1e9) { printf("No cycle found.\n"); } else { printf("%.2lf\n", ans); } } return 0; }
true
e53082f06bde6918a0f35667eae34c56637f8d0f
C++
luisSalher/Sistemas-Distribuidos
/Practica3/Fecha.cpp
UTF-8
2,285
3.328125
3
[]
no_license
#include "Fecha.h" #include <iostream> using namespace std; Fecha::Fecha(int dd, int mm, int aaaa) { mes = mm; dia = dd; anio = aaaa; int cadena[1000000]; } void Fecha::inicializaFecha(int dd, int mm, int aaaa) { Fecha f; if(!f.valida(dd,mm,aaaa)) { return; } else { anio = aaaa; mes = mm; dia = dd; } return; } void Fecha::muestraFecha() { cout << "\nLa fecha es(dia-mes-año): " << dia << "-" << mes << "-" << anio << endl << "\n"; return; } int Fecha::convierte() { //cout << "\nFecha: " << (anio*10000+mes*100+dia) << "\n"; return (anio*10000+mes*100+dia); } bool Fecha::leapyr() { if((anio%4 == 0 || anio%400 == 0) && (anio % 100 != 0)) { return true; } return false; } bool Fecha::valida(int mm, int dd, int aaaa) { if(mm < 1 || mm > 12) { cout << "\nError, mes invalido\n"; return false; } if(dd < 1 || dd > 31) { cout << "\nEste dia no existe \nAsumiendo que todos los meses tienen 31 dias...\n"; return false; } if(aaaa < 0 || aaaa > 2018) { cout << "\nAño invalido\n"; return false; } return true; } int Fecha::getDia() { return dia; } int Fecha::getMes() { return mes; } int Fecha::getAnio() { return anio; } int Fecha::masVieja(Fecha a, Fecha b) { if(a.convierte() > b.convierte()) { //cout << "1,"; return 1; } if(a.convierte() == b.convierte()) { //cout << "0,"; return 0; } if(a.convierte() < b.convierte()) { //cout << "-1,"; return -1; } } int Fecha::masVieja2(Fecha &a, Fecha &b) { if(a.convierte() > b.convierte()) { //cout << "1,"; return 1; } if(a.convierte() == b.convierte()) { //cout << "0,"; return 0; } if(a.convierte() < b.convierte()) { //cout << "-1,"; return -1; } }
true
2ea379e2e666c214d9e1a2102e02a9294414d75d
C++
andrewletskalyuk/Practice_17.08.2019
/Project4/Coordinates.h
UTF-8
196
2.65625
3
[]
no_license
#pragma once class Coordinates { int x; int y; public: Coordinates(); Coordinates(int, int); ~Coordinates(); void setX(int _x); void setY(int _y); int getX() const; int getY() const; };
true
196d1361a83dbc74602b1fdadaa25f2c99548c69
C++
johnli28/data-algorithm
/dynamic-program/LongestCommonSubsequence.h
UTF-8
919
3.109375
3
[]
no_license
#pragma once #include <iostream> #include <string> #include "utils.h" #include <vector> using namespace std; // NOTE: // dynamic programming: split a big problem into small problems // A dynamic programming table, store the states (results) of small problems // Initiate states int lcsDP(char* lStr, int lLen, char* rStr, int rLen, string & lcsStr) { // Note: 2D array as DP table vector<vector<int>> table; int lcsLen = 0; // two tiers of for loop for (int i = 0; i <= lLen; i++) { table.push_back(vector<int>(rLen + 1)); for (int j = 0; j <= rLen; j++) { if (i == 0 || j == 0) { table[i][j] = 0; } else if (lStr[i - 1] == rStr[j - 1]) { table[i][j] = 1 + table[i - 1][j - 1]; lcsStr.append(1, lStr[i - 1]); } else { table[i][j] = max(table[i - 1][j], table[i][j - 1]); } } } return table[lLen][rLen]; }
true
4fdf4759eebecb07a06618ecf126068e643656a3
C++
tsargs/Physically-based-modeling
/Physically-based modeling 2.0/Vortex.h
UTF-8
716
2.546875
3
[]
no_license
// // Vortex.h // PhysicallyBasedModeling // // Created by Shyam Prathish Sargunam on 10/4/17. // Copyright © 2017 Shyam Prathish Sargunam. All rights reserved. // #ifndef VORTEX #define VORTEX #include <stdio.h> #include <algorithm> #include "Vector3.h" class Vortex { public: Vector3 base_center; Vector3 axis; float length; float radius; float r_f; float max_r_f; float t; Vortex(void); Vortex(const Vector3& center, const Vector3 axis_dir, const float& l, const float& r, const float& r_f_val, const float& max_r_f_val, const float& tightness); ~Vortex(void); Vector3 get_velocity(const Vector3& pos, const Vector3& v); }; #endif
true
64bda182e796668a348eadb57fc6e0e86d922743
C++
tatjam/SpaceStation
/SS13++/src/util/FileUtil.h
UTF-8
1,329
2.671875
3
[]
no_license
#pragma once #include <string> #ifdef _WIN32 #include <Windows.h> #endif // The path to the location of our executable extern std::string futil_exePath; // The path from which the program was launched extern std::string futil_runPath; struct FileUtil { // Converts '/' to '\' static std::string windowPath(std::string path) { } // Converts '\' to '/' static std::string normalPath(std::string path) { } // Platform dependant static std::string autoPath(std::string path) { } // Windows only for now :( // TODO static std::string stripFilename(std::string path) { std::string::size_type pos = path.find_last_of("\\/"); return path.substr(0, pos); } // TODO OSX and Linux static std::string getExecutablePath(bool executePath = false) { std::string out; #ifdef _WIN32 if (!executePath) { TCHAR pbuf[MAX_PATH]; GetModuleFileName(NULL, pbuf, MAX_PATH); for (int i = 0; i < MAX_PATH; i++) { if (pbuf[i] == '\0') { break; } out += pbuf[i]; } } else { TCHAR pbuf[MAX_PATH]; GetCurrentDirectory(MAX_PATH, pbuf); for (int i = 0; i < MAX_PATH; i++) { if (pbuf[i] == '\0') { break; } out += pbuf[i]; } } #endif #ifdef _linux_ // TODO we need to write this t-t return "SAD!"; #endif return out; } };
true
d0d837919535b01b32ba88ef935ba0eacd9e873f
C++
StefanKubsch/NARC
/Sources/lwmf/lwmf_multithreading.hpp
UTF-8
2,936
2.984375
3
[ "Unlicense", "LicenseRef-scancode-public-domain" ]
permissive
/* *************************************************************** * * * lwmf_multithreading - lightweight media framework * * * * (C) 2019 - present by Stefan Kubsch * * * *************************************************************** */ #pragma once #include <vector> #include <thread> #include <future> #include <memory> #include <tuple> #include <utility> #include <queue> #include <mutex> #include <condition_variable> namespace lwmf { class Multithreading final { public: Multithreading(); Multithreading(const Multithreading&) = delete; Multithreading(Multithreading&&) = delete; Multithreading& operator = (const Multithreading&) = delete; Multithreading& operator = (Multithreading&&) = delete; ~Multithreading(); template<class F, class... Args>void AddThread(F&& f, Args&& ... args); void WaitForThreads(); private: std::vector<std::thread> Workers{}; std::vector<std::future<void>> Results{}; std::queue<std::packaged_task<void()>> Tasks{}; std::mutex QueueMutex{}; std::condition_variable Condition{}; bool Stop{}; }; inline Multithreading::Multithreading() { const std::size_t NumberOfThreads{ static_cast<std::size_t>(std::thread::hardware_concurrency()) }; Workers.reserve(NumberOfThreads); LWMFSystemLog.AddEntry(LogLevel::Trace, __FILENAME__, __LINE__, "lwmf::Multithreading() (variable name:NumberOfThreads, value: " + std::to_string(NumberOfThreads) + ")"); for (std::size_t i{}; i < NumberOfThreads; ++i) { Workers.emplace_back([this] { while (true) { std::packaged_task<void()> Task; { std::unique_lock<std::mutex> lock(QueueMutex); Condition.wait(lock, [this] { return Stop || !Tasks.empty(); }); if (Stop && Tasks.empty()) { return; } Task = std::move(Tasks.front()); Tasks.pop(); } Task(); } }); } } inline Multithreading::~Multithreading() { { const std::unique_lock<std::mutex> lock(QueueMutex); Stop = true; } Condition.notify_all(); for (auto&& Worker : Workers) { Worker.join(); } } template<class F, class... Args>void Multithreading::AddThread(F&& f, Args&& ... args) { std::packaged_task<std::invoke_result_t<F, Args...>()> Task([func = std::forward<F>(f), args = std::make_tuple(std::forward<Args>(args)...)]() { return std::apply(func, std::move(args)); }); Results.emplace_back(Task.get_future()); const std::unique_lock<std::mutex> lock(QueueMutex); Tasks.emplace(std::move(Task)); Condition.notify_one(); } inline void Multithreading::WaitForThreads() { for (const auto& Result : Results) { Result.wait(); } Results.clear(); Results.shrink_to_fit(); } } // namespace lwmf
true
711bf95db9bfe8c36ccbe613f45ef072d6803888
C++
seanjedi/ECS175Project3
/Bresenham.cpp
UTF-8
4,582
3.25
3
[]
no_license
#include "Bresenham.h" #include <math.h> #include <iostream> using namespace std; void makePixel(int x, int y, float* PixelBuffer, int windowSizeX, float Rintensity, float Gintensity, float Bintensity, int mode); inline void max(int& a, int& b, float& c, float& d) { if (a > b) { int temp = a; a = b; b = temp; float temp2 = c; c = d; d = temp2; } } void Pixel(int x, int y, float* pixelBuffer, float intensity, int windowSizeX, int mode) { if (mode == 0) { makePixel(x, y, pixelBuffer, windowSizeX, intensity, 0, 0, 0); } else if (mode == 1) { makePixel(x, y, pixelBuffer, windowSizeX, 0, intensity, 0, 1); } else if(mode == 2){ makePixel(x, y, pixelBuffer, windowSizeX, 0, 0, intensity, 2); } else { makePixel(x, y, pixelBuffer, windowSizeX, intensity, intensity, intensity, 3); } } void Bresenham(int x1, int x2, int y1, int y2, float* PixelBuffer, int windowSizeX, float light1, float light2, int mode) { float intensity; if (x1 == x2) { max(y1, y2, light1, light2); for (int i = y1; i < y2; i++) {; intensity = ((float(y2) - float(i)) / (float(y2) - float(y1)) * light1) + ((float(i) - float(y1)) / (float(y2) - float(y1)) * light2); Pixel(x1, i, PixelBuffer, intensity, windowSizeX, mode); } } else if (y1 == y2) { max(x1, x2, light1, light2); for (int i = x1; i < x2; i++) { intensity = ((float(x2) - float(i)) / (float(x2) - float(x1)) * light1) + ((float(i) - float(x1)) / (float(x2) - float(x1)) * light2); Pixel(i, y1, PixelBuffer, intensity, windowSizeX, mode); } } else { int dx = fabs(x2 - x1), dy = fabs(y2 - y1); int x, y; float m = (float(y2 - y1) / float(x2 - x1)); if (m >= 1) { if (y1 > y2) { x = x2; y = y2; max(y1, y2, light1, light2); } else { x = x1; y = y1; } int Dx2 = 2 * dx, Dx2y = 2 * (dx - dy); int p = 2 * dx - dy; intensity = ((float(y2) - float(y)) / (float(y2) - float(y1)) * light1) + ((float(y) - float(y1)) / (float(y2) - float(y1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); while (y < y2) { y++; if (p < 0) p += Dx2; else { x++; p += Dx2y; } intensity = ((float(y2) - float(y)) / (float(y2) - float(y1)) * light1) + ((float(y) - float(y1)) / (float(y2) - float(y1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); } } else if (m > 0 && m < 1) { if (x1 > x2) { x = x2; y = y2; max(x1, x2, light1, light2); } else { x = x1; y = y1; } int Dy2 = 2 * dy, Dy2x = 2 * (dy - dx); int p = 2 * dy - dx; intensity = ((float(x2) - float(x)) / (float(x2) - float(x1)) * light1) + ((float(x) - float(x1)) / (float(x2) - float(x1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); while (x < x2) { x++; if (p < 0) p += Dy2; else { y++; p += Dy2x; } intensity = ((float(x2) - float(x)) / (float(x2) - float(x1)) * light1) + ((float(x) - float(x1)) / (float(x2) - float(x1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); } } else if (m <= -1) { if (y1 > y2) { x = x2; y = y2; max(y1, y2, light1, light2); } else { x = x1; y = y1; } int Dx2 = 2 * dx, Dx2y = 2 * (dx - dy); int p = 2 * dx - dy; intensity = ((float(y2) - float(y)) / (float(y2) - float(y1)) * light1) + ((float(y) - float(y1)) / (float(y2) - float(y1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); while (y < y2) { y++; if (p < 0) p += Dx2; else { x--; p += Dx2y; } intensity = ((float(y2) - float(y)) / (float(y2) - float(y1)) * light1) + ((float(y) - float(y1)) / (float(y2) - float(y1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); } } else if (m < 0 && m > -1) { if (x1 > x2) { x = x2; y = y2; max(x1, x2, light1, light2); } else { x = x1; y = y1; } int Dy2 = 2 * dy, Dy2x = 2 * (dy - dx); int p = 2 * dy - dx; intensity = ((float(x2) - float(x)) / (float(x2) - float(x1)) * light1) + ((float(x) - float(x1)) / (float(x2) - float(x1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); while (x < x2) { x++; if (p < 0) p += Dy2; else { y--; p += Dy2x; } intensity = ((float(x2) - float(x)) / (float(x2) - float(x1)) * light1) + ((float(x) - float(x1)) / (float(x2) - float(x1)) * light2); Pixel(x, y, PixelBuffer, intensity, windowSizeX, mode); } } } }
true
4ed0a202ce00ffdbcc1a1c23f0eb7bd99fe26c0b
C++
highlandear/snail
/GlMainApp/GlMainApp/illuminant.hpp
GB18030
1,752
3.078125
3
[ "MIT" ]
permissive
#pragma once #include <windows.h> #include <gl/GL.h> class GLight { public: GLight(int i) : id(i) {} GLight() : id(0){} int getID() { return id; } void setID(int i) { id = i; } // ùԴλ void GLight::setPosV(const float v[]) { glLightfv(id, GL_POSITION, v); } // û void GLight::setAmbientV(const float v[]) { glLightfv(id, GL_AMBIENT, v); } // void GLight::setDiffuseV(const float v[]) { glLightfv(id, GL_DIFFUSE, v); } // void GLight::setSpecularV(const float v[]) { glLightfv(id, GL_SPECULAR, v); } // void GLight::setAttenuationV(const float v[]) { glLightfv(id, GL_LINEAR_ATTENUATION, v); } void GLight::getPosV(float * p) { glGetLightfv(id, GL_POSITION, p); } bool available() { return 0 != id; } void off() { glDisable(id); } void on() { glEnable(id); } void drop() { off(); id = 0; } private: int id; }; class LightManager { public: static GLight & light(int index) { return lights[index]; } static void on(int index) { lights[index].setID(ID_START + index); lights[index].on(); } static bool isOn(int index) { return lights[index].available(); } static void off(int index) { lights[index].off(); } static void enable() { glEnable(GL_LIGHTING); } static void disable() { glDisable(GL_LIGHTING); } static bool isEnabled(){return GL_TRUE == glIsEnabled(GL_LIGHTING);} /* 0ŹԴΪĬϹԴ GL_LIGHT0 */ static void onDefault(); static void offDefault() { off(0); } static GLight& getDefault() { return lights[0]; } static void offAll() { for (int i = 0; i < 8; i++) off(i); } private: static GLight lights[8]; static const int ID_START = GL_LIGHT0; };
true
b997e15e41de1677eab0bdaceb5b5241c072b37d
C++
JanKesek/C---C
/min tablicy.cpp
UTF-8
489
3.484375
3
[]
no_license
#include <iostream> using namespace std; int minValue (int a) { int tab[a]; cout << "Wpisz " << a << " elementow" << endl; for (int h=0;h<a;h++) { cin >> tab[h]; } int min=tab[0]; int indxMin =0; for (int i=1;i<a;i++) { if (tab[i] < min) { min = tab[i]; indxMin=i; } } return min; } int main() { int n; cout << "Ile elementow ma zawierac tablica?" << endl; cin >> n; cout << "Najmniejsza wartosc tablicy to " << minValue(n) << endl; return 0; }
true
d84eb1b3b5dcc4fab88187bf74e97ac0be35efed
C++
tagoro9/Practicas-ETSII
/SSI/practica_2/cpp/lib/skc/skc.h
UTF-8
675
2.84375
3
[]
no_license
#ifndef SKC_H_ #define SKC_H_ #include <vector> #include <iostream> #include <sstream> #include <string> using namespace std; //Estructura vector de la STL typedef vector<int> Vector; const char BIN = 'B'; const char HEX = 'H'; const char DEC = 'D'; const char DEBUG = 'd'; const char STD = 's'; class Skc { protected: Vector _message; //Convertir string de numeros en vector de enteros Vector s_to_v(string s); string int2bin(int number); private: string int2hex(int number); public: Skc() {}; virtual void code(string msg, const char MODE = STD) {}; virtual void set_seed(string new_seed) {}; string to_s(const char MODE); }; #endif /* SKC_H_ */
true
eb49bd6a767cac8a89dd52111558de68d6f73198
C++
Josedm92/UD2
/ejercicio2.2.cpp
UTF-8
1,006
3.90625
4
[]
no_license
//Ejercicio 2.2 de la pagina 50. #include <iostream> //Incluimos libreria iostream que permite la entrada por teclado y la salida por pantalla. using namespace std; //Sentencia obligatoria. //Declaración e inicialización de variables. int numero=0; //Inicio del programa. int main () { cout << "Introduzca un número: " << endl; //Pedimos por pantalla el número. cin >> numero; //Almacenamos el número en su variable correspondiente. if (numero==0) { cout << "El número introducido es 0, no seas troll." << endl; } else { if (numero%2==0) { //Comprobamos el si modulo de la división del número introducido entre 2 da como resultado 0. cout << "el número introducido (" << numero << ") es par." << endl; //En caso afirmativo el número es par, sacamos por pantalla esta información. } else { cout << "el número introducido (" << numero << ") es impar." << endl; //En el caso contrario el número es impar, sacamos por pantalla esta información. } } } //Fin del programa
true
22b282c6449875cfa7555da67dc30aa3179bb52c
C++
bmegli/HW6
/src/exercise06_02.cpp
UTF-8
1,074
3.078125
3
[]
no_license
#include <Rcpp.h> using namespace Rcpp; //' @title simplifies list of numeric vectors to array if possibles //' @description Task: //' Write your own implementation of the simplify2array() function. Your function should //' expect a list of numeric vectors on input. //' //' @param L list of numeric vectors //' @return vector, array or list //' @export // [[Rcpp::export]] SEXP simplify2array(List L) { if(L.size()==0) return NumericVector(0); if(!(Rf_isReal(L[0]) || Rf_isInteger(L[0]))) //just the first for now, we will check the rest as we go stop("L has to be list of numeric vectors"); if(L.size()==1) return L[0]; int len1=NumericVector(L[0]).size(); bool shared_size=true; for(int i=0;i<L.size();++i) { if(!(Rf_isReal(L[i]) || Rf_isInteger(L[i]) )) stop("L has to be list of numeric vectors"); shared_size &= (NumericVector(L[i]).size()==len1); } if(!shared_size) return L; NumericMatrix M(len1, L.size()); for(int i=0;i<L.size();++i) M.column(i)=NumericVector(L[i]); return M; }
true
fd25a954818da94774f7f679ccf15c8d95755291
C++
NPIPHI/v8LoadHttp
/src/http.cpp
UTF-8
1,214
2.6875
3
[]
no_license
// // Created by 16182 on 1/2/2021. // #include "http.h" std::string Http::get(std::string url, int port, std::string subdomain) { Socket socket{url.c_str(), port}; std::string msg = make_header(url.c_str(), port, subdomain.c_str()); socket.write_bytes(msg.begin().base(), msg.end().base()); InputStream is(&socket); char buff[1<<16]; int len = is.read(buff, 1<<16); buff[len] = 0; auto content_length_ptr = strstr(buff, "Content-Length: ") + strlen("Content-Length: "); int content_length = atoi(content_length_ptr); auto content_begin = strstr(buff, "\r\n\r\n") + strlen("\r\n\r\n"); std::string content = content_begin; content.reserve(content_length); while(content.length() < content_length){ int len = is.read(buff, content_length - content.length()); buff[len] = 0; content += buff; } return content; } std::string Http::make_header(const char * url, int port, const char * subdomain) { char buff[1<<16]; sprintf(buff, "GET /%s HTTP/1.1\n" "Host: %s:%d\n" "Connection: close\n" "Accept: */*\n\n", subdomain, url, port); return buff; }
true
5b88b9aad7a0814af87f9cc1cd5a4756192df785
C++
vasily-golubev/acinverse
/src/types.cpp
UTF-8
204
2.734375
3
[]
no_license
#include "types.h" float distance (vector3 r1, vector3 r2) { float squared = (r1.x - r2.x) * (r1.x - r2.x) + (r1.y - r2.y) * (r1.y - r2.y) + (r1.z - r2.z) * (r1.z - r2.z); return sqrt(squared); }
true
82cb03a554f17c501729a0344364c43bf61e994f
C++
gittyvarshney/Linked_list
/floyd_cycle.cpp
UTF-8
2,399
3.53125
4
[]
no_license
#include<bits/stdc++.h> using namespace std; #define MAX 100005 //Detect cycle through floyd algorithm which is no coincidence //two pointer p and q increment p ones and increment q twice //to find starting of loop increment the meet node and head node class linkedList { public: int data; linkedList* next; }; void insert_node(linkedList*& head,int d) { linkedList* temp = head; linkedList* ptr = new linkedList(); ptr->data = d; ptr->next = NULL; if(temp != NULL) { while(temp->next !=NULL) { temp = temp->next; } temp->next = ptr; } else { head = ptr; } } void print_linkedList(linkedList*& head) { linkedList* temp = head; while(temp!= NULL) { cout << temp->data << " "; temp = temp->next; } cout << "\n"; } void create_cycle(linkedList*& head,int at) { linkedList* temp = head; linkedList* prev = NULL; linkedList* loop_at = NULL; while(temp!= NULL) { if(temp->data == at) //creates loop at 3rd node { loop_at = temp; } prev = temp; temp = temp->next; } prev->next = loop_at; } void floyd_find_start_node(linkedList* head,linkedList* p) { //finds the starting node of loop when cycle is founded //though floyd algorithm (no coincidence) while(head!= p) { head = head->next; p = p->next; } cout << "Starting node of loop is: " << head->data << "\n"; } void detect_cycle(linkedList*& head) {// increment p once // increment q twice it is quaranteed is cycle is there it // is busted linkedList* p = head; linkedList* q = head; while(p!= NULL && q!= NULL && q->next != NULL) { p = p->next; q = q->next->next; if(p == q) { cout << "cycle detected \n"; floyd_find_start_node(head,p); return; } } cout << "There is no Cycle \n"; } int main() { /* #ifndef ONLINE_JUDGE freopen("D:\\Project Sunrise\\input.txt", "r", stdin); freopen("D:\\Project Sunrise\\output.txt", "w", stdout); #endif ios::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); */ //implementation of undirected graph linkedList* head = NULL; insert_node(head,1); insert_node(head,2); insert_node(head,3); insert_node(head,4); insert_node(head,5); insert_node(head,6); insert_node(head,7); print_linkedList(head); create_cycle(head,4); detect_cycle(head); }
true
85143d69c4be4d67b6320c5b26f767564dc7b89f
C++
GregVanK/PibbliePums
/Game/PibbliePums/PibbliePums/Inventory.h
UTF-8
467
2.921875
3
[]
no_license
#pragma once #include <list> #include "Food.h" /* *@author: Greg VanKampen *@file: Inventory *@description: Special food container class */ namespace GEX { class Inventory { public: Inventory(); Inventory(std::list<Food> inventory); public: void addFood(Food f); Food removeFood(int index); Food getFood(int index); std::list<Food> getItems() { return _items; } int getSize() { return _items.size(); } private: std::list<Food> _items; }; }
true