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
3c3f1f60fb6313e14637f9752b8080efd83a5f5d
C++
xGreat/CppNotes
/src/algorithms/data_structures/hashmap/unique_number_of_occurrence.hpp
UTF-8
1,585
3.484375
3
[ "MIT" ]
permissive
#ifndef UNIQUE_NUMBER_OF_OCCURRENCE_HPP #define UNIQUE_NUMBER_OF_OCCURRENCE_HPP /* https://leetcode.com/problems/unique-number-of-occurrences/ Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. Example 1: Input: arr = [1,2,2,1,1,3] Output: true Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. Example 2: Input: arr = [1,2] Output: false Example 3: Input: arr = [-3,0,1,-3,1,1,1,-3,10,0] Output: true Constraints: 1. 1 <= arr.length <= 1000 2. -1000 <= arr[i] <= 1000 */ #include <vector> #include <unordered_map> #include <unordered_set> namespace Algo::DS::HashMap { class UniqueNumberOfOccurrence { public: static bool check(const std::vector<int>& v) { std::unordered_map<int, size_t> occurrence_map; for (const auto& i : v) { if (occurrence_map.count(i) == 0) { occurrence_map[i] = 1; } else { ++occurrence_map[i]; } } std::unordered_set<size_t> unique_occurrence_num; for (const auto& [_, count] : occurrence_map) { if (unique_occurrence_num.count(count) > 0) { return false; } else { unique_occurrence_num.insert(count); } } return true; } }; } #endif //UNIQUE_NUMBER_OF_OCCURRENCE_HPP
true
dcf1b50d7c7a42eca08ae575baa490c92cbf189f
C++
sheilsarda/SoC_Programming
/vitis_tutorials/bloom/fpga/hls_stream_utils.h
UTF-8
1,327
2.734375
3
[ "MIT" ]
permissive
#pragma once #include<ap_int.h> #include<hls_stream.h> namespace hls_stream { template<typename T> void buffer(hls::stream<T> &stream_o, T* axi_i, unsigned int nvals) { axiToStreamLoop: for (int i = 0; i < nvals; i++) { stream_o.write(axi_i[i]); } } template<typename T> void buffer(T* axi_o, hls::stream<T> &stream_i, unsigned int nvals) { streamToAxiLoop: for (int i = 0; i < nvals; i++) { axi_o[i] = stream_i.read(); } } template<int Wo, int Wi> void resize(hls::stream<ap_uint<Wo> > &stream_o, hls::stream<ap_uint<Wi> > &stream_i, unsigned int nvals) { if (Wo < Wi) { // Wide to Narrow ap_uint<Wi> tmp; int nwrites = Wi / Wo; int nreads = nvals; resizeStreamW2NLoop: for (int i = 0; i < nreads; i++) { for (int j = 0; j < nwrites; j++) { if (j == 0) tmp = stream_i.read(); stream_o.write(tmp(Wo - 1 + Wo * j, Wo * j)); } } } if (Wo > Wi) { // Narrow to Wide ap_uint<Wo> tmp; int nwrites = nvals; int nreads = Wo / Wi; resizeStreamN2WLoop: for (int i = 0; i < nwrites; i++) { for (int j = 0; j < nreads; j++) { tmp(Wi - 1 + Wi * j, Wi * j) = stream_i.read(); if (j == (Wo / Wi - 1)) stream_o.write(tmp); } } } if (Wo == Wi) { // Equal sizes resizeStreamEqLoop: for (int i = 0; i < nvals; i++) { stream_o.write(stream_i.read()); } } } }
true
9023921512edfd489c85a00a847d5f31eca87ec4
C++
Predelnik/Toolbox
/src/macros/remap_rvalues_for.h
UTF-8
771
2.84375
3
[ "MIT" ]
permissive
#pragma once #include <utility> // useful for chaining functions. Just write original chaining function ref // qualified Then write REMAP_RVALUES_FOR (function name) it will add // appropriate overload for ref-ref-qualified case. Preserving reference // category of return type. #define REMAP_RVALUES_FOR(MEMBER_FUNC_NAME) \ template <typename... ArgTypes> \ auto &&MEMBER_FUNC_NAME(ArgTypes &&... args) && { \ return std::move( \ static_cast<std::remove_pointer_t<decltype(this)> &>(*this) \ .MEMBER_FUNC_NAME(std::forward<ArgTypes>(args)...)); \ }
true
b641a79dd2f14127e6d9a0e09154c53baa8f39e5
C++
mylvoh0714/BOJ
/10942.cpp
WINDOWS-1252
831
3.109375
3
[]
no_license
//BOJ 10942 Ӹ? #include <iostream> #include <vector> using namespace std; int dp[2001][2001]; // dp[start][end] = Check if arr[start]~arr[end] is palindrome, return 1 else 0 int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin >> n; vector<int> arr(n + 1); for ( int i = 1; i <= n; i++ ) { cin >> arr[i]; } for ( int i = 1; i <= n; i++ ) // dp length = 1 { dp[i][i] = 1; } for ( int i = 1; i <= n-1; i++ ) // dp length = 2 { if ( arr[i] == arr[i + 1] ) dp[i][i + 1] = 1; } for ( int len = 3; len <= n ; len++ ) { for ( int i = 1; i <= n - len + 1; i++ ) { if ( arr[i] == arr[i + len - 1] ) dp[i][i + len - 1] = dp[i + 1][i + len - 2]; } } int T; cin >> T; int a, b; for ( int i = 0; i < T; i++ ) { cin >> a >> b; cout << dp[a][b] << '\n'; } }
true
2403863157d33d54f638d2e12ceeda12eb1da1fc
C++
MrScriptX/Vulkan-Tile-Engine
/VulkanInstance.cpp
UTF-8
2,876
2.546875
3
[]
no_license
#include "VulkanInstance.h" VulkanInstance::VulkanInstance(std::shared_ptr<extensions> extensionsObj, std::shared_ptr<settings> settingsObj, std::shared_ptr<graphic> graphicObj) { m_pExtensions = extensionsObj; m_pSettings = settingsObj; m_pGraphic = graphicObj; VkApplicationInfo app_info = getApplicationInfo(); if (m_pSettings->validation_layer_enable && !checkLayersSupport()) { throw std::runtime_error("Requested layers are not available!"); } VkInstanceCreateInfo create_info = {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.pNext = nullptr; create_info.flags = 0; create_info.pApplicationInfo = &app_info; std::vector<const char*> extensions = getRequiredExtensions(); create_info.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); create_info.ppEnabledExtensionNames = extensions.data(); if (m_pSettings->validation_layer_enable) { create_info.enabledLayerCount = static_cast<uint32_t>(m_pExtensions->validationLayers.size()); create_info.ppEnabledLayerNames = m_pExtensions->validationLayers.data(); } else { create_info.enabledLayerCount = 0; } if (vkCreateInstance(&create_info, nullptr, &m_pGraphic->vulkan_instance) != VK_SUCCESS) { std::string error = "Failed to create vulkan instance!"; std::cerr << error << std::endl; Logger::registerError(error); } } VulkanInstance::~VulkanInstance() { } VkApplicationInfo VulkanInstance::getApplicationInfo() { VkApplicationInfo app_info = {}; app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; app_info.pNext = nullptr; app_info.pApplicationName = "Tile Engine"; app_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0); app_info.pEngineName = "VkTile"; app_info.engineVersion = VK_MAKE_VERSION(1, 0, 0); app_info.apiVersion = VK_API_VERSION_1_0; return app_info; } bool VulkanInstance::checkLayersSupport() { uint32_t layer_count = 0; vkEnumerateInstanceLayerProperties(&layer_count, nullptr); std::vector<VkLayerProperties> available_layers(layer_count); vkEnumerateInstanceLayerProperties(&layer_count, available_layers.data()); for (const char* layer_name : m_pExtensions->validationLayers) { bool layer_found = false; for (const VkLayerProperties& layer_properties : available_layers) { if (strcmp(layer_name, layer_properties.layerName) == 0) { layer_found = true; break; } } if (!layer_found) { return false; } } return true; } std::vector<const char*> VulkanInstance::getRequiredExtensions() { uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); if (m_pSettings->validation_layer_enable) { extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME); } return extensions; }
true
d0eb4627990e103a27fcbf8818bb7c27103a1b66
C++
HashMac/aadc2016
/aadcUser/include/adtf2OpenCV.h
UTF-8
3,798
2.859375
3
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <adtf_platform_inc.h> #include <adtf_plugin_sdk.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> // Convert an ADTF cImage to an OpenCV Mat. cv::Mat cImageToCV(const cImage& c) { const tInt16 format = c.GetFormat()->nPixelFormat; /*std::cout << "Pixel Format: " << c.GetFormat()->nPixelFormat << std::endl; std::cout << "Pixel Format 2: " << format << std::endl; std::cout << "BitsPerPixel: " << c.GetFormat()->nBitsPerPixel << std::endl; std::cout << "BitsPerPixel 2: " << c.GetBitsPerPixel() << std::endl; std::cout << "Palette Size: " << c.GetFormat()->nPaletteSize << std::endl;*/ int type = CV_8UC3; if( format == IImage::PF_GREYSCALE_8 ) { //std::cout << "CV_8UC1" << std::endl; type = CV_8UC1; } else if( format == IImage::PF_RGB_888 ) { //std::cout << "CV_8UC3" << std::endl; type = CV_8UC3; } else if( format == IImage::PF_GREYSCALE_16 ) { //std::cout << "CV_16UC1" << std::endl; type = CV_16UC1; } else if( format == IImage::PF_RGBA_8888 ) { //std::cout << "CV_8UC4" << std::endl; type = CV_8UC4; } else if( format == IImage::PF_GREYSCALE_FLOAT32 ) { //std::cout << "CV_32FC1" << std::endl; type = CV_32FC1; } else { std::stringstream ss; ss << "Wrong PixelFormat in input image: " << format << " (Unsupported by cImageToCV)."; LOG_ERROR( ss.str().c_str() ); } //std::cout << "Converting adtf pixel format " << format << " to OpenCV " << type << std::endl; return cv::Mat(c.GetHeight(),c.GetWidth(),type,c.GetBitmap()); } // Convert OpenCV image to ADTF image. // IMPORTANT: Currently only works if depth of image is 8 and it has 3 channels (RGB) or 1 channel (Grayscale). cImage cvToCImage( const cv::Mat& im ) { std::stringstream ss; cImage resultIm; tInt resultFormat = IImage::PF_UNKNOWN; if( im.type() == CV_8UC1 ) resultFormat = IImage::PF_GREYSCALE_8; else if( im.type() == CV_8UC3 ) resultFormat = IImage::PF_RGB_888; else if( im.type() == CV_16UC1 ) resultFormat = IImage::PF_GREYSCALE_16 ; else if( im.type() == CV_8UC4 ) resultFormat = IImage::PF_RGBA_8888; else if( im.type() == CV_32FC1 ) resultFormat = IImage::PF_GREYSCALE_FLOAT32; else { std::stringstream ss; ss << "Wrong PixelFormat in input image: " << im.type() << " (Unsupported by cvToCImage)."; LOG_ERROR( ss.str().c_str() ); return resultIm; } /*std::stringstream ss2; ss2 << "Creating: " << resultFormat << " " << im.elemSize(); LOG_WARNING( ss2.str().c_str() );*/ //std::cout << "Converting OpenCV pixel format " << im.type() << " to ADTF " << resultFormat << std::endl; //std::cout << "\tOpenCV elemSize: " << im.elemSize() << std::endl; //Create (tInt nWidth, tInt nHeight, tInt nBitsPerPixel, tInt nBytesPerLine=0, const tUInt8 *pBitmap=NULL, tInt nPixelFormat=0) tResult res = resultIm.Create(im.size().width, im.size().height, im.elemSize()*8, im.step, NULL, resultFormat); if( !res == ERR_NOERROR ) { LOG_ERROR( "Could not create ADTF image in cvToCImage!" ); return resultIm; } if( (size_t)resultIm.GetSize() != (size_t)im.step*im.rows ) { LOG_ERROR( "Something went wrong. Sizes of OpenCV image and ADTF image don't match. Cannot copy!" ); return resultIm; } /*ss << "Pixel format: " << pixelFormat << " w: " << im.size().width << " h: " << im.size().height; ss << " result size: " << resultIm.GetSize() << " source size: " << im.step*im.rows; LOG_WARNING( ss.str().c_str() );*/ // Get a pointer to the raw image data tUInt8* rawPtr = resultIm.GetBitmap(); if( rawPtr == NULL ) { LOG_ERROR( "Bitmap returned nullpointer when converting to ADTF format." ); } else { // Raw data copy: (YUCK!) // TODO: Test resultIm.SetBits function memcpy(rawPtr, (char*)im.data, im.step * im.rows); } return resultIm; }
true
1b79121b4c75b6c11bd188c80e7f4d47c98cd8ac
C++
stanleychen86/Hanoi
/Hanoi/workingSFML/player.h
UTF-8
339
2.703125
3
[]
no_license
#ifndef PLAYER_H #define PLAYER_H #include "entity.h" class Player : public Entity { private: int pointer_index; sf::RenderWindow& win; GameEntities& ge; void drawPointer(bool draw = true); public: Player(const std::vector<int>& p_order, sf::RenderWindow& p_win, GameEntities& ge); int select(); void takeTurn(); }; #endif
true
c3fe73fb652131043d6838d04983cec81e31b96b
C++
wowoto9772/Hungry-Algorithm
/BOJ/9465/solution.cpp
UTF-8
885
2.5625
3
[]
no_license
#include <stdio.h> #include <memory.h> int n; int I[2][100003]; int dp[2][100003]; int M(int a, int b){ return a < b ? b : a; } int dy(int i, int j){ if (dp[i][j] != -1)return dp[i][j]; dp[i][j] = 0; if (j < n){ if (i)dp[i][j] = I[i][j] + dy(0, j + 1); else dp[i][j] = I[i][j] + dy(1, j + 1); } for (int a = 0; a <= 1; a++){ for (int b = j + 2; b <= n && b <= j+4; b++){ dp[i][j] = M(dp[i][j], I[i][j] + dy(a, b)); } } if (!dp[i][j])dp[i][j] = I[i][j]; return dp[i][j]; } int main() { int t; scanf("%d", &t); while (t--){ scanf("%d", &n); for (int i = 0; i <= 1; i++){ for (int j = 1; j <= n; j++){ scanf("%d", &I[i][j]); } } memset(dp, 0xff, sizeof(dp)); int ans = 0; for (int i = 0; i <= 1; i++){ for (int j = 1; j <= n; j++){ int k = dy(i, j); ans = ans < k ? k : ans; } } printf("%d\n", ans); } }
true
d08611159b118f23753f1698ac605a8c74920cf0
C++
sagrudd/amos
/src/Align/simple-overlap.cc
UTF-8
12,920
2.609375
3
[ "Artistic-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// A. L. Delcher // // File: simple-overlap.cc // // Last Modified: Thu May 27 08:24:56 EDT 2004 // // Compute overlaps among an input set of sequences by // direct all-pairs alignment. #include "simple-overlap.hh" static string Bank_Name; // Name of read bank from which reads are obtained static double Error_Rate = DEFAULT_ERROR_RATE; // Fraction of errors allowed in overlap alignment static bool Fasta_Input = false; // If true, then input comes from the multifasta file named // on the command line static int Lo_ID = 0, Hi_ID = INT_MAX; // Range of indices for which to compute overlaps static int Min_Overlap_Len = DEFAULT_MIN_OVERLAP_LEN; // Minimum number of bases by which two sequences must overlap static bool Show_Alignment = false; // If true, then also output the overlap alignments int main (int argc, char * argv []) { BankStream_t read_bank (Read_t::NCODE); Simple_Overlap_t olap; vector <char *> string_list, qual_list; vector <char *> tag_list; vector <ID_t> id_list; vector <Range_t> clr_list; Alignment_t ali; time_t now; iostream :: fmtflags status; int i, j, n; try { now = time (NULL); cerr << "Starting on " << ctime (& now) << endl; Verbose = 0; Parse_Command_Line (argc, argv); if (Fasta_Input) cerr << "Fasta input file is " << Bank_Name << endl; else cerr << "Read bank is " << Bank_Name << endl; status = cerr . setf (ios :: fixed); cerr << "Alignment error rate is " << setprecision (2) << Error_Rate << endl; cerr . setf (status); cerr << "Minimum overlap bases is " << Min_Overlap_Len << endl; if (Fasta_Input) Read_Fasta_Strings (string_list, id_list, tag_list, Bank_Name); else { read_bank . open (Bank_Name, B_READ); Get_Strings_From_Bank (string_list, qual_list, clr_list, id_list, tag_list, read_bank); } n = string_list . size (); for (i = 0; i < n - 1; i ++) { double erate; int lo, hi; for (j = i + 1; j < n; j ++) { Simple_Overlap (string_list [i], strlen (string_list [i]), string_list [j], strlen (string_list [j]), olap); if (olap . a_olap_len < Min_Overlap_Len || olap . b_olap_len < Min_Overlap_Len) continue; erate = (2.0 * olap . errors) / (olap . a_olap_len + olap . b_olap_len); if (erate <= Error_Rate) { olap . a_id = id_list [i]; olap . b_id = id_list [j]; olap . flipped = false; Output (stdout, olap); if (Show_Alignment) { if (olap . a_hang <= 0) { lo = Max (- olap . a_hang - 5, 0); hi = - olap . a_hang + 5; Overlap_Align (string_list [i], strlen (string_list [i]), string_list [j], lo, hi, strlen (string_list [j]), 1, -3, -2, -2, ali); printf ( "\nOverlap a: %d .. %d of %d (%s) b: %d .. %d of %d (%s)\n", ali . a_lo, ali . a_hi, id_list [i], tag_list [i], ali . b_lo, ali . b_hi, id_list [j], tag_list [j]); ali . Print (stdout, string_list [i], string_list [j]); } else { lo = Max (olap . a_hang - 5, 0); hi = olap . a_hang + 5; Overlap_Align (string_list [j], strlen (string_list [j]), string_list [i], lo, hi, strlen (string_list [i]), 1, -3, -2, -2, ali); printf ( "\nOverlap a: %d .. %d of %d (%s) b: %d .. %d of %d (%s)\n", ali . a_lo, ali . a_hi, id_list [j], tag_list [j], ali . b_lo, ali . b_hi, id_list [i], tag_list [i]); ali . Print (stdout, string_list [j], string_list [i]); } } } } Reverse_Complement (string_list [i]); for (j = i + 1; j < n; j ++) { Simple_Overlap (string_list [i], strlen (string_list [i]), string_list [j], strlen (string_list [j]), olap); if (olap . a_olap_len < Min_Overlap_Len || olap . b_olap_len < Min_Overlap_Len) continue; erate = (2.0 * olap . errors) / (olap . a_olap_len + olap . b_olap_len); if (erate <= Error_Rate) { int save; if (Show_Alignment) { if (olap . a_hang <= 0) { lo = Max (- olap . a_hang - 5, 0); hi = - olap . a_hang + 5; Overlap_Align (string_list [i], strlen (string_list [i]), string_list [j], lo, hi, strlen (string_list [j]), 1, -3, -2, -2, ali); printf ( "\nOverlap a: %d .. %d of complement %d (%s) b: %d .. %d of %d (%s)\n", ali . a_lo, ali . a_hi, id_list [i], tag_list [i], ali . b_lo, ali . b_hi, id_list [j], tag_list [j]); ali . Print (stdout, string_list [i], string_list [j]); } else { lo = Max (olap . a_hang - 5, 0); hi = olap . a_hang + 5; Overlap_Align (string_list [j], strlen (string_list [j]), string_list [i], lo, hi, strlen (string_list [i]), 1, -3, -2, -2, ali); printf ( "\nOverlap a: %d .. %d of %d (%s) b: %d .. %d of complement %d (%s)\n", ali . a_lo, ali . a_hi, id_list [j], tag_list [j], ali . b_lo, ali . b_hi, id_list [i], tag_list [i]); ali . Print (stdout, string_list [j], string_list [i]); } } // Re-orient with a forward and b reversed save = olap . a_hang; olap . a_hang = - olap . b_hang; olap . b_hang = - save; olap . a_id = id_list [i]; olap . b_id = id_list [j]; olap . flipped = true; Output (stdout, olap); } } } read_bank . close (); } catch (Exception_t & e) { cerr << "** AMOS Exception **" << endl; cerr << e << endl; exit (EXIT_FAILURE); } catch (std :: exception & e) { cerr << "** Standard Exception **" << endl; cerr << e << endl; exit (EXIT_FAILURE); } return 0; } static void Get_Strings_From_Bank (vector <char *> & s, vector <char *> & q, vector <Range_t> & clr_list, vector <ID_t> & id_list, vector <char * > & tag_list, BankStream_t & read_bank) // Populate s and q with sequences and quality values, resp., // from read_bank . Put the clear-ranges for the sequences in clr_list . // read_bank must already be opened. Put the identifying tags for the // sequences in tag_list . { Read_t read; Ordered_Range_t position; int i, n; n = s . size (); for (i = 0; i < n; i ++) free (s [i]); s . clear (); n = q . size (); for (i = 0; i < n; i ++) free (q [i]); q . clear (); n = tag_list . size (); for (i = 0; i < n; i ++) free (tag_list [i]); tag_list . clear (); id_list . clear(); clr_list . clear (); char * tmp, tag_buff [100]; string seq; string qual; Range_t clear; int this_offset; int a, b, j, len, qlen; while ( read_bank >> read ) { id_list . push_back (read . getIID()); tag_list . push_back (strdup (read . getEID() . c_str())); clear = read . getClearRange (); if (Verbose > 2) cerr << read; seq = read . getSeqString (clear); qual = read . getQualString (clear); clr_list . push_back (clear); len = seq . length (); tmp = strdup (seq . c_str ()); for (j = 0; j < len; j ++) tmp [j] = tolower (tmp [j]); s . push_back (tmp); qlen = qual . length (); if (len != qlen) { sprintf (Clean_Exit_Msg_Line, "ERROR: Sequence length (%d) != quality length (%d) for read %d\n", len, qlen, read . getIID( )); Clean_Exit (Clean_Exit_Msg_Line, __FILE__, __LINE__); } tmp = strdup (qual . c_str ()); q . push_back (tmp); } return; } static void Output (FILE * fp, const Simple_Overlap_t & olap) // Print the contents of olap to fp . { fprintf (fp, "%5d %5d %c %5d %5d %5d %5d %5d %3d %4.2f\n", olap . a_id, olap . b_id, olap . flipped ? 'I' : 'N', olap . a_hang, olap . b_hang, olap . a_olap_len, olap . b_olap_len, olap . score, olap . errors, 200.0 * olap . errors / (olap . a_olap_len + olap . b_olap_len)); return; } static void Parse_Command_Line (int argc, char * argv []) // Get options and parameters from command line with argc // arguments in argv [0 .. (argc - 1)] . { bool errflg = false; int ch; optarg = NULL; while (!errflg && ((ch = getopt (argc, argv, "aE:Fho:v:")) != EOF)) switch (ch) { case 'a' : Show_Alignment = true; break; case 'E' : Error_Rate = strtod (optarg, NULL); break; case 'F' : Fasta_Input = true; break; case 'h' : errflg = true; break; case 'o' : Min_Overlap_Len = strtol (optarg, NULL, 10); break; case 'v' : Verbose = strtol (optarg, NULL, 10); break; case '?' : fprintf (stderr, "Unrecognized option -%c\n", optopt); default : errflg = true; } if (errflg) { Usage (argv [0]); exit (EXIT_FAILURE); } if (optind > argc - 1) { Usage (argv [0]); exit (EXIT_FAILURE); } Bank_Name = argv [optind ++]; return; } static void Read_Fasta_Strings (vector <char *> & s, vector <ID_t> & id_list, vector <char *> & tag_list, const std :: string & fn) // Open file named fn and read FASTA-format sequences from it // into s and their tags into tag_list . { FILE * fp; std :: string seq, hdr; fp = File_Open (fn . c_str (), "r", __FILE__, __LINE__); s . clear (); id_list . clear(); tag_list . clear (); char tag [MAX_LINE]; char * tmp; int j, len; int cnt = 0; while (Fasta_Read (fp, seq, hdr)) { if ( cnt >= Lo_ID && cnt < Hi_ID ) { tmp = strdup (seq . c_str ()); len = seq . length (); for (j = 0; j < len; j ++) tmp [j] = tolower (tmp [j]); s . push_back (tmp); sscanf (hdr . c_str (), "%s", tag); tag_list . push_back (strdup (tag)); id_list . push_back (cnt); } ++ cnt; } return; } static void Usage (const char * command) // Print to stderr description of options and command line for // this program. command is the command that was used to // invoke it. { fprintf (stderr, "USAGE: %s <bank-name>\n" "\n" "Compute pairwise overlaps among a set of sequences by\n" "brute-force all-pairs alignment. Sequences are obtained\n" "from <bank-name>\n" "\n" "Options:\n" " -a Also show alignments of overlaps \n" " -E <x> Maximum error rate for overlaps is <x>\n" " e.g., -E 0.06 for 6% error rate\n" " -F Input is a fasta file\n" " -h Print this usage message\n" " -o <n> Set minimum overlap length to <n>\n" " -v <n> Set verbose level to <n>. Higher produces more output.\n" "\n", command); return; }
true
6c3848d5b7051a126af06ded87ef6e4016e61c14
C++
TsurumiMasayuki/MyDirectXLib
/MyDirectXLib/Project1/Source/Math/RectF.cpp
UTF-8
188
2.515625
3
[]
no_license
#include "RectF.h" RectF::RectF() : RectF(0, 0, 0, 0) { } RectF::RectF(float x, float y, float width, float height) : x(x), y(y), width(width), height(height) { } RectF::~RectF() { }
true
9254db48c6231dae061c71cbc9fdace504d84ba9
C++
geneotech/Singularity
/misc/randval.h
UTF-8
681
2.578125
3
[]
no_license
#pragma once #include <random> #include <utility> extern int randval(int min, int max); extern unsigned randval(unsigned min, unsigned max); extern float randval(float min, float max); extern float randval(float minmax); extern unsigned randval(std::pair<unsigned, unsigned>); extern float randval(std::pair<float, float>); extern int randval(int min, int max, std::mt19937& gen); extern unsigned randval(unsigned min, unsigned max, std::mt19937& gen); extern float randval(float min, float max, std::mt19937& gen); extern unsigned randval(std::pair<unsigned, unsigned>, std::mt19937& gen); extern float randval(std::pair<float, float>, std::mt19937& gen);
true
e08772f07a3c9c8c67ffa934ff20ab7d1c94208e
C++
chufucun/rocana-impala-udfs
/median-test.cc
UTF-8
3,335
2.609375
3
[ "Apache-2.0" ]
permissive
// Copyright 2015 Rocana, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <math.h> #include <impala_udf/uda-test-harness.h> #include <impala_udf/udf-test-harness.h> #include "median.h" using namespace impala; using namespace impala_udf; using namespace std; // For algorithms that work on floating point values, the results might not match // exactly due to floating point inprecision. The test harness allows passing a // custom equality comparator. Here's an example of one that can tolerate some small // error. // This is particularly true for distributed execution since the order the values // are processed is variable. bool FuzzyCompare(const DoubleVal& x, const DoubleVal& y) { if (x.is_null && y.is_null) return true; if (x.is_null || y.is_null) return false; return fabs(x.val - y.val) < 0.00001; } // Reimplementation of FuzzyCompare that parses doubles encoded as StringVals. // TODO: This can be removed when separate intermediate types are supported in Impala 2.0 bool FuzzyCompareStrings(const StringVal& x, const StringVal& y) { if (x.is_null && y.is_null) return true; if (x.is_null || y.is_null) return false; // Note that atof expects null-terminated strings, which is not guaranteed by // StringVals. However, since our UDAs serialize double to StringVals via stringstream, // we know the serialized StringVals will be null-terminated in this case. double x_val = atof(string(reinterpret_cast<char*>(x.ptr), x.len).c_str()); double y_val = atof(string(reinterpret_cast<char*>(y.ptr), y.len).c_str()); return fabs(x_val - y_val) < 0.00001; } bool TestMedian() { // Setup the test UDAs. UdaTestHarness2<StringVal, StringVal, DoubleVal, IntVal> median( ReservoirSampleInit, ReservoirSampleUpdate, ReservoirSampleMerge, ReservoirSampleSerialize, AppxMedianFinalize); median.SetResultComparator(FuzzyCompareStrings); // Test empty input vector<DoubleVal> vals; vector<IntVal> samples; if (!median.Execute(vals, samples, StringVal::null())) { cerr << "Median: " << median.GetErrorMsg() << endl; return false; } // Initialize the test values. for (int i = 0; i < 1001; ++i) { vals.push_back(DoubleVal(i)); samples.push_back(IntVal(1001)); } double expected_median = 500; stringstream expected_median_ss; expected_median_ss << expected_median; string expected_median_str = expected_median_ss.str(); StringVal expected_median_sv(expected_median_str.c_str()); // Run the tests if (!median.Execute(vals, samples, expected_median_sv)) { cerr << "Median: " << median.GetErrorMsg() << endl; return false; } return true; } int main(int argc, char** argv) { bool passed = true; passed &= TestMedian(); cerr << (passed ? "Tests passed." : "Tests failed.") << endl; return 0; }
true
cb0de8b266b63684fa7a83418391669f18f15421
C++
slowriot/libtelegram
/include/libtelegram/types/video.h
UTF-8
2,145
2.90625
3
[ "MIT" ]
permissive
#ifndef TELEGRAM_TYPES_VIDEO_H_INCLUDED #define TELEGRAM_TYPES_VIDEO_H_INCLUDED #include "libtelegram/config.h" #include "helpers/optional.h" namespace telegram::types { struct video { /// See https://core.telegram.org/bots/api#video std::string file_id; // Unique identifier for this file int_fast32_t width = 0; // Video width as defined by sender int_fast32_t height = 0; // Video height as defined by sender int_fast32_t duration = 0; // Duration of the video in seconds as defined by sender std::optional<photosize> thumb; // Optional. Video thumbnail std::optional<std::string> mime_type; // Optional. MIME type of the file as defined by sender std::optional<int_fast32_t> file_size; // Optional. File size (in bytes) static video const from_json(nlohmann::json const &tree); static video const from_json(nlohmann::json const &tree, std::string const &path); }; inline video const video::from_json(nlohmann::json const &tree) { /// Factory to generate a struct of this type from the correct property tree /// If any non-optional elements are missing from the tree, throws std::domain_error return video{tree.at("file_id"), tree.at("width"), tree.at("height"), tree.at("duration"), helpers::make_optional_from_json<photosize>(tree, "thumb"), helpers::make_optional_from_json<std::string>(tree, "mime_type"), helpers::make_optional_from_json<int32_t>(tree, "file_size")}; } inline video const video::from_json(nlohmann::json const &tree, std::string const &path) { /// Helper to generate a struct of this type from a path within a tree /// If there is no such child, throws std::domain_error return from_json(tree.at(path)); } } #endif // TELEGRAM_TYPES_VIDEO_H_INCLUDED
true
5f3651269ae5e219661ecf7a8319147f1137887d
C++
Parkyunhwan/CodePlus_Basic
/Exemplary_solution/Seven_Dwarfs.cpp
UTF-8
782
2.90625
3
[]
no_license
//9개 중 7명의 키를 합했을 때 100 이 되는 경우를 찾는 문제 //9C2 이므로 36가지 경우가 발생 2중 포문을 통한 완전 탐색을 실시 한다. #include <iostream> #include <algorithm> using namespace std; int arr[10]; int n,result = 0; #define MAX 987654321; bool check = false; int main() { for(int i = 1; i < 9; i++) { cin >> arr[i]; result += arr[i]; } for(int i = 1; i <= 9; i++) { for(int j=i+1; j <=9; j++) { if(result - arr[i] - arr[j] == 100) { arr[i] = MAX; arr[j] = MAX; check = true; break; } } if(check) break; } sort(arr,arr+10); for(in) }
true
84f34aefb9e509c38b15740534a3a88276471b21
C++
ChauDinh/cpp_dummies
/Preprosessor.cpp
UTF-8
195
2.6875
3
[]
no_license
#include <iostream> #define TOREPLACE REPLACEWITH #define rep(i, a, b) for (int i = a; i < b; i++) using namespace std; int main() { rep(i, 0, 5) { cout << i << endl; }; return 0; }
true
474467e2c9fed46ad396a8ea3f3a3a0a9ebd7b48
C++
kalimfaria/Conference-Manager
/Dijkstra.h
UTF-8
12,268
3.5
4
[]
no_license
# ifndef DIJKSTRA_H # define DIJKSTRA_H #include <limits.h> #include <iostream> #include <vector> # include <string> using namespace std; void printPath (vector<int>a , vector <int> b, vector<int> c, int ); struct AdjListNode // node in an adj list { int dest; // destination double weight; // weight AdjListNode* next; AdjListNode () { dest = weight = 0; next = NULL ;} }; // an adjacency list-> linked list =) struct AdjList { public: AdjListNode *head; AdjList () { head = NULL; }//head pointer }; // A graph is an array of adjacency lists. // -> an array of linked lists =) // Size of array will be V (number of vertices in graph) (v by e ) struct Graph { int V; AdjList* array; Graph () { V = 0;} }; // A utility function to create a new adjacency list node AdjListNode* newAdjListNode(int dest, double weight) { AdjListNode* newNode = new AdjListNode; newNode->dest = dest; newNode->weight = weight; return newNode; } // A utility function that creates a graph of V vertices or an array of lists of the form V:Connected Edges Graph* createGraph(int V) { Graph* graph = new Graph; graph->V = V; graph->array = new AdjList [V]; return graph; } // Adds an edge to an undirected graph void addEdge(Graph* graph, int src, int dest, double weight) { //( insertion at head operation only) AdjListNode* newNode = newAdjListNode(dest, weight); newNode->next = graph->array[src].head; graph->array[src].head = newNode; // Since graph is undirected, add an edge from dest to src also // if it was directed, then we would simply skip this part =D -> FIND OUT FIRST IF DIRECTED/UNDIRECTED newNode = newAdjListNode(src, weight); newNode->next = graph->array[dest].head; graph->array[dest].head = newNode; } // Structure to represent a min heap node struct MinHeapNode { int v; double dist; }; // Structure to represent a min heap struct MinHeap { int size; // Number of heap nodes present currently -> length factor int capacity; // Capacity of min heap -> heapsize int *pos; // This is needed for decreaseKey() MinHeapNode **array; // we can also use a vector here MinHeap () { size = capacity = 0; pos = NULL; } // constructor }; // An initialiser for the MinHeapNode MinHeapNode* newMinHeapNode(int v, double dist) { MinHeapNode* minHeapNode = new MinHeapNode; minHeapNode->v = v; minHeapNode->dist = dist; return minHeapNode; } // A function to create a Min Heap MinHeap* createMinHeap(int capacity) { MinHeap* minHeap = new MinHeap; minHeap->pos = new int [capacity]; // this is the index for the array/heap minHeap->size = 0; // because nothing is added yet =) minHeap->capacity = capacity; minHeap->array = new MinHeapNode *[capacity]; // so now, we have an array of minheapnodes which are not pointing at each other. Not a linked list return minHeap; } // A utility function to swap two nodes of min heap. Needed for min heapify void swapMinHeapNode(MinHeapNode** a, MinHeapNode** b) { MinHeapNode* t = *a; *a = *b; *b = t; // copying nodes } // Position is needed for decreaseKey() void minHeapify(MinHeap* minHeap, int index) { int smallest, left, right; smallest = index; left = 2 * index + 1; // left child right = 2 * index + 2; // right child if (left < minHeap->size && minHeap->array[left]->dist < minHeap->array[smallest]->dist ) smallest = left; if (right < minHeap->size && minHeap->array[right]->dist < minHeap->array[smallest]->dist ) smallest = right; if (smallest != index) // leave the smallest where it is { // The nodes to be swapped in min heap MinHeapNode *smallestNode = minHeap->array[smallest]; MinHeapNode *indexNode = minHeap->array[index]; // Swap positions // update pointers minHeap->pos[smallestNode->v] = index; minHeap->pos[indexNode->v] = smallest; // Swap nodes // exchange values swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[index]); minHeapify(minHeap, smallest); } } // A function to check if the given minHeap is ampty or not int isEmpty(MinHeap* minHeap) { return minHeap->size == 0; } // Standard function to extract minimum node from heap struct MinHeapNode* extractMin(MinHeap* minHeap) { if (isEmpty(minHeap)) return NULL; // Store the root node MinHeapNode* root = minHeap->array[0];// the minimum value is always at 0 =D // Replace root node with last node MinHeapNode* lastNode = minHeap->array[minHeap->size - 1]; // BIGGEST VALUE minHeap->array[0] = lastNode; // pointers are repointed. Remember that the list is not a linked list, its an array of pointers // Update position of last node minHeap->pos[root->v] = minHeap->size-1; minHeap->pos[lastNode->v] = 0; // Reduce heap size and heapify root --(minHeap->size); minHeapify(minHeap, 0); // sifting return root; } // Function to decreasy dist value of a given vertex v. This function // uses pos[] of min heap to get the current index of node in min heap void decreaseKey(MinHeap* minHeap, int v, double dist) { // Get the index of v in heap array int i = minHeap->pos[v]; // Get the node and update its dist value minHeap->array[i]->dist = dist; // new key =( SADNESS // Travel up while the complete tree is not heapified. // This is a O(height of tree) loop while (i && (minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist)) // if dist of child is less than that of parent { // Swap this node with its parent // swap pointers minHeap->pos[minHeap->array[i]->v] = (i-1)/2; // child minHeap->pos[minHeap->array[(i-1)/2]->v] = i; // parent swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]); // move to parent index and then continue. Now we are sifting up i = (i - 1) / 2; } } // A utility function to check if a given vertex // 'v' is in min heap or not bool isInMinHeap(MinHeap *minHeap, int v) // because we need nodes to be labelled 1,2,3,4... { if (minHeap->pos[v] < minHeap->size) return true; return false; } // A utility function used to print the solution that is store in an array void printArr(double dist[], int n) { string arr[15] = {"SEECS", "SCME", "SMME", "RCMS", "IGIS", "SADA", "NBS", "ASAB", "CAMP", "HQ", "SCEE", "IqbalSquare", "Gate10", "Gate1", "RCMMW"}; cout << "Vertex Distance from Source" << endl; for (int i = 0; i < n; ++i) cout << arr[i] << "\t" << dist[i] << " metres" << endl; } // The main function that calulates distances of shortest paths from src to all // vertices. It is a O(ELogV) function void dijkstra(Graph* graph, int src) { int V = graph->V;// Get the number of vertices in graph double *dist = new double [V]; // dist values used to pick minimum weight edge vector <int> a ; // for u vector <int> b ; // for v vector <int> c ; // for sum of distances for (int i = 0; i < V; i++) // initialising dist[i] = 0; // helps pick the minimum edge to follow// sorted by distances MinHeap* minHeap = createMinHeap(V); // Initialize min heap with all vertices. dist value of all vertices for (int v = 0; v < V; ++v) { dist[v] = INT_MAX; // in other words, infinity minHeap->array[v] = newMinHeapNode(v, dist[v]); minHeap->pos[v] = v; } // Make dist value of src vertex as 0 so that it is extracted first minHeap->array[src] = newMinHeapNode(src, dist[src]); minHeap->pos[src] = src; dist[src] = 0; decreaseKey(minHeap, src, dist[src]); // from infinite to 0 =O // Initially size of min heap is equal to V. when we extract, it decreases minHeap->size = V; // In the following loop, min heap contains all nodes // whose shortest distance is not yet finalized. while (!isEmpty(minHeap)) { // Extract the vertex with minimum distance value MinHeapNode* minHeapNode = extractMin(minHeap); int u = minHeapNode->v; // Store the extracted vertex number // Traverse through all adjacent vertices of u (the extracted // vertex) and update their distance values AdjListNode* MinNode = graph->array[u].head;// accessing one index of adjacency list while (MinNode != NULL) { int v = MinNode->dest; // If shortest distance to v is not finalized yet, and weight of u-v // plus dist of u from src is less than dist value of v, then update // distance value of v if (isInMinHeap(minHeap, v) && (MinNode->weight + dist[u]) < dist[v]) { dist[v] = dist[u] + MinNode->weight; a.push_back(u); b.push_back(v); c.push_back(dist[v]); // update distance value in min heap also decreaseKey(minHeap, v, dist[v]); } MinNode = MinNode->next; // just like in a linked list } } printArr(dist, V); printPath(a,b,c,V); } void printPath (vector<int>a , vector <int> b, vector<int> c, int V ) { for ( int i = a.size()-1; i >= 0; i-- ) { for ( int j = i-1; j >= 0; j-- ) // moving further one step to the righ if (b[i] == b[j]) { a.erase(a.begin()+j); b.erase(b.begin()+j); c.erase(c.begin()+j); i = a.size()-1; j = i - 1; } } cout <<endl; /*for ( int i = 0; i < a.size(); i++ ) cout << a[i] << " " << b[i] << " " << c[i] << endl;*/ int **paths = new int*[V]; for ( int i = 0; i < V; i++ ) paths[i] = new int[V]; for ( int i = 0 ; i < V; i ++ ) for ( int j = 0 ; j < V; j ++ ) paths[i][j] = -1; int s = b.size(); for ( int i = 0; i < s/*V-1*/; i++ )// starting from the bottom of the list { paths[i][V-1] = b[b.size()-1]; paths[i][V-2] = a[a.size()-1]; int k = V-2; for ( int j = b.size()-1; j >= 0; j -- ) { if ( b[j] == paths[i][k] ) { k--; paths[i][k] = a[j]; } } b.pop_back(); a.pop_back(); } cout << endl; string arr[15] = {"SEECS", "SCME", "SMME", "RCMS", "IGIS", "SADA", "NBS", "ASAB", "CAMP", "HQ", "SCEE", "IqbalSquare", "Gate10", "Gate1", "RCMMW"}; cout << "Paths: " << endl; for ( int i = 0; i < V; i ++ ) { for ( int j = 0; j < V; j ++ ) if ( paths[i][j] != -1 ) cout << arr[paths[i][j]] << " "; cout << endl; } } void NUSTShortestPath() { int V = 15; string arr[15] = {"SEECS", "SCME", "SMME", "RCMS", "IGIS", "SADA", "NBS", "ASAB", "CAMP", "HQ", "SCEE", "IqbalSquare", "Gate10", "Gate1", "RCMMW"}; cout << "\n\t Your way around NUST:" << endl; for ( int i = 0; i < 15; i++ ) cout <<i << " " << arr[i] << endl; int i = 0; do { cout << "Please select your source location:" << endl; cin >> i; } while ( i > 14 || i < 0 ); Graph* graph = createGraph(V); addEdge(graph, 0, 2, 1356.73); addEdge(graph, 0, 9, 715.7); addEdge(graph, 0, 10, 910.67); addEdge(graph, 0, 14, 288.039); addEdge(graph, 0, 11, 790.206); addEdge(graph, 1, 5, 565.707); addEdge(graph, 1, 6, 834.556); addEdge(graph, 1, 7, 725.413); addEdge(graph, 1, 9, 921.741); addEdge(graph, 1, 12, 1119.16); addEdge(graph, 2, 10, 935.82); addEdge(graph, 3, 7, 50.3152); addEdge(graph, 3, 8, 38.7723); addEdge(graph, 4, 5, 92.9356); addEdge(graph, 4, 6, 239.724); addEdge(graph, 4, 11, 182.305); addEdge(graph, 5, 6, 204.624); addEdge(graph, 5, 8, 84.0953); addEdge(graph, 6, 12, 1027.91); addEdge(graph, 7, 11, 86.0585); addEdge(graph, 9, 11, 599.424); addEdge(graph, 9, 12, 1076.1); addEdge(graph, 10, 11, 698.512); addEdge(graph, 10, 13, 704.699); addEdge(graph, 11, 13, 485.027); addEdge(graph, 11, 14, 276.508); dijkstra(graph, i); } # endif
true
52dffc0605d9e62d5dc99dff6bc85b6cb9ee8580
C++
szaialt/CppGeometry
/bolyongas2/main.cc
UTF-8
7,474
2.75
3
[]
no_license
#include <SDL.h> #include <SDL_gfxPrimitives.h> #include <SDL_keyboard.h> #include <SDL_events.h> #include <math.h> #include <time.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <iostream> #include <vector> #include "wander.h" using namespace std; int min(int a, int b){ if (a < b) return a; else return b; } int max(int a, int b){ if (a > b) return a; else return b; } vector<color> generate_colors(int colorMaxValue){ vector<color> colors; color col; //fekete col.red = 0; col.green = 0; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //fehér col.red = colorMaxValue; col.green = colorMaxValue; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //rózsaszín col.red = colorMaxValue; col.green = colorMaxValue/2; col.blue = colorMaxValue/2; col.alpha = colorMaxValue; colors.push_back(col); //világoskék col.red = colorMaxValue/2; col.green = colorMaxValue/2; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //piros col.red = colorMaxValue; col.green = 0; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //sárga col.red = colorMaxValue; col.green = colorMaxValue; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //lila col.red = colorMaxValue/2; col.green = colorMaxValue/4; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //zöld col.red = 0; col.green = colorMaxValue/2; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //bordó col.red = colorMaxValue/2; col.green = 0; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //kék col.red = 0; col.green = 0; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //narancssárga col.red = colorMaxValue; col.green = colorMaxValue/2; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //narancssárga col.red = colorMaxValue; col.green = colorMaxValue/4; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //lila col.red = colorMaxValue/4; col.green = 0; col.blue = colorMaxValue/2; col.alpha = colorMaxValue; colors.push_back(col); //kék col.red = colorMaxValue/4; col.green = colorMaxValue/2; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //zöld col.red = 0; col.green = colorMaxValue; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //sárgászöld col.red = colorMaxValue/3; col.green = colorMaxValue; col.blue = 0; col.alpha = colorMaxValue; colors.push_back(col); //bíbor col.red = colorMaxValue/2; col.green = 0; col.blue = colorMaxValue/4; col.alpha = colorMaxValue; colors.push_back(col); //kékeszöld col.red = 0; col.green = colorMaxValue/2; col.blue = colorMaxValue/2; col.alpha = colorMaxValue; colors.push_back(col); //sötétkék col.red = 0; col.green = 0; col.blue = colorMaxValue/2; col.alpha = colorMaxValue; colors.push_back(col); //kékeslila col.red = colorMaxValue/4; col.green = 0; col.blue = colorMaxValue/2; col.alpha = colorMaxValue; colors.push_back(col); //rózsaszín col.red = colorMaxValue; col.green = colorMaxValue/3; col.blue = colorMaxValue/3; col.alpha = colorMaxValue; colors.push_back(col); //piros col.red = colorMaxValue; col.green = 0; col.blue = colorMaxValue/16; col.alpha = colorMaxValue; colors.push_back(col); //lila col.red = colorMaxValue/3; col.green = colorMaxValue/16; col.blue = colorMaxValue; col.alpha = colorMaxValue; colors.push_back(col); //barna col.red = colorMaxValue/2; col.green = colorMaxValue/4; col.blue = colorMaxValue/4; col.alpha = colorMaxValue; colors.push_back(col); //rózsaszín col.red = colorMaxValue; col.green = 0; col.blue = colorMaxValue/4; col.alpha = colorMaxValue; colors.push_back(col); return colors; } //Miért nem fordul???? vector <vector<int> > generate_matrix(int n, int m, wander* w){ vector<vector<int> > matrix = vector<vector<int> >(); point p = w->get_position(); for (int i = 0; i < n; i++){ vector<int> v = vector<int>(); for (int j = 0; j < m; j++){ if ((i == p.x) && (j == p.y)){ v.push_back(1); } else { v.push_back(0); } } matrix.push_back(v); } return matrix; } int main(int argc, char *argv[]) { SDL_Event ev; SDL_Surface *screen; /* SDL inicializálása és ablak megnyitása */ SDL_Init(SDL_INIT_VIDEO); screen=SDL_SetVideoMode(0, 0, 0, SDL_ANYFORMAT); if (!screen) { fprintf(stderr, "Nem sikerult megnyitni az ablakot!\n"); exit(1); } SDL_WM_SetCaption("SDL peldaprogram", "SDL peldaprogram"); int width = screen->w; int height = screen->h; int maxSize = min(width/5, height/5); int minSize = maxSize/5; int cellSize = 10; const int colorMaxValue = 255; const int half = colorMaxValue/2; const int state_number = 2; int t = 0; int d = maxSize*2; int x = 0; int y = 0; int dist = 20; // Itt rajzolj srand(time(NULL)); int n = width/cellSize; int m = height/cellSize; int vx = rand(); int vy = rand(); int x1 = vx % n; int y1 = vy % m; point p; p.x = x1; p.y = y1; wander* wander0 = new wander(n, m, p); int ny = max(n, m); vector<vector<int> > cell_matrix = generate_matrix(n, m, wander0); vector<color> colors = generate_colors(colorMaxValue); int index = rand() % colors.size(); color col = colors.at(index); while (SDL_WaitEvent(&ev) && ev.type!=SDL_QUIT && ev.type != SDL_KEYDOWN){ if (ev.type == SDL_KEYDOWN) { //Ez miért nem működik?? //SDLKey keyPressed = ev.key.keysym.sym; cout << "Billentyű észlelve." << endl; SDL_Quit(); } else if (ev.type == SDL_MOUSEBUTTONDOWN) { //Ez miért nem működik?? //SDLKey keyPressed = ev.key.keysym.sym; cout << "Egér észlelve." << endl; SDL_Quit(); } for (int i = 0; i < n; i++){ for (int j = 0; j < m; j++){ Sint16 x1 = i*cellSize + 1; Sint16 y1 = j*cellSize + 1; Sint16 x2 = (i+1)*cellSize; Sint16 y2 = (j+1)*cellSize; // state_number == 2 if ((cell_matrix.at(i)).at(j) == 1) boxRGBA(screen, x1, y1, x2, y2, col.red, col.green, col.blue, col.alpha); else if ((cell_matrix.at(i)).at(j) == 0) boxRGBA(screen, x1, y1, x2, y2, 0, 0, 0, colorMaxValue); } } wander0->go(); cell_matrix = generate_matrix(n, m, wander0); t = t+1; /* eddig elvegzett rajzolasok a kepernyore */ SDL_Flip(screen); sleep( 1 ); } /* ablak bezarasa */ SDL_Quit(); return 0; }
true
bbedffb48b06a431f8079e29e5a472b99358cb65
C++
hexen2k/cppio
/CPP2/CPP2/zadanie8.cpp
UTF-8
761
3.453125
3
[]
no_license
#include <iostream> #include <string> #include "zadanie8.h" using namespace std; void zadanie8(void) { char inbuff[1000]; char inchar; char * wynik = NULL; cout << "Podaj ciag znakowy do przeszukania: " << endl; cin >> inbuff; cout << "Podaj wyszukiwany znak: " << endl; cin >> inchar; wynik = znajdz(inbuff, inchar); if (wynik != NULL) { cout << "Tekst wystepujacy po drugim wystapieniu wyszukiwanego znaku (pierwszy to szukany znak): " << endl; cout << wynik << endl; } else { cout << "Nie znaleziono drugieo wystpienia znaku!" << endl; } } char * znajdz(char *s, char c) { char * wynik = NULL; int cnt = 0; while (*s++ != '\0') { if (*s == c) { cnt++; if (cnt == 2) { wynik = s; break; } } } return wynik; }
true
b88c72c2df2ba7e0e62d4efb007ee715f9e606f6
C++
SapphireSuite/Sapphire
/Engine/Include/Sapphire/Core/Debug/Log.hpp
UTF-8
2,306
2.84375
3
[ "MIT" ]
permissive
// Copyright 2020 Sapphire development team. All Rights Reserved. #pragma once #ifndef SAPPHIRE_CORE_LOG_GUARD #define SAPPHIRE_CORE_LOG_GUARD #include <ostream> #include <Core/Time/DateTime.hpp> #include <Core/Debug/LogLevel.hpp> #include <Core/Debug/LogChannel.hpp> namespace Sa { /** * \file Log.hpp * * \brief Sapphire's Log class. * * \ingroup Debug * \{ */ /** * \brief Sapphire's Log class. * * Contains log infos. */ class Log { public: /// Log's file name. const wchar* file = nullptr; /// Log's function name. const char8* function = nullptr; /// Log's line number. const uint32 line = 0u; /// Log's string message. const wchar* str = nullptr; /// Level of Log. const LogLvlFlag level; /// Log's channel. const LogChannel& channel; /// Date time of Log. const DateTime date; /** * \brief \e Value Constructor. * * \param[in] _file File of the Log. * \param[in] _function Function of the Log. * \param[in] _line Line of the Log. * \param[in] _str String of the Log. * \param[in] _level Level of the Log. * \param[in] _channel Channel of the Log. */ SA_ENGINE_API Log( const wchar* _file, const char8* _function, uint32 _line, const wchar* _str, LogLvlFlag _level, const LogChannel& _channel ) noexcept; /** * \brief \e Move constructor. * * \param[in] _other Other to construct from. */ SA_ENGINE_API Log(Log&& _other); /** * \brief \e Copy constructor. * * \param[in] _other Other to construct from. */ SA_ENGINE_API Log(const Log& _other); /** * \brief \e Output log into stream. * * \param[in,out] _stream Stream to output in. */ SA_ENGINE_API virtual void Output(std::wostream& _stream) const noexcept; /** * \brief \e Output this log into stream. * * \param[in,out] _stream Stream to output in. * * \return stream \e _stream parameter. */ SA_ENGINE_API std::wostream& operator>>(std::wostream& _stream) const noexcept; }; /** * \brief \e Output log into stream. * * \param[in,out] _stream Stream to output in. * \param[in,out] _log Log to output. * * \return stream \e _stream parameter. */ SA_ENGINE_API std::wostream& operator<<(std::wostream& _stream, const Log& _log) noexcept; /** \} */ } #endif // GUARD
true
f77ebf5822e281d7e591500dc442d481a67cdabe
C++
sasaki-seiji/ProgrammingLanguageCPP4th
/part3/ch19/19-4-list/src/List.h
UTF-8
476
2.9375
3
[]
no_license
/* * List.h * * Created on: 2016/08/19 * Author: sasaki */ #ifndef LIST_H_ #define LIST_H_ class List; class List_iterator { List* cur; public: List_iterator(List* p) : cur{p} { } void reset(List* p) { cur = p; } int *next(); }; class List { int value; List* next; public: List(int v) : value{v}, next{nullptr} { } List(int v, List* suc) : value{v}, next{suc} { } ~List() { delete next; } friend int* List_iterator::next(); }; #endif /* LIST_H_ */
true
5a1220a9d90c56e94a8ad8193df3f859d74df2a7
C++
demarrem29/MOBA
/Source/MOBA/EquipmentComponent.cpp
UTF-8
25,312
2.5625
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "EquipmentComponent.h" #include "MOBACharacter.h" #include "MOBAAttributeSet.h" #include "AbilitySystemComponent.h" void UItem::SetCurrentStacks(int32 NewStackCount) { // Destroy item if new stack count is 0 if (NewStackCount == 0) { MyOwner->EquipmentComponent->RemoveItemFromInventory(this, true); return; } // Stack count was not zero, use new value CurrentStacks = FMath::Clamp(NewStackCount, 1, MaxStacks); // Enforce valid stack count return; } ESlotType UEquipment::GetEquipmentSlotType() { switch (this->GetItemType()) { case EItemType::Armor: return ESlotType::Armor; case EItemType::BrainImplant: return ESlotType::BrainImplant; case EItemType::BodyImplant: return ESlotType::BodyImplant; case EItemType::Source: return ESlotType::OffHand; case EItemType::TwoHand: return ESlotType::MainHand; case EItemType::ArmorModule: return ESlotType::Armor; case EItemType::WeaponModule: return ESlotType::EitherHand; case EItemType::MainHand: return ESlotType::MainHand; case EItemType::OneHand: return ESlotType::EitherHand; default: return ESlotType::None; } } // Sets default values for this component's properties UEquipmentComponent::UEquipmentComponent() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. PrimaryComponentTick.bCanEverTick = true; // Set default MaxInventorySize and Initialize Inventory MaxInventorySize = 6; Inventory.Init(NULL, MaxInventorySize); } // Called when the game starts void UEquipmentComponent::BeginPlay() { Super::BeginPlay(); // ... } // Called every frame void UEquipmentComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); // ... } // Function to add an item to inventory. ExistingItem is an optional parameter. WARNING: ReturnedItem may be NULL. void UEquipmentComponent::AddItemToInventory(const TSubclassOf<class UItem> ItemClass, TArray<UItem*> &ReturnedItems, EInventoryMessage &Message, UItem* const ExistingItem, const int32 Quantity) { // Initialize variables bool Instanced = false; bool AnotherExists = false; bool Unique = false; bool CanStack = false; int32 AvailableInventorySlots = 0; UItem* Item = NULL; int32 QuantityRemaining = Quantity; int32 InventorySlotsRequired = 0; int32 SlotsUsed = 0; TArray<int32> EmptyInventorySlotIndices; // Holds position of empty slots in inventory // Arrays for delegate to broadcast TArray<UItem*> AffectedItems; TArray<int32> AffectedIndices; // Use ItemClass to get a default object UObject* ItemBPObj = ItemClass->ClassDefaultObject; Item = Cast<UItem>(ItemBPObj); // Verify item class is valid, abort if not if (!Item) { Message = EInventoryMessage::DoesNotExist; return; } AnotherExists = ClassAlreadyPresentInInventory(ItemClass); // Whether another item of the same class is present in inventory Unique = Item->GetUniqueOwned(); // Multiple of the same item class allowed in inventory? // Abort if the item is unique and another is in inventory if (AnotherExists && Unique) { Message = EInventoryMessage::Unique; return; } InventorySlotsRequired = (Quantity + Item->GetMaxStacks() - 1) / Item->GetMaxStacks(); // How many inventory slots are required // Find number of available inventory slots for (int i = 0; i < MaxInventorySize; i++) { // Create pointer to current inventory index UItem* CurrentItem = Inventory[i]; // Check if a valid pointer is there if (!CurrentItem->IsValidLowLevel()) { // No item is here, increment available slots and note the index of that empty slot AvailableInventorySlots++; EmptyInventorySlotIndices.Add(i); } } // Should we try to add stacks to an existing inventory slot before filling a new inventory slot? CanStack = (Item->GetMaxStacks() > 1) ? true : false; // If we can stack, check and see if any of the existing items have room for more stacks TArray<UItem*> FilterArray = ItemInstancesAlreadyPresentInInventory(ItemClass); if (CanStack) { // Get all items in inventory of the same class and check and see if any of them have room for more stacks SlotsUsed = InventorySlotsRequired; int32 QuantityStacked = 0; for (auto& AnotherItem : FilterArray) { // Test if the operation can be performed prior to actually changing anything if (AnotherItem->GetCurrentStacks() < AnotherItem->GetMaxStacks()) { // Item with available stacks found, add stacks and decrement number of stacks to add int32 AvailableStacks = AnotherItem->GetMaxStacks() - AnotherItem->GetCurrentStacks(); int32 StacksUsed = (QuantityRemaining >= AvailableStacks) ? AvailableStacks : QuantityRemaining; QuantityRemaining -= StacksUsed; SlotsUsed--; if (QuantityRemaining <= 0) break; } } if (SlotsUsed > AvailableInventorySlots) { Message = EInventoryMessage::InventoryFull; return; } } else // Item can't stack, each quantity is its own inventory slot { SlotsUsed = Quantity; if (SlotsUsed > AvailableInventorySlots) { Message = EInventoryMessage::InventoryFull; return; } } // Ready to actually make inventory changes, reset remaining quantity QuantityRemaining = Quantity; // Use stacks of existing item instances first if (CanStack) { for (auto& AnotherItem : FilterArray) { UItem* CurrentItem = CastChecked<UItem>(AnotherItem); // Find other item instances with available stacks if (CurrentItem->GetCurrentStacks() < CurrentItem->GetMaxStacks()) { // Item with available stacks found, add stacks and decrement number of stacks to add int32 AvailableStacks = CurrentItem->GetMaxStacks() - CurrentItem->GetCurrentStacks(); // Use whichever value is lower, quantity remaining or available stacks int32 StacksUsed = (QuantityRemaining >= AvailableStacks) ? AvailableStacks : QuantityRemaining; QuantityRemaining -= StacksUsed; // Update item to reflect stack change CurrentItem->SetCurrentStacks(CurrentItem->GetCurrentStacks() + StacksUsed); // End if there are no more stacks to add if (QuantityRemaining <= 0) break; // Add this item to the list of affected items if we haven't already ReturnedItems.AddUnique(CurrentItem); AffectedItems.Add(CurrentItem); AffectedIndices.Add(Inventory.Find(CurrentItem)); } } } // Create new inventory slots for each remaining slot required for (int32 i = 0; i < SlotsUsed; i++) { if (i == 0) { // Get Item Properties to determine what we can do Instanced = Cast<UItem>(ExistingItem) ? true : false; // Does the item exist already or do we need to create a new instance if (!Instanced) { Item = NewObject<UItem>(this, ItemClass); } else { Item = ExistingItem; } } else { Item = NewObject<UItem>(this, ItemClass); } int32 AvailableStacks = Item->GetMaxStacks(); int32 StacksUsed = (QuantityRemaining >= AvailableStacks) ? AvailableStacks : QuantityRemaining; QuantityRemaining -= StacksUsed; Item->SetCurrentStacks(StacksUsed); Item->SetOwner(CastChecked<AMOBACharacter>(this->GetOwner())); // Add item to inventory and update delegate arrays Inventory[EmptyInventorySlotIndices[i]] = Item; AffectedItems.Add(Item); AffectedIndices.Add(EmptyInventorySlotIndices[i]); // Add this item as a returned item reference ReturnedItems.Add(Item); if (QuantityRemaining <= 0) break; } Message = EInventoryMessage::Success; // Operation successfully added some items, broacast the delegate OnInventoryChange.Broadcast(AffectedItems, AffectedIndices); return; } // Function to remove an item from inventory. EInventoryMessage UEquipmentComponent::RemoveItemFromInventory(UItem* ItemToRemove, bool Delete, int32 NumberOfStacksToRemove) { // Verify that the item is actually in the inventory if (Inventory.Contains(ItemToRemove)) { // Create return value for delegate and add the item as an affected inventory slot TArray<UItem*> AffectedItems; TArray<int32> AffectedIndices; AffectedIndices.Add(Inventory.Find(ItemToRemove)); // Check if we are just removing some stacks or actually removing the entire item if (NumberOfStacksToRemove >= ItemToRemove->GetCurrentStacks()) { Inventory[Inventory.Find(ItemToRemove)] = NULL; if (ItemToRemove->GetItemType() == EItemType::Consumable || Delete) { ItemToRemove->BeginDestroy(); } } else { // Only Removing Stacks, decrement stacks and add item to delegate. item is not added if removed/deleted ItemToRemove->SetCurrentStacks(ItemToRemove->GetCurrentStacks() - NumberOfStacksToRemove); AffectedItems.Add(ItemToRemove); } // Broadcast Delegate and return OnInventoryChange.Broadcast(AffectedItems, AffectedIndices); return EInventoryMessage::Success; } // Item did not exist, do nothing and return else return EInventoryMessage::DoesNotExist; } // Function that allows users to drag and drop items to move them around to preferred inventory location UFUNCTION(BlueprintCallable) EInventoryMessage UEquipmentComponent::SwapItemsInInventory(int32 Index1, int32 Index2) { // Verify that both indices are valid and that at least one of the items exists. We can move to an empty slot if one of the items doesn't exist if ((Inventory.IsValidIndex(Index1) && Inventory.IsValidIndex(Index2)) && (Inventory[Index1]->IsValidLowLevel() || Inventory[Index2]->IsValidLowLevel())) { // Create arrays for the delegate to broadcast TArray<UItem*> AffectedItems; TArray<int32> AffectedIndices; // Create item pointers UItem* FirstItem = Inventory[Index1]; UItem* SecondItem = Inventory[Index2]; // Swap items Inventory[Index1] = SecondItem; Inventory[Index2] = FirstItem; // Fill arrays for delegate to broadcast AffectedItems.Add(FirstItem); AffectedItems.Add(SecondItem); AffectedIndices.Add(Index2); AffectedIndices.Add(Index1); // Broadcast and return OnInventoryChange.Broadcast(AffectedItems, AffectedIndices); return EInventoryMessage::Success; } else return EInventoryMessage::DoesNotExist; } int32 UEquipmentComponent::GetEmptyInventorySlots(TArray<int32>& OptionalIndexArray) { int32 EmptySlotCount = 0; for (auto & Item : Inventory) { if (!Item->IsValidLowLevel()) { EmptySlotCount++; if (OptionalIndexArray.GetData() != nullptr) { OptionalIndexArray.Add(Inventory.Find(Item)); } } } return EmptySlotCount; } // This function determines if we should add new stacks to an existing item, or create a new one. bool UEquipmentComponent::ClassAlreadyPresentInInventory(TSubclassOf<UItem> ItemClass) { for (auto & Item : Inventory) { if (Item->IsValidLowLevel()) { if (Item->GetClass() == ItemClass) { return true; } } } return false; } // Find all items in inventory of the given class TArray<UItem*> UEquipmentComponent::ItemInstancesAlreadyPresentInInventory(TSubclassOf<UItem> ItemClass) { TArray<UItem*> Filter; for (auto & Item : Inventory) { if (Item->IsValidLowLevel()) { if (Item->GetClass() == ItemClass) { Filter.Add(Item); } } } return Filter; } // Are we adding stacks to a specific item? bool UEquipmentComponent::ItemInstanceAlreadyPresentInInventory(UItem* Item) { TArray<UItem*> PresentItemsOfSameClass = ItemInstancesAlreadyPresentInInventory(Item->GetClass()); for (auto& ItemInstance : PresentItemsOfSameClass) { if (ItemInstance == Item) return true; } return false; } // Function to equip a new item on the character. EInventoryMessage UEquipmentComponent::Equip(ESlotType SlotToEquip, UEquipment* ItemToEquip) { // Make sure that passed in item is a valid equippable item if (ItemToEquip) { AMOBACharacter* MyOwner = Cast<AMOBACharacter>(this->GetOwner()); UItem* UpcastItem = CastChecked<UItem>(ItemToEquip); if (MyOwner) { // Verify that the item can actually be equipped in the desired slot EItemType ItemType = UpcastItem->GetItemType(); switch (ItemType) { case EItemType::Armor: if (SlotToEquip != ESlotType::Armor) return EInventoryMessage::WrongSlot; break; case EItemType::ArmorModule: if (SlotToEquip != ESlotType::Armor) return EInventoryMessage::WrongSlot; break; case EItemType::BrainImplant: if (SlotToEquip != ESlotType::BrainImplant) return EInventoryMessage::WrongSlot; break; case EItemType::BodyImplant: if (SlotToEquip != ESlotType::BodyImplant) return EInventoryMessage::WrongSlot; break; case EItemType::OneHand:if ((SlotToEquip != ESlotType::MainHand) || (SlotToEquip != ESlotType::OffHand)) return EInventoryMessage::WrongSlot; break; case EItemType::TwoHand:if (SlotToEquip != ESlotType::MainHand) return EInventoryMessage::WrongSlot; break; case EItemType::Source:if (SlotToEquip != ESlotType::OffHand) return EInventoryMessage::WrongSlot; break; case EItemType::WeaponModule:if ((SlotToEquip != ESlotType::MainHand) || (SlotToEquip != ESlotType::OffHand)) return EInventoryMessage::WrongSlot; break; default: return EInventoryMessage::InvalidEquipment; } // Check if an item is already equipped in the slot // Note: if the item is a module, there must already be an equipped item in the slot if (EquipmentSlots.Contains(SlotToEquip)) { UEquipment* FoundEquipment = *EquipmentSlots.Find(SlotToEquip); // There is an item equipped already. Check if the item to equip is a module and if it can fit in SlotToEquip if (ItemType == EItemType::ArmorModule || ItemType == EItemType::WeaponModule) { // Verify modules are placed on the correct type of equipment if (ItemType == EItemType::ArmorModule && SlotToEquip != ESlotType::Armor) return EInventoryMessage::WrongSlot; if (ItemType == EItemType::WeaponModule && Cast<UWeapon>(FoundEquipment) == NULL) return EInventoryMessage::WrongSlot; // Check if there is room for another module TArray<UEquipment*> ExistingModules = FoundEquipment->GetEquippedModules(); if ((FoundEquipment->GetMaxSlots() > ExistingModules.Num()) && (ExistingModules.Num() >= 0)) { ExistingModules.Add(ItemToEquip); if (ItemInstanceAlreadyPresentInInventory(ItemToEquip)) { RemoveItemFromInventory(ItemToEquip); } } else return EInventoryMessage::ModuleSlotsFull; } else // Not a module, need to unequip existing item { // Ignore two hand weapons for now, require additional checks that will be handled below if (ItemToEquip->GetItemType() != EItemType::TwoHand) { EInventoryMessage UnEquip = this->UnEquip(SlotToEquip); if (UnEquip != EInventoryMessage::Success) { return UnEquip; // Item could not be unequipped. Maybe not enough inventory space } } } } // Additional steps required for equipping a two hand weapon if (ItemToEquip->GetItemType() == EItemType::TwoHand) { int32 SlotsRequired = 0; bool TwoHandRemovedFromInventory = false; // Make sure that we actually can put enough items back in inventory to equip a two hand weapon if (ItemInstanceAlreadyPresentInInventory(ItemToEquip)) { RemoveItemFromInventory(ItemToEquip); TwoHandRemovedFromInventory = true; SlotsRequired--; } // Check if there are enough inventory slots to do the transaction TArray<int32> EmptyInventorySlotsArray; TArray<UItem*> ReturnedItems; EInventoryMessage AddItemsMessage; if (EquipmentSlots.Contains(ESlotType::MainHand)) SlotsRequired++; if (EquipmentSlots.Contains(ESlotType::OffHand)) SlotsRequired++; if (GetEmptyInventorySlots(EmptyInventorySlotsArray) < SlotsRequired) { // Not enough slots, put the two hand weapon back in inventory and abort if (TwoHandRemovedFromInventory) AddItemToInventory(ItemToEquip->GetClass(), ReturnedItems, AddItemsMessage, ItemToEquip, 1); return EInventoryMessage::InventoryFull; } // Checks passed, unequip the current weapon slots EInventoryMessage UnEquip = this->UnEquip(ESlotType::OffHand); // Check if the item was successfully unequipped or the slot is empty if (UnEquip != EInventoryMessage::Success && UnEquip != EInventoryMessage::DoesNotExist) { return UnEquip; // Item could not be unequipped. Maybe not enough inventory space } // Swap the item to be equipped with the main hand if (EquipmentSlots.Contains(ESlotType::MainHand)) { this->SwapEquipment(ItemToEquip, *EquipmentSlots.Find(ESlotType::MainHand)); return EInventoryMessage::Success; } } // If item is to be equipped in offhand slot, unequip a two hand weapon if its there if (SlotToEquip == ESlotType::OffHand) { if (EquipmentSlots.Contains(ESlotType::MainHand)) { UEquipment* MainHandWeapon = *EquipmentSlots.Find(ESlotType::MainHand); if (MainHandWeapon->GetItemType() == EItemType::TwoHand) { EInventoryMessage ReturnMessage = UnEquip(ESlotType::MainHand); if (ReturnMessage != EInventoryMessage::Success) { return EInventoryMessage::InvalidEquipment; } } } } // Did not contain an equipped item already else { if (ItemType == EItemType::ArmorModule || ItemType == EItemType::WeaponModule) { return EInventoryMessage::InvalidEquipment; // Can't equip a module on an empty slot } } // Equip new item if not a module (module already equipped above) Cast<UItem>(ItemToEquip)->SetOwner(MyOwner); // Add the item owner if (ItemType != EItemType::ArmorModule && ItemType != EItemType::WeaponModule) { if (!AddEquipmentToCharacter(ItemToEquip)) { return EInventoryMessage::DoesNotExist; } } RemoveItemFromInventory(ItemToEquip); return EInventoryMessage::Success; } return EInventoryMessage::DoesNotExist; } return EInventoryMessage::DoesNotExist; } EInventoryMessage UEquipmentComponent::UnEquip(ESlotType SlotToUnequip) { // Return storage containers for inventory operations TArray<UItem*> ReturnedItems; EInventoryMessage ReturnedMessage; // Verify there is at least one inventory slot available TArray<int32> EmptyInventorySlots; if (GetEmptyInventorySlots(EmptyInventorySlots) < 1) { return EInventoryMessage::InventoryFull; } // Verify there is actually something to remove from this slot if (!EquipmentSlots.Contains(SlotToUnequip)) { return EInventoryMessage::InvalidEquipment; } UEquipment* ItemToUnequip = *EquipmentSlots.Find(SlotToUnequip); // Attempt to remove the item if (!RemoveEquipmentFromCharacter(ItemToUnequip)) return EInventoryMessage::DoesNotExist; // Return the item to inventory AddItemToInventory(ItemToUnequip->StaticClass(), ReturnedItems, ReturnedMessage, ItemToUnequip); return EInventoryMessage::Success; } EInventoryMessage UEquipmentComponent::SwapEquipment(UEquipment* Equipment1, UEquipment* Equipment2) { // Verify both items are valid if (Equipment1->IsValidLowLevel() && Equipment2->IsValidLowLevel()) { // Verify we own both items if (Equipment1->GetOwner() == CastChecked<AMOBACharacter>(this->GetOwner()) && Equipment2->GetOwner() == CastChecked<AMOBACharacter>(this->GetOwner())) { // Verify items use the same slot type if (Equipment1->GetEquipmentSlotType() == Equipment2->GetEquipmentSlotType()) { // Verify that one of them is actually equipped already int32 SwapFirstItem = -1; if (EquipmentSlots.Contains(Equipment1->GetEquipmentSlotType())) { SwapFirstItem = 1; } else if (EquipmentSlots.Contains(Equipment2->GetEquipmentSlotType())) { SwapFirstItem = 0; } else { return EInventoryMessage::WrongSlot; } UEquipment* ItemToRemove; UEquipment* ItemToAdd; switch (SwapFirstItem) { case 0: { ItemToAdd = Equipment2; ItemToRemove = Equipment1; } case 1: { ItemToAdd = Equipment1; ItemToRemove = Equipment2; } default: return EInventoryMessage::DoesNotExist; } // Remove first item and granted gameplay effects if (!RemoveEquipmentFromCharacter(ItemToRemove)) { return EInventoryMessage::InvalidEquipment; } // Remove second item from inventory if it is in there if (ItemInstanceAlreadyPresentInInventory(CastChecked<UItem>(ItemToAdd))) { RemoveItemFromInventory(ItemToAdd); } // Equip second item and grant gameplay effects if (!AddEquipmentToCharacter(ItemToAdd)) { // Operation failed, undo previous removal operation AddEquipmentToCharacter(ItemToRemove); return EInventoryMessage::InvalidEquipment; } // Add first item to inventory TArray<UItem*> ReturnedItems; EInventoryMessage Message; AddItemToInventory(CastChecked<UItem>(ItemToRemove)->GetClass(), ReturnedItems, Message, ItemToRemove, 1); return EInventoryMessage::Success; } else { return EInventoryMessage::InvalidEquipment; } } // We don't own both items else { return EInventoryMessage::InvalidEquipment; } } // One or more items is(are) not valid else { return EInventoryMessage::DoesNotExist; } } bool UEquipmentComponent::AddEquipmentToCharacter(UEquipment* ItemToAdd) { // Verify item is a valid equippable item if (ItemToAdd->IsValidLowLevel()) { ESlotType EquipmentSlotType = ItemToAdd->GetEquipmentSlotType(); EItemType ItemType = ItemToAdd->GetItemType(); AMOBACharacter* MyOwner = ItemToAdd->GetOwner(); // Verify the slot is available if (!EquipmentSlots.Contains(EquipmentSlotType)) { // Verify we own the item to be equipped if (ItemToAdd->GetOwner() == CastChecked<AMOBACharacter>(this->GetOwner())) { // Add equipment to equipment slot, apply gameplay effects, and broadcast delegate EquipmentSlots.Add(EquipmentSlotType, ItemToAdd); for (auto Effect : Cast<UEquipment>(ItemToAdd)->GetGrantedEffects()) { FGameplayEffectContextHandle Context = CastChecked<AMOBACharacter>(MyOwner)->AbilitySystemComponent->MakeEffectContext(); CastChecked<AMOBACharacter>(MyOwner)->AbilitySystemComponent->BP_ApplyGameplayEffectToSelf(Effect.Key, Effect.Value, Context); } OnEquipmentChange.Broadcast((uint8)ItemToAdd->GetEquipmentSlotType(), ItemToAdd); if (ItemType == EItemType::OneHand || ItemType == EItemType::TwoHand) // Broadcast weapon attribute changes. Other attribute changes handled by attribute set { if (EquipmentSlotType == ESlotType::MainHand) MyOwner->AttributeSet->MainHandChange.Broadcast(MyOwner->AttributeSet->MainHandAttackSpeed.GetCurrentValue(), MyOwner->AttributeSet->MainHandMinDamage.GetCurrentValue(), MyOwner->AttributeSet->MainHandMaxDamage.GetCurrentValue(), MyOwner->AttributeSet->MainHandAttackRange.GetCurrentValue()); else if (EquipmentSlotType == ESlotType::OffHand) MyOwner->AttributeSet->OffHandChange.Broadcast(MyOwner->AttributeSet->OffHandAttackSpeed.GetCurrentValue(), MyOwner->AttributeSet->OffHandMinDamage.GetCurrentValue(), MyOwner->AttributeSet->OffHandMaxDamage.GetCurrentValue(), MyOwner->AttributeSet->OffHandAttackRange.GetCurrentValue()); } return true; } } } return false; } bool UEquipmentComponent::RemoveEquipmentFromCharacter(UEquipment* ItemToRemove) { // Verify equipment pointer is valid if (ItemToRemove->IsValidLowLevel()) { ESlotType EquipmentSlotType = ItemToRemove->GetEquipmentSlotType(); EItemType ItemType = ItemToRemove->GetItemType(); AMOBACharacter* MyOwner = ItemToRemove->GetOwner(); // Verify that the item is actually equipped already if (EquipmentSlots.Contains(EquipmentSlotType)) { if (*EquipmentSlots.Find(EquipmentSlotType) == ItemToRemove) { EquipmentSlots.Remove(EquipmentSlotType); for (auto Effect : Cast<UEquipment>(ItemToRemove)->GetGrantedEffects()) { FGameplayEffectContextHandle Context = MyOwner->AbilitySystemComponent->MakeEffectContext(); MyOwner->AbilitySystemComponent->RemoveActiveGameplayEffectBySourceEffect(Effect.Key, ItemToRemove->GetOwner()->AbilitySystemComponent); } OnEquipmentChange.Broadcast((uint8)EquipmentSlotType, ItemToRemove); if (ItemType == EItemType::OneHand || ItemType == EItemType::TwoHand) // Broadcast weapon attribute changes. Other attribute changes handled by attribute set { if (EquipmentSlotType == ESlotType::MainHand) MyOwner->AttributeSet->MainHandChange.Broadcast(MyOwner->AttributeSet->MainHandAttackSpeed.GetCurrentValue(), MyOwner->AttributeSet->MainHandMinDamage.GetCurrentValue(), MyOwner->AttributeSet->MainHandMaxDamage.GetCurrentValue(), MyOwner->AttributeSet->MainHandAttackRange.GetCurrentValue()); else if (EquipmentSlotType == ESlotType::OffHand) MyOwner->AttributeSet->OffHandChange.Broadcast(MyOwner->AttributeSet->OffHandAttackSpeed.GetCurrentValue(), MyOwner->AttributeSet->OffHandMinDamage.GetCurrentValue(), MyOwner->AttributeSet->OffHandMaxDamage.GetCurrentValue(), MyOwner->AttributeSet->OffHandAttackRange.GetCurrentValue()); } return true; } } } return false; }
true
8baccf87a0f547a4b824d2ac291bd1eb51dc958e
C++
SurroKun/Algo
/2 - Order Statistic Tree/Order Statistic Tree/commandline.h
UTF-8
1,345
2.71875
3
[]
no_license
#pragma once #include "store.h" #include <iostream> #include <string> #include <windows.h> using namespace std; class CommandLine { public: void run() { HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); string fileName; SetConsoleTextAttribute(hConsole, 14); cout << "Give me the name of the file with database : "; SetConsoleTextAttribute(hConsole, 15); cin >> fileName; SetConsoleTextAttribute(hConsole, 14); cout << "Do you want to see export process? Y/N : "; SetConsoleTextAttribute(hConsole, 15); char yn; cin >> yn; SetConsoleTextAttribute(hConsole, 14); cout << "Do you want to see trees? Y/N : "; SetConsoleTextAttribute(hConsole, 15); char yn2; cin >> yn2; bool displayImport = false; if (yn == 'Y') displayImport = true; bool displayTrees = false; if (yn2 == 'Y') displayTrees = true; Store store(fileName, displayImport); if (displayTrees) store.printTrees(); SetConsoleTextAttribute(hConsole, 14); cout << "\n\n--------------------------------------------------\n"; while (1) { SetConsoleTextAttribute(hConsole, 14); cout << "SEARCH\n"; SetConsoleTextAttribute(hConsole, 15); char category[100]; cout << "category : "; cin >> category; cout << "product : "; int rang; cin >> rang; store.printProduct(category, rang); } } };
true
0d1ebe4e94e7e443346638795375f72494918d25
C++
CubeDr/Bakejoon
/CLion/P2413.cpp
UTF-8
612
2.703125
3
[]
no_license
#include <cstdio> int n; int ns[50000]; // 현재 상태 int pos[50001]; // 원본의 위치 int main() { scanf("%d", &n); for(int i=0; i<n; i++) { scanf("%d", &ns[i]); pos[ns[i]] = i; } for(int i=0; i<n; i++) { // 한번 바뀐 숫자면 더 바꾸지 않음 if(pos[ns[i]] != i) continue; if(ns[i] == 1) continue; int j = pos[ns[i]-1]; // 바꿀 필요가 없음 if(j < i) continue; int t = ns[i]; ns[i] = ns[j]; ns[j] = t; } for(int i=0; i<n; i++) printf("%d ", ns[i]); return 0; }
true
1fa03c40e83aad8600118288e9dcfdbb1e7beb81
C++
prajapati-sachin/COP290-Assignment1
/cop/Common_functions.cpp
UTF-8
1,153
3.109375
3
[]
no_license
#include "Common_functions.h" using namespace std; //void print_Vertex2d(Vertex2d v){ // cout << "{" << v.x << "," << v.y << "}" <<"\n"; //} //void print_Vertex2d_List(Vertex2d_List v_list){ // cout << "Vertices : "; // for(int i=0;i<v_list.V.size();i++){ // print_Vertex2d(v_list.V[i]); // } //} //void print_Vertex3d(Vertex3d v){ // cout << "{" << v.x << " " << v.y << " " << v.z << "}" <<"\n"; //} //void print_Vertex3d_List(Vertex3d_List v_list){ // cout << "Vertices : "; // for(int i=0;i<v_list.V.size();i++){ // print_Vertex3d(v_list.V[i]); // } //} //void print_Edge2d(Edge2d e){ // cout<< " [v1: "; // print_Vertex2d(e.v1); // cout<< " v2: "; // print_Vertex2d(e.v2); // cout<< "]\n"; //} //void print_Edge2d_List(Edge2d_List e_list){ // cout << "Edges : "; // for(int i=0;i<e_list.E.size();i++){ // print_Edge2d(e_list.E[i]); // } //} //void print_Edge3d(Edge3d e){ // cout<< " [v1: "; // print_Vertex3d(e.x); // cout<< " v2: "; // print_Vertex3d(e.y); // cout<< "]\n"; //} //void print_Edge3d_List(Edge3d_List e_list){ // cout << "Edges : "; // for(int i=0;i<e_list.E.size();i++){ // print_Edge3d(e_list.E[i]); // } //}
true
8d77a933cd4dea9b40fe0eeb69033f2f7607fbf6
C++
dmtan90/QualityAssessor3
/example/CVStatisticsWindow.h
UTF-8
28,851
2.609375
3
[]
no_license
#pragma once #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> class CVStatisticsWindow { public: explicit CVStatisticsWindow( int max = 100, float font_scale = 0.5 ) : m_max( max ), m_font_scale( font_scale ),m_color(0,0,0) { m_mask = "MASK"; m_lbn = "QUALITYOFLBN"; m_light_value = -1; m_blur_value = -1; m_noise_value = -1; m_maskvalues.resize(5, -1); } void add_name( const std::string &name, int val = 0 ) { m_names.push_back( name ); m_values.push_back( val ); } void set_color(cv::Scalar color) { m_color = color; } void clear_name() { m_names.clear(), m_values.clear(); } void set_name( int index, const std::string &name ) { m_names[index] = name; } size_t size() const { return m_names.size(); } int &value( int index ) { return m_values[index]; } const int &value( int index ) const { return m_values[index]; } std::string &name( int index ) { return m_names[index]; } const std::string &name( int index ) const { return m_names[index]; } int &max() { return m_max; } const int &max() const { return m_max; } void value( int index, int val ) { m_values[index] = val; } void set_value( const std::string &name, int value ) { for(int i=0; i<m_names.size(); i++) { if(m_names[i] == name) { m_values[i] = value; break; } } } void set_name( const std::vector<std::string> &names ) { m_names = names; m_values.resize( names.size(), 0 ); } void set_name( const std::vector<std::string> &names, const std::vector<int> &values ) { m_names = names; m_values = values; } void set_mask_name(const std::string & name) { m_mask = name; } void set_mask_values(const std::vector<int> &value) { m_maskvalues = value; } void set_lbn_name(const std::string & name) { m_lbn = name; } void set_light_value(int value) { m_light_value = value; } void set_blur_value(int value) { m_blur_value = value; } void set_noise_value(int value) { m_noise_value = value; } void imshow( const std::string &winname ) const { if( m_canvas.empty() ) return; cv::imshow( winname, m_canvas ); } void imwrite( const std::string &filename ) const { if( m_canvas.empty() ) return; cv::imwrite( filename, m_canvas ); } void fillRectangle( cv::Mat &img, const cv::Rect &rect, const cv::Scalar &scalar, int lineType = 8 /*cv::LINE_8*/, int shift = 0, cv::Point offset = cv::Point() ) { std::vector<cv::Point> points = { { rect.x, rect.y }, { rect.x, rect.y + rect.height }, { rect.x + rect.width, rect.y + rect.height }, { rect.x + rect.width, rect.y }, }; const cv::Point *pts[1] = { points.data() }; int npts[] = { points.size() }; cv::fillPoly( img, pts, npts, 1, scalar, lineType, shift, offset ); } void update() { if( m_names.empty() ) { m_canvas = cv::Mat(); return; } size_t max_string_length = 0; for( auto &name : m_names ) if( name.length() > max_string_length ) max_string_length = name.length(); if(max_string_length < m_mask.length()) { max_string_length = m_mask.length(); } if(max_string_length < m_lbn.length()) { max_string_length = m_lbn.length(); } int letter_width = 20 * m_font_scale; int letter_height = 20 * m_font_scale; int name_area_width = letter_width * ( max_string_length + 2 ); int process_area_width = letter_width * 68; int percentage_area_width = letter_width * 10; int fieldwidth = letter_width * 6; int box_width = name_area_width + process_area_width + percentage_area_width; int box_height = letter_height * 3; int canvas_width = box_width; int canvas_height = box_height * (m_names.size() + 6) + 10; //std::cout << "------read 00----" << std::endl; //cv::Mat rightmat = cv::imread("/wqy/Downloads/right.jpg"); //std::cout << "------read 11----" << std::endl; //cv::Mat tmp(40,40, rightmat.type()); //cv::resize(rightmat, tmp, cv::Size(20,20), (0,0),(0,0)); //std::cout << "------read ok----" << std::endl; m_canvas = cv::Mat( canvas_height, canvas_width, CV_8UC3 , m_color); //m_canvas = cv::Mat::zeros( canvas_height, canvas_width, CV_8UC3 ); //tmp.copyTo(m_canvas); //cv::Mat cloneroi = m_canvas(cv::Rect(100, 10, 20,20)); //cv::addWeighted(cloneroi,1.0, m_canvas, 0.3,0,cloneroi); //tmp.copyTo(cloneroi); //int vert_step = (m_names.size() + 1) * box_height; int process_area_x = 0; int step = 0; std::string strname; for( int i = 0; i < m_names.size(); ++i ) { int box_y = box_height * i; int name_area_x = 0; strname = m_names[i]; if(m_names[i].length() < max_string_length) { std::string strtmp(max_string_length, ' '); strname = strtmp.substr(0, max_string_length - strname.length()) + strname; } strname += ":"; cv::Size textsize = cv::getTextSize(strname, 0, m_font_scale, 0, NULL); //cv::putText( m_canvas, strname, cv::Point( name_area_x + letter_width, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); process_area_x = name_area_x + name_area_width; //int process_area_x = name_area_x + name_area_width; cv::putText( m_canvas, strname, cv::Point( process_area_x - textsize.width - letter_width, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 0, 255 ) ); std::string percent_str = "LOW"; float percent_f = 0; if(m_values[i] == 1) { percent_str = "MEDIUM"; percent_f = 0.5; }else if(m_values[i] == 2) { percent_str = "HIGH"; percent_f = 1; } if(m_values[i] == 0) { cv::putText( m_canvas, "LOW", cv::Point( process_area_x, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 4 * letter_width, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 255, 0, 0 ), 1 ); }else { cv::putText( m_canvas, "LOW", cv::Point( process_area_x, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 4 * letter_width, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 4 * letter_width, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 4 * letter_width + 3, box_y + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step = 4 * letter_width + box_height - 6 + letter_width; if(m_values[i] == 1) { cv::putText( m_canvas, "MEDIUM", cv::Point( process_area_x + step, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 7 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, "MEDIUM", cv::Point( process_area_x + step, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 7 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 7 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 7 * letter_width + step + 3, box_y + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 7 * letter_width + box_height - 6 + letter_width; if(m_values[i] == 2) { cv::putText( m_canvas, "HIGH", cv::Point( process_area_x + step, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 255, 0 ), 1 ); }else { cv::putText( m_canvas, "HIGH", cv::Point( process_area_x + step, box_y + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, box_y + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step + 3, box_y + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } } /////////////////////////// //vert_step += box_height; int vert_step = (m_names.size() + 1) * box_height; strname = m_lbn; if(strname.length() < max_string_length) { std::string strtmp(max_string_length, ' '); strname = strtmp.substr(0, max_string_length - strname.length()) + strname; } strname += ":"; step = 0; //step = 4 * letter_width + box_height - 6 + letter_width; cv::Size textsize = cv::getTextSize(strname, 0, m_font_scale, 0, NULL); cv::putText( m_canvas, strname, cv::Point( name_area_width - textsize.width - letter_width, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 0, 255 ) ); if(m_light_value == 0) { cv::putText( m_canvas, "BRIGHT", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(0 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, "BRIGHT", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 6 * letter_width + box_height - 6 + letter_width; if(m_light_value == 1) { cv::putText( m_canvas, " DARK", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, " DARK", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } /* step += 8 * letter_width + box_height - 6 + letter_width; if(m_light_value == 2) { cv::putText( m_canvas, " NORMAL", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(0 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, " NORMAL", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } */ vert_step += box_height; step = 0; if(m_blur_value == 0) { cv::putText( m_canvas, " CLEAR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(0 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, " CLEAR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 6 * letter_width + box_height - 6 + letter_width; if(m_blur_value == 1) { cv::putText( m_canvas, " BLUR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, " BLUR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } /* step += 8 * letter_width + box_height - 6 + letter_width; if(m_blur_value == 2) { cv::putText( m_canvas, "SERIOUSBLUR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "SERIOUSBLUR", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 11 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } */ vert_step += box_height; step = 0; if(m_noise_value == 0) { cv::putText( m_canvas, " NOISE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, " NOISE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 6 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 6 * letter_width + box_height - 6 + letter_width; if(m_noise_value == 1) { cv::putText( m_canvas, " NONOISE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 255, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(0 , 255, 0 ), 1 ); }else { cv::putText( m_canvas, " NONOISE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } vert_step += box_height * 2; /////////////////// strname = m_mask; if(strname.length() < max_string_length) { std::string strtmp(max_string_length, ' '); strname = strtmp.substr(0, max_string_length - strname.length()) + strname; } strname += ":"; step = 0; textsize = cv::getTextSize(strname, 0, m_font_scale, 0, NULL); cv::putText( m_canvas, strname, cv::Point( name_area_width - textsize.width - letter_width, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 0, 0, 255 ) ); if(m_maskvalues[0] == 1) { cv::putText( m_canvas, "LEFT EYE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "LEFT EYE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 8 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 9 * letter_width + box_height - 6 + letter_width; if(m_maskvalues[1] == 1) { cv::putText( m_canvas, "RIGHT EYE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 9 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "RIGHT EYE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 9 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 9 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 9 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 9 * letter_width + box_height - 6 + letter_width; if(m_maskvalues[2] == 1) { cv::putText( m_canvas, "NOSE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "NOSE", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 5 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 6 * letter_width + box_height - 6 + letter_width; if(m_maskvalues[3] == 1) { cv::putText( m_canvas, "LEFT MOUTH CORNER", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 17 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "LEFT MOUTH CORNER", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 17 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 17 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 17 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } step += 17 * letter_width + box_height - 6 + letter_width; if(m_maskvalues[4] == 1) { cv::putText( m_canvas, "RIGHT MOUTH CORNER", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 255, 0, 0 ) ); fillRectangle( m_canvas, cv::Rect( process_area_x + 18 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB(255 , 0, 0 ), 1 ); }else { cv::putText( m_canvas, "RIGHT MOUTH CORNER", cv::Point( process_area_x + step, vert_step + 2 * letter_height ), 0, m_font_scale, CV_RGB( 122, 122, 122 ) ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 18 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 0, 0, 0 ), 1 ); fillRectangle( m_canvas, cv::Rect( process_area_x + 18 * letter_width + step, vert_step + 3, box_height - 6, box_height - 6 ), CV_RGB( 122, 122, 122 ), 1 ); cv::rectangle( m_canvas, cv::Rect( process_area_x + 18 * letter_width + step + 3, vert_step + 6, box_height - 12, box_height - 12 ), CV_RGB( 0, 0, 0 ), 1 ); } } private: int m_max; float m_font_scale; std::vector<std::string> m_names; std::vector<int> m_values; cv::Mat m_canvas; std::string m_mask; std::vector<int> m_maskvalues; std::string m_lbn; int m_light_value; int m_blur_value; int m_noise_value; cv::Scalar m_color; };
true
15853ebebc4249fcf41de3486ce9d3f758a8b10e
C++
idahoenigmann/eprog
/serie08/university/University.cpp
UTF-8
634
3
3
[]
no_license
// // Created by ida on 02.12.20. // #include "University.h" std::string University::getName() { return name; } std::string University::getCity() { return city; } unsigned int University::getNumStudents() { return num_students; } void University::setName(std::string new_name) { name = new_name; } void University::setCity(std::string new_city) { city = new_city; } void University::setNumStudents(unsigned int new_num_students) { num_students = new_num_students; } void University::graduate() { assert(num_students > 0); num_students--; } void University::newStudent() { num_students++; }
true
3c5d94c3eaaf46ba7b5cf7705c15c5c81f9db30a
C++
sagarsingla14/Codechef
/650LC.cpp
UTF-8
1,442
2.71875
3
[]
no_license
#include <bits/stdc++.h> #define ll long long int using namespace std; ll checkprime(ll n) { if(n == 2 || n ==3) { return 1; } ll flag = 1; for(ll i = 2 ; i <= sqrt(n) ; i++) { if((n % i) == 0) { flag = 0; break; } } if(flag) { return 1; } else{ return 0; } } ll highestfactor(ll n) { ll mx = 1; for(ll i = 2 ; i <= sqrt(n) ; i++) { if(n % i == 0) { ll f1 = i; ll f2 = n / i; mx = max(mx , f1); mx = max(mx , f2); } } return mx; } int main() { ll n; cin >> n; ll dp[1001] = {0}; dp[0] = 0 , dp[1] = 0 , dp[2] = 2 , dp[3] = 3 , dp[4] = 4 , dp[5] = 5; ll prime = checkprime(n); if(prime) { dp[n] = n; } else{ for(ll i = 6 ; i <= n ; i++) { if(checkprime(i)) { dp[i] = i; } else{ if(i % 2) { ll factor = highestfactor(i); cout << factor << endl; ll val = dp[factor]; dp[i] = dp[factor] + (i / factor); } else{ dp[i] = dp[i / 2] + 2; } } } } for(ll i = 0; i <= n ; i++) { cout << dp[i] << " "; } cout << endl; cout << dp[n] << endl; return 0; }
true
ae158a31c8621aaa9da84398609f7918515b328a
C++
uzbit/allegprogs
/evector/evector.h
UTF-8
1,232
3.34375
3
[]
no_license
#include<iostream.h> #include<stdlib.h> #include<conio.h> #ifndef _VECTOR_H #define _VECTOR_H template<class itype> class evector { public: evector(); evector(int size); ~evector(); int size(){return mysize;} itype& operator[](int index); void resize(int newsize); protected: int mysize; itype *mydata; }; template<class itype> evector<itype>::evector() :mysize(0), mydata(0) { } template<class itype> evector<itype>::evector(int size) :mysize(0), mydata(0) { mysize=size; mydata=new itype[mysize]; } template<class itype> evector<itype>::~evector() { delete mydata; mysize=0; } template<class itype> itype& evector<itype>::operator[](int index) { if(index>=mysize || index<0) { cout<<"ERROR IN INDEX: "<<index<<" MAX INDEX: "<<mysize-1<<'\n'; getch(); exit(1); } return mydata[index]; } template<class itype> void evector<itype>::resize(int newsize) { itype *temp=new itype[mysize]; for(int i=0;i<mysize;i++) temp[i]=mydata[i]; delete [] mydata; mydata=new itype[newsize]; for(int v=0;v<mysize;v++) mydata[v]=temp[v]; mysize=newsize; delete temp; } #endif
true
d35dd353a41e054a110d74399e7651639cf71c6d
C++
polinasand/Sockets-Alarm
/SocketClient/main.cpp
UTF-8
3,488
2.828125
3
[]
no_license
#include <winsock2.h> #include <iostream> #include <thread> #include <chrono> using namespace std; void print(); int printInterval(); int printAlarm(); void process(int, int, int, int); int alarmCount = 0; int main() { print(); return 0; } void print() { cout<<"Set time interval and 3 alarms\n"; for (int i =0 ; i < 32; i++) cout<<"="; cout<<'\n'; int interval = printInterval(); int t1 = printAlarm(), t2 = printAlarm(), t3 = printAlarm(); process(interval, t1, t2, t3); } int printInterval() { int interval; cout<<"Input int interval\n"; while (true) { if (!(cin>>interval)) { cout<<"Input int interval\n"; cin.clear(); cin.get(); continue; } break; } return interval; } int printAlarm() { cout<<"You can set only 3 alarms.\nInput 0, if you wanna skip one.\nInput int count of seconds>0, if you wanna set an alarm\n"; int t = -1; if (alarmCount < 3) { while (true) { if (!(cin>>t)) { cout<<"Set time in seconds\n"; cin.clear(); cin.get(); continue; } if (t>=0) break; } alarmCount++; cin.clear(); return t; } } void process(int Interval, int Alarm1, int Alarm2, int Alarm3) { WSADATA WsaData; int err = WSAStartup(MAKEWORD(2,2), &WsaData); if (err == SOCKET_ERROR) { printf("WSAStartup() failed: %ld\n", GetLastError()); system("PAUSE"); exit(1); } SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); SOCKADDR_IN anADDR; anADDR.sin_family = AF_INET; anADDR.sin_port = htons(228); anADDR.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); err = connect(s, (struct sockaddr*)&anADDR, sizeof(struct sockaddr)); if (err == SOCKET_ERROR) { printf("connect() failed: %ld\n", GetLastError()); system("PAUSE"); exit(1); } string interval = to_string(Interval); string alarm1 = to_string(Alarm1); string alarm2 = to_string(Alarm2); string alarm3 = to_string(Alarm3); // Declare and initialize variables. int bytesSent; int bytesRecv = SOCKET_ERROR; char sendbuf[32] = ""; char recvbuf[32] = ""; //---------------------- // Send and receive data. bytesSent = send( s, interval.c_str(), interval.size(), 0 ); printf( "Bytes Sent: %ld\n", bytesSent ); bytesSent = send( s, alarm1.c_str(), alarm1.size(), 0 ); printf( "Bytes Sent: %ld\n", bytesSent ); bytesSent = send( s, alarm2.c_str(), alarm2.size(), 0 ); printf( "Bytes Sent: %ld\n", bytesSent ); bytesSent = send( s, alarm3.c_str(), alarm3.size(), 0 ); printf( "Bytes Sent: %ld\n", bytesSent ); for (int i = 0; i < 32; i++) cout<<"-"; cout<<'\n'; while (1) { bytesRecv = SOCKET_ERROR; while( bytesRecv == SOCKET_ERROR ) { bytesRecv = recv( s, recvbuf, 32, 0 ); if ( bytesRecv == 0 || bytesRecv == WSAECONNRESET ) { printf( "Connection Closed.\n"); break; } if(bytesRecv == SOCKET_ERROR){ printf("%d\n", WSAGetLastError()); } } cout<<recvbuf; for (int i = 0; i < 32; i++) cout<<"-"; cout<<'\n'; } closesocket(s); WSACleanup(); system("PAUSE"); }
true
63111533c00067f1fbaa3fb14b274a03e5914b88
C++
LoveWX/OJ_mycoder
/hdu/2387.cpp
UTF-8
1,137
2.71875
3
[]
no_license
#include<iostream> using namespace std; struct price { long shops[5]; }; struct shop { long prices[5]; }; price p[5]; shop s[5]; int pn,sn,m; int cmp1(const void *a,const void *b) { return ((price*)a)->shops[m]-((price*)b)->shops[m]; } int cmp2(const void *aa,const void *bb) { int i; shop *a=(shop*)aa; shop *b=(shop*)bb; for(i=0;i<pn;i++) if(a->prices[i]!=b->prices[i]) return a->prices[i]-b->prices[i]; return 0; } int main() { int tcase,d=1,i,j,maxp,temp; while(scanf("%d",&tcase)!=EOF) { while(tcase-->0) { scanf("%d%d",&pn,&sn); maxp=2147483640; for(i=0;i<pn;i++) for(j=0;j<sn;j++) { scanf("%d",&temp); p[j].shops[i]=temp; if(temp<maxp) { m=i; maxp=temp; } } qsort(p,sn,sizeof(price),cmp1); for(i=0;i<pn;i++) for(j=0;j<sn;j++) s[i].prices[j]=p[j].shops[i]; qsort(s,pn,sizeof(shop),cmp2); printf("Scenario #%d:\n",d++); m=1; for(i=0;i<pn;i++) for(j=0;j<sn;j++) if(m==1) { printf("%d",s[i].prices[j]); m=0; } else printf(" %d",s[i].prices[j]); printf("\n\n"); } } return 0; }
true
4d029a008b3c4dbb54d6ae6e86dfe3fb784eaea0
C++
avpdiver/ETEngine
/Engine/source/EtMath/Vector.h
UTF-8
8,599
3.078125
3
[ "MIT" ]
permissive
#pragma once #pragma warning(disable : 4201) //nameless struct union - used in math library #include "MathUtil.h" #include <initializer_list> #include <array> namespace et { namespace math { enum ctor { uninitialized }; //Generic vector //************** // n = dimensions // T = data type // In 3D cartesian coordinate space: // Left handed - Y is up // Vectors are treated as columns when multiplied with matrices template <uint8 n, class T> struct vector { public: // members std::array<T, n> data; // constructors vector(); vector(const T &rhs); vector(const std::initializer_list<T> args); // operators T operator[] (const uint8 index) const; T& operator[] (const uint8 index); vector<n, T> operator-() const; // string conversion std::string ToString() const; operator std::string() const { return ToString(); } }; //specializations //*************** //vec2 template <typename T> struct vector<2, T> { union { std::array<T, 2> data; struct { T x; T y; }; }; vector(); vector(const T &rhs); vector(const std::initializer_list<T> args); vector(const T& x, const T& y); //operators T operator[] (const uint8 index) const; T& operator[] (const uint8 index); vector<2, T> operator-() const; //string conversion std::string ToString() const; operator std::string() const { return ToString(); } }; //vec3 template<typename T> struct vector<3, T> { union { std::array<T, 3> data; struct { T x; T y; T z; }; struct { vector<2, T> xy; T _vec3_ignored_z; }; struct { T _vec3_ignored_x; vector<2, T> yz; }; }; static vector<3, T> ZERO; static vector<3, T> UP; static vector<3, T> DOWN; static vector<3, T> LEFT; static vector<3, T> RIGHT; static vector<3, T> FORWARD; static vector<3, T> BACK; vector(); vector(const T &rhs); vector(const std::initializer_list<T> args); vector(const T& x, const T& y, const T& z); vector(const vector<2, T>& vec, const T& z); vector(const T& x, const vector<2, T>& vec); //operators T operator[] (const uint8 index) const; T& operator[] (const uint8 index); vector<3, T> operator-() const; //string conversion std::string ToString() const; operator std::string() const { return ToString(); } }; //vec4 template<typename T> struct vector<4, T> { union { std::array<T, 4> data; struct { T x; T y; T z; T w; }; struct { T r; T g; T b; T a; }; struct { vector<2, T> xy; T _vec4_ignored1_z; T _vec4_ignored1_w; }; struct { T _vec4_ignored2_x; vector<2, T> yz; T _vec4_ignored2_w; }; struct { T _vec4_ignored3_x; T _vec4_ignored3_y; vector<2, T> zw; }; struct { vector<3, T> xyz; T _vec4_ignored4_w; }; struct { vector<3, T> rgb; T _vec4_ignored_a; }; }; //constructors vector(); vector(const T &rhs); vector(const std::initializer_list<T> args); //with scalars vector(const T& x, const T& y, const T& z, const T& w); //with vec2 vector(const vector<2, T>& xy, const vector<2, T>& zw); vector(const vector<2, T>& xy, const T& z, const T& w); vector(const T& x, const T& y, const vector<2, T>& zw); vector(const T& x, const vector<2, T>& yz, const T& w); //with vec3 vector(const vector<3, T>& xyz, const T& w); vector(const T& x, const vector<3, T>& yzw); //operators T operator[] (const uint8 index) const; T& operator[] (const uint8 index); vector<4, T> operator-() const; //string conversion std::string ToString() const; operator std::string() const { return ToString(); } }; //operators //********* template <uint8 n, class T> std::ostream& operator<<( std::ostream& os, const math::vector<n, T>& vec); template <class T> std::ostream& operator<<( std::ostream& os, const math::vector<2, T>& vec); template <class T> std::ostream& operator<<( std::ostream& os, const math::vector<3, T>& vec); template <class T> std::ostream& operator<<( std::ostream& os, const math::vector<4, T>& vec); //negate // addition template <uint8 n, class T> vector<n, T> operator+(const vector<n, T> &lhs, const T scalar); template <uint8 n, class T> vector<n, T> operator+(const T scalar, const vector<n, T> &rhs); template <uint8 n, class T> vector<n, T> operator+(const vector<n, T> &lhs, const vector<n, T> &rhs); // subtraction template <uint8 n, class T> vector<n, T> operator-(const vector<n, T> &lhs, const T scalar); template <uint8 n, class T> vector<n, T> operator-(const vector<n, T> &lhs, const vector<n, T> &rhs); // multiplication template <uint8 n, class T> vector<n, T> operator*(const vector<n, T> lhs, const T &scalar); template <uint8 n, class T> vector<n, T> operator*(const T scalar, const vector<n, T> &lhs); template <uint8 n, class T> vector<n, T> operator*(const vector<n, T> &lhs, const vector<n, T> &rhs); // hadamard product //division template <uint8 n, class T> vector<n, T> operator/(const vector<n, T> &lhs, const T scalar); template <uint8 n, class T> vector<n, T> operator/(const T scalar, const vector<n, T> &rhs); template <uint8 n, class T> vector<n, T> operator/(const vector<n, T> &lhs, const vector<n, T> &rhs); //hadamard product //operations //********** template <uint8 n, class T> bool nearEqualsV(const vector<n, T> &lhs, const vector<n, T> &rhs, const T epsilon = ETM_DEFAULT_EPSILON_T ); template <uint8 n, class T> bool isZero(const vector<n, T> &lhs, const T epsilon = static_cast<T>(0)); template <uint8 n, class T> bool operator==(const vector<n, T> &lhs, const vector<n, T> &rhs); template <uint8 n, class T> T dot(const vector<n, T> &lhs, const vector<n, T> &rhs); //this is important so we do template specaializations template <class T> T dot(const vector<2, T> &lhs, const vector<2, T> &rhs); template <class T> T dot(const vector<3, T> &lhs, const vector<3, T> &rhs); template <class T> T dot(const vector<4, T> &lhs, const vector<4, T> &rhs); template <uint8 n, class T> T lengthSquared(const vector<n, T> &vec); template <uint8 n, class T> T length(const vector<n, T> &vec); template <uint8 n, class T> T distance(const vector<n, T> &lhs, const vector<n, T> &rhs); template <uint8 n, class T> T distanceSquared(const vector<n, T> &lhs, const vector<n, T> &rhs); template <uint8 n, class T> vector<n, T> normalize(const vector<n, T> &vec); template <uint8 n, class T> vector<n, T> pow(const vector<n, T> &vec, T exponent); //Vectors need to be prenormalized //if input vectors are zero it will generate NaN template <uint8 n, class T> T angleFastUnsigned(const vector<n, T>& lhs, const vector<n, T>& rhs); template <uint8 n, class T> T angleSafeUnsigned(const vector<n, T>& lhs, const vector<n, T>& rhs); // project source vector onto target vector template <uint8 n, class T> T vecProjectionFactor(vector<n, T> const& source, vector<n, T> const& target); template <uint8 n, class T> vector<n, T> vecProjection(vector<n, T> const& source, vector<n, T> const& target); //access to array for the graphics api template<uint8 n, typename T> T const* valuePtr( vector<n, T> const& vec ); template<uint8 n, typename T> T* valuePtr( vector<n, T>& vec ); template<typename T, uint8 n, typename T2> vector<n, T> vecCast(const vector<n, T2> &vec); template<uint8 n, typename T> vector<n, T> swizzle(vector<n, T> const& vec, vector<n, int32> const& indices); //dimension specific operations //***************************** //vec2 template<class T> vector<2, T> perpendicular(const vector<2, T>& vec); //Vectors need to be prenormalized template<class T> T angleSigned(const vector<2, T>& lhs, const vector<2, T>& rhs); //vec3 //direction will be left handed (lhs = thumb, rhs = index, result -> middle finger); template<class T> vector<3, T> cross(const vector<3, T>& lhs, const vector<3, T>& rhs); //inputs vectors must be prenormalized, //and, for accurate measurments the outAxis should also be normalized after //if input vectors are zero it will generate NaN template<class T> T angleFastAxis(const vector<3, T>& lhs, const vector<3, T>& rhs, vector<3, T> &outAxis); template<class T> T angleSafeAxis(const vector<3, T>& lhs, const vector<3, T>& rhs, vector<3, T> &outAxis); } // namespace math //shorthands typedef math::vector<2, float> vec2; typedef math::vector<3, float> vec3; typedef math::vector<4, float> vec4; typedef math::vector<2, math::int32> ivec2; typedef math::vector<3, math::int32> ivec3; typedef math::vector<4, math::int32> ivec4; typedef math::vector<2, double> dvec2; typedef math::vector<3, double> dvec3; typedef math::vector<4, double> dvec4; } // namespace et #include "Vector.inl"
true
81f7aa0095cebc82aa97b3e4d4752cba5ee832ca
C++
dfs-minded/solving_algos
/Practicing/CyclesViaEdges.h
UTF-8
2,005
3.109375
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <vector> #include <tuple> #include <set> #include <algorithm> #include <numeric> using namespace std; vector<vector<int>> Read(int& edges_num) { ifstream input; input.open("input.txt"); vector<vector<int>> graph; if (input.is_open()) { int V, E; input >> V >> E; graph.resize(V, vector<int>()); for (int e = 0; e < E; ++e) { int from, to; input >> from >> to; --from; --to; graph[from].push_back(to); graph[to].push_back(from); } edges_num = E; input.close(); } return graph; } void Write(int res) { ofstream output("output.txt"); if (output.is_open()) { output << res; output.close(); } } // DFS on finding bridges in a graph void Solve(const vector<vector<int>>& graph, int curr, int parent, int depth, vector<bool>& visited, vector<int>& min_depth_can_reach, /*vector<int>& entry_depth,*/ int& res) { visited[curr] = true; min_depth_can_reach[curr] /*= entry_depth[curr]*/ = depth; for (auto adj : graph[curr]) { if (adj == parent) continue; if (!visited[adj]) { Solve(graph, adj, curr, depth + 1, visited, min_depth_can_reach, /*entry_depth,*/ res); min_depth_can_reach[curr] = min(min_depth_can_reach[curr], min_depth_can_reach[adj]); if (min_depth_can_reach[adj] > depth) ++res; // found a bridge } else min_depth_can_reach[curr] = min(min_depth_can_reach[curr], min_depth_can_reach[adj] /*entry_depth[adj]*/); } } int Solve(vector<vector<int>> graph, int edges_num) { int N = graph.size(); vector<bool> visited(N); //vector<int> entry_depth(N); vector<int> min_depth_can_reach(N); int res = 0; for (int i = 0; i < N; ++i) { if (!visited[i]) Solve(graph, i, -1, 0, visited, min_depth_can_reach, /*entry_depth,*/ res); } return edges_num - res; } int main() { int edges_num = 0; auto graph = Read(edges_num); Write(Solve(graph, edges_num)); return 0; }
true
5d478f062f7f9a9222804cd1f0e4e78eb0914bac
C++
Frangalante24/AURORA-3.0
/MAIN/SENSORES/MPU.ino
UTF-8
625
2.578125
3
[]
no_license
// Biblioteca para a comunicacao I2C #include<Wire.h> #include <MPU6050.h> MPU6050 mpu; float AcX,AcY,AcZ; void setup() { Serial.begin(9600); Wire.begin(); Wire.setClock(400000); mpu.initialize(); mpu.setFullScaleAccelRange(3); mpu.setXAccelOffset(769); mpu.setYAccelOffset(1115); mpu.setZAccelOffset(-1625); //Inicializa o MPU-6050 em modo normal } void loop() { AcX = mpu.getAccelerationX() / 1024.0; AcY = mpu.getAccelerationY() / 1024.0; AcZ = mpu.getAccelerationZ() / 1024.0; Serial.println(AcX); Serial.println(AcY); Serial.println(AcZ); delay(1000); }
true
23ef0b8c49080121c712e481ac033f744a526ef7
C++
saturnerianis/satsolver
/HannahSatSolver/more2sat.cpp
UTF-8
9,234
3.4375
3
[]
no_license
/* * Hannah Christenson * * Functions to solve 2sat in linear time * */ #include <stack> #include <list> #include <unordered_map> #include <iostream> #include <cmath> #include <vector> using namespace std; typedef unordered_map<int, list<int> > graph; typedef vector<vector<int> > bool_formula; typedef unordered_map<int, bool> assignment; void print_graph(graph &the_graph); void print_soln(const unordered_map<int,bool> &soln); /* * A function which takes a vector of vectors, representing * a vector of clauses of length less than or equal to 2 * and, in any clause which has only one literal, duplicates that * literal within the clause, so that it has a length of two * PRECONDITION: each sub-vector has length 1 or 2 * POSTCONDITION: each sub-vector has length 2, and sub-vectors * that originally had length one have a copy of the first entry * as the second entry */ void make_2SAT(bool_formula &fml){ for(vector<int> vec: fml) if(vec.size() == 0 || vec.size() > 2) cout << "clause length that is not 1 or 2 encountered" << endl; else if(vec.size() == 1) vec.push_back(vec[0]); } /* * a function that converts a 2sat formula to both a forward and * reverse graph such that, for every clause of literals 1 and 2, * there is an edge from -1->2 and -2->1 in the graph * PRECONDITION: each clause in the formula has exactly 2 literals */ pair<graph, graph> formula_to_graph(const bool_formula & clause_list){ graph forward_graph; graph reverse_graph; for(vector<int> vec: clause_list){ int literal_1 = vec[0]; int literal_2 = vec[1]; //add the edges, make sure that the counterparts exist as vertices forward_graph[-literal_1].push_back(literal_2); forward_graph[-literal_2].push_back(literal_1); reverse_graph[literal_1].push_back(-literal_2); reverse_graph[literal_2].push_back(-literal_1); forward_graph[literal_1]; forward_graph[literal_2]; reverse_graph[-literal_1]; reverse_graph[-literal_2]; } return pair<graph,graph>(forward_graph, reverse_graph); } /* * A function that performs depth first search in a given directed graph * from a given vertex, pushing that vertex onto the stack once it has * been fully expanded * PRECONDITION: vertex is in the graph and has not yet been visited */ void depth_first_search_stack(unordered_map<int, bool> & visited, stack<int> & st, const graph & the_graph, int vertex){ visited[vertex] = true; for(int edge: the_graph.at(vertex)) if(visited.find(edge) == visited.cend()) depth_first_search_stack(visited, st, the_graph, edge); st.push(vertex); } /* * A function that performs depth-first search, noting which vertex initiated * search for each vertex that is "discovered," and adding all discovered * vertices to a list * PRECONDITIONS: vertex is in the graph and has not yet been marked off as having * a leader */ void depth_first_search_list(list<int> & the_list, const graph & the_graph, int vertex, int leader, unordered_map<int, int> &leaders){ leaders[vertex] = leader; for(int edge: the_graph.at(vertex)) if(leaders.find(edge) == leaders.end()) depth_first_search_list(the_list, the_graph, edge, leader, leaders); the_list.push_back(vertex); } /* * A function that returns a vector of the strongly connected components of a graph, * represented as lists themselves, and a map from vertices to the "leaders" of their * scc, in a pair */ pair<vector<list<int> >, unordered_map<int,int> > find_strongly_connected_components(const pair<graph, graph> & graphs){ unordered_map<int, bool> visited; stack<int> st; vector<list<int> > connected_components; unordered_map<int, int> leaders; //iterate through the vertices of the graph for(pair<int,list<int> > vertex: graphs.first){ //if the vertex has not been visited perform depth first search with the stack //which will add vertices such that strongly connected components will be //found in the reverse topological order in the second pass, since we use the //reverse graph if (visited.find(vertex.first) == visited.end()) { depth_first_search_stack(visited, st, graphs.second, vertex.first); } } //while the stack is not empty, find the connected component of the top element whose //scc has not yet been identified by dfs. because we find the first node of the scc's in //reverse topological order, we will find exactly an scc with dfs while(!st.empty()){ if(leaders.find(st.top()) == leaders.end()){ list<int> connected_component; depth_first_search_list(connected_component, graphs.first, st.top(), st.top(), leaders); connected_components.push_back(connected_component); } st.pop(); } return pair<vector<list<int> >, unordered_map<int,int> > (connected_components, leaders); } /* * A function which returns a bool indicating whether or not the original * boolean formula is satisfiable, by determining if any literal and its * negation are in the same strongly connected component * * PRECONDITION: the negation of each key is also represented in leaders */ bool check_satisfiability(const unordered_map<int, int> &leaders){ for(pair<int,int> leader: leaders) if(leaders.at(leader.first) == leaders.at(-leader.first)) return false; return true; } /* * A function which checks to see if any vertex in the connected component has * already been assigned a value. If that is the case, assign all variables in * the cc to false; otherwise, assign all variables in the cc true */ void solution_helper(const list<int> & cc, assignment &soln){ bool b = true; for(int i: cc) if(soln.find(-i) != soln.cend()){ b = false; break; } for(int i: cc) soln[i] = b; } /* * A fucntion which assigns values to the literals in such a way * that the formula is * * PRECONDITION: strongly connected components are ordered in reverse * topological order */ void solution(const vector<list<int> > scc, assignment &soln){ for(list<int> cc: scc) solution_helper(cc, soln); } unordered_map<int,bool> two_sat_solver(bool_formula &fml, assignment &asgt){ make_2SAT(fml); pair<vector<list<int> >, unordered_map<int,int> > results = find_strongly_connected_components(formula_to_graph(fml)); //way to avoid copy constructor?? if(!check_satisfiability(results.second)){ unordered_map<int,bool> empty; return empty; } solution(results.first, asgt); asgt[0] = true; return asgt; } // int main() { // //make a formula // bool_formula clause_list; // // vector<int> pair_1(2); // // pair_1[0] = -1; // // pair_1[1] = 2; // // vector<int> pair_2(2); // // pair_2[0] = -2; // // pair_2[1] = 3; // // vector<int> pair_3(2); // // pair_3[0] = 1; // // pair_3[1] = -3; // // vector<int> pair_4(2); // // pair_4[0] = 3; // // pair_4[1] = 2; // // clause_list.push_back(pair_1); // // clause_list.push_back(pair_2); // // clause_list.push_back(pair_3); // // clause_list.push_back(pair_4); // vector<int> pair_1(2); // pair_1[0] = 1; // pair_1[1] = 3; // vector<int> pair_2(2); // pair_2[0] = -2; // pair_2[1] = 4; // vector<int> pair_3(2); // pair_3[0] = -4; // pair_3[1] = 3; // vector<int> pair_4(2); // pair_4[0] =-3; // pair_4[1] = 5; // vector<int> pair_5(2); // pair_5[0] = -5; // pair_5[1] = -1; // // vector<int> pair_6(2); // // pair_6[0] = 2; // // pair_6[1] = 3; // vector<int> pair_7(2); // pair_7[0] = -3; // pair_7[1] = -5; // // vector<int> pair_8(2); // // pair_8[0] = -12; // // pair_8[1] = -32; // // vector<int> pair_9(2); // // pair_9[0] = -22; // // pair_9[1] = -32; // clause_list.push_back(pair_1); // clause_list.push_back(pair_2); // clause_list.push_back(pair_3); // clause_list.push_back(pair_4); // clause_list.push_back(pair_5); // //clause_list.push_back(pair_6); // clause_list.push_back(pair_7); // // clause_list.push_back(pair_8); // // clause_list.push_back(pair_9); // pair<graph, graph> graphs = formula_to_graph(clause_list); // print_graph(graphs.first); // cout << endl << "reverse graph: " << endl << endl; // print_graph(graphs.second); // vector<list<int> > connected_components = // find_strongly_connected_components(graphs.first, graphs.second).first; // unordered_map<int, int> leaders = // find_strongly_connected_components(graphs.first, graphs.second).second; // vector<list<int> >::iterator itr_cc = connected_components.begin(); // for(; itr_cc != connected_components.end(); ++itr_cc){ // cout << "connected component: " << endl; // list<int>::iterator list_itr = itr_cc->begin(); // for(; list_itr != itr_cc->end(); ++ list_itr){ // cout << *list_itr << " "; // } // cout << endl; // } // cout << endl << "satisfiability: " << check_satisfiability(leaders) << endl; // print_soln(solution(connected_components)); // } void print_graph(const graph & the_graph){ for(pair<int, list<int> > vertex: the_graph){ cout << "vertex: " << vertex.first; cout << " edges to: "; for(int edge: vertex.second) cout << edge << " "; cout << endl; } } void print_soln(const unordered_map<int,bool> &soln){ cout << "assignment thus far: " << endl; for(pair<int,bool> val: soln) if(val.first > 0) cout << val.first << ": " << val.second << endl; }
true
34b745739e4137bd0db742811589edecce5b1463
C++
bshah016/CS_Projects
/Put_Vector_in_Order.cpp
UTF-8
1,324
3.953125
4
[]
no_license
#include <iostream> #include <vector> using namespace std; void SortVector(vector<int>& myVec) { for (unsigned int i = 0; i < myVec.size(); ++i) { for (unsigned int j = i + 1; j < myVec.size(); ++j) { if (myVec.at(i) != 0) { if (myVec.at(i) > myVec.at(j)) { swap(myVec.at(i), myVec.at(j)); } } } if (i != myVec.size() - 1) cout << myVec.at(i) << ", "; else { cout << myVec.at(i); } } } int main() { int input; int size; cout << "Enter the size of the vector!" << endl << "Size: "; cin >> size; vector<int> myVec(size); for (int i = 0; i < size; ++i) { cout << "Enter the value at index " << i << "!" << endl << "Value: "; cin >> input; myVec.at(i) = input; } cout << "Here is what the vector looks like before it gets sorted. Take a look!" << endl << "<"; for (int j = 0; j < size; ++j) { if (j != myVec.size() - 1) cout << myVec.at(j) << ", "; else { cout << myVec.at(j); } } cout << ">" << endl << endl; //myVec.push_back(10000); cout << "This is the sorted vector!" << endl << "<"; SortVector(myVec); cout << ">" << endl; return 0; }
true
c39dfd602359fc4ff332c6a5b64faec4351829e8
C++
Ionsto/CBR-CS-A
/Wolf hunt/Wolf hunt/EntityPlayer.cpp
UTF-8
1,666
2.84375
3
[]
no_license
#include "EntityPlayer.h" #include "World.h" #include <math.h> #include <iostream> EntityPlayer::EntityPlayer(World * world,Vector pos) : EntityLiving(world,pos) { MousePosition = Vector(0, 0); this->MaxForce = 25; this->WalkForce = 10; this->CurrentMaxForce = MaxForce * (Health / 100); this->CurrentWalkForce = WalkForce * (Health / 100); SetSpeed(MaxForce); //RotOld -= 1; Type = EntityType::TypePlayer; } EntityPlayer::~EntityPlayer() { } void EntityPlayer::UpdatePlayerAngle() { float RotSpeed = 0.1; Vector LookVector = MousePosition; float Angle = 180/3.14 * atan2f(LookVector.Y, LookVector.X); if (Rot < 170 && Angle > 170) { int i = 0; } RotOld += 0.01 * AngleDifference(Rot,Angle); //RotOld -= 0.1; } void EntityPlayer::Update() { EntityLiving::Update(); UpdatePlayerAngle(); Vector diff = Pos - PosOld; this->CurrentMaxForce = MaxForce * (Health / 100); this->CurrentWalkForce = CurrentWalkForce * (Health / 100); this->CurrentMaxForce = MaxForce * (Health / 100); } void EntityPlayer::MoveForward() { this->ApplyForce(Vector(cos((Rot / 180)*3.14) * MoveForce, sin((Rot / 180)*3.14) * MoveForce)); } void EntityPlayer::MoveBackward() { this->ApplyForce(Vector(-cos((Rot / 180)*3.14) * MoveForce, -sin((Rot / 180)*3.14) * MoveForce)); } void EntityPlayer::MoveLeft() { this->ApplyForce(Vector(cos(((Rot + 90) / 180)*3.14) * MoveForce, sin(((Rot + 90) / 180)*3.14) * MoveForce)); } void EntityPlayer::MoveRight() { this->ApplyForce(Vector(cos(((Rot - 90) / 180)*3.14) * MoveForce, sin(((Rot - 90) / 180)*3.14) * MoveForce)); } void EntityPlayer::SetSpeed(float speed) { if (MoveForce != speed) { MoveForce = speed; } }
true
0215b88217b6467f3cd8c00ba46b488048f4a595
C++
yururyuru00/programing
/programing/Compirer_training/R4/r4_4.cpp
UTF-8
1,764
3.703125
4
[]
no_license
#include <iostream> #include <assert.h> class stack { protected: int sp; int max; int* data; public: stack() {stack(10);} stack(int sz) {sp=0; max=sz; data=new int[max];} ~stack() {delete [] data;} void push(int d) {assert(sp<=max); data[sp++]=d;} void pop() {assert(0<sp); --sp;} bool empty() const {return sp==0;} int top() const {return data[sp-1];} int size() const {return sp;} void dump(std::ostream&) const; }; void stack::dump(std::ostream& os) const { os << "max=" << max << ", "; os << "sp=" << sp << ", "; os << "data=("; for (int i=0; i<sp; i++) os << data[i] << " "; os << ")" << std::endl; } class stack_ac :public stack { private: int push_counter; int pop_counter; public: stack_ac() { push_counter=0; pop_counter=0; } stack_ac(int sz): stack(sz) { push_counter=0; pop_counter=0; } void push(int d) { stack::push(d); push_counter++; } void pop() { stack::pop(); pop_counter++; } int n_push() {return push_counter;} int n_pop() {return pop_counter;} }; int main(void) { stack_ac s1 = stack_ac(10); stack_ac s2 = stack_ac(10); s1.push(4); s1.push(3); s1.push(65); s1.push(2); s1.pop(); s1.pop(); s2.push(2); s2.push(1); s2.pop(); s2.push(11); s2.pop(); s2.pop(); s1.dump(std::cout); std::cout << "push_coounter :" << s1.n_push() << std::endl; std::cout << "pop_coounter :" << s1.n_pop() << std::endl; std::cout << std::endl; s2.dump(std::cout); std::cout << "push_coounter :" << s2.n_push() << std::endl; std::cout << "pop_coounter :" << s2.n_pop() << std::endl; }
true
2c9b1d46a10c43a4dbddecaee83eedf3df5cd874
C++
WhiZTiM/coliru
/Archive2/39/1783603a7223b1/main.cpp
UTF-8
5,694
3.28125
3
[]
no_license
#include <iostream> #include <string> #include <typeinfo> #include <memory> struct person { // struct visitor { virtual ~visitor() = default ; } ; virtual ~person() = default ; virtual std::string name() const = 0 ; virtual int age() const = 0 ; virtual std::shared_ptr<person> best_friend() const = 0 ; virtual void befriend( std::shared_ptr<person> p ) = 0 ; virtual std::string faith() const = 0 ; virtual double get_pocket_change() const = 0; virtual void add_pocket_change (double change) = 0; virtual std::ostream& print( std::ostream& stm = std::cout ) const { stm << name() << ' ' << age() << " years (" << faith() << ')' ; const auto f = best_friend() ; if(f) stm << " best friend: '" << f->name() << "' (" << f->faith() << ')' ; stm << std::endl << "pocket change = $" << get_pocket_change() << std::endl; return stm << '\n' ; } // virtual bool accept( person::visitor& ) {} ; // bool accept( person::visitor&& v ) { return accept(v) ; } // forward to virtual }; struct person_impl : person { virtual std::string name() const override { return name_ ; } virtual int age() const override { return age_ ; } virtual std::shared_ptr<person> best_friend() const override { return best_friend_ ; } virtual void befriend( std::shared_ptr<person> p ) override { best_friend_ = p ; } virtual double get_pocket_change() const override {return pocket_change;} virtual void add_pocket_change (double change) override { pocket_change += change;} person_impl( std::string name, int age, std::shared_ptr<person> best_friend = {} ) : name_(name), age_(age), best_friend_(best_friend) {} private: const std::string name_ ; int age_ ; double pocket_change = 0; std::shared_ptr<person> best_friend_ ; template < typename T > std::shared_ptr<person_impl> convert ( std::string new_name ) { auto p = std::make_shared<T>( new_name.empty() ? name_ : new_name, age_, best_friend_ ) ; p->add_pocket_change(pocket_change) ; return p ; } friend struct person_proxy ; }; struct person_proxy : person { private: std::shared_ptr<person_impl> actual ; public: virtual std::string name() const override { return actual->name() ; } virtual int age() const override { return actual->age() ; } virtual std::shared_ptr<person> best_friend() const override { return actual->best_friend() ; } virtual void befriend( std::shared_ptr<person> p ) override { actual->befriend(p) ; } virtual std::string faith() const override { return actual->faith() ; } virtual double get_pocket_change() const override {return actual->get_pocket_change();} virtual void add_pocket_change (double change) override {actual->add_pocket_change (change);} explicit person_proxy( std::shared_ptr<person_impl> p ) : actual(p) {} void rebind( std::shared_ptr<person_impl> p ) { actual = p ; } template < typename T > static std::shared_ptr<T> cast( std::shared_ptr<person> p ) { auto proxy = std::dynamic_pointer_cast<person_proxy>(p) ; return std::dynamic_pointer_cast<T>( proxy ? proxy->actual : p ) ; } template< typename T, typename... ARGS > static std::shared_ptr<person_proxy> make( ARGS&&... args ) { return std::make_shared<person_proxy>( std::make_shared<T>( std::forward<ARGS>(args)... ) ) ; } template < typename T > void convert( std::string new_name = "" ) { rebind( actual->convert<T>(new_name) ) ; } }; #define DEFINE_PERSON(denomination) \ struct denomination : person_impl \ { \ using person_impl::person_impl ; \ virtual std::string faith() const override { return #denomination ; } \ }; DEFINE_PERSON(wasp) DEFINE_PERSON(muslim) DEFINE_PERSON(agnostic) DEFINE_PERSON(hindu) struct buddhist : person_impl { private: std::string mala_colour = "red", buddhist_rank = "monk"; public: using person_impl::person_impl ; virtual std::string faith() const override { return "buddhist" ; } std::string get_mala_colour() const {return mala_colour;} void set_mala_colour (const std::string& colour) {mala_colour = colour;} std::string get_buddhist_rank() const {return buddhist_rank;} void set_buddhist_rank (const std::string& rank) {buddhist_rank = rank;} template <typename T> void reincarnates() {std::cout << name() << " has reincarnated to a " << typeid(T).name() << ".\n" ;} }; struct dog {}; int main() { std::shared_ptr<person_proxy> priya = person_proxy::make<buddhist>( "Priya", 28 ) ; std::shared_ptr<person_proxy> sandy = person_proxy::make<wasp>( "Sandy", 23, priya ) ; priya->befriend(sandy) ; sandy->print() ; auto sandy_best_friend = person_proxy::cast<buddhist>( sandy->best_friend() ) ; if(sandy_best_friend) { std::cout << sandy_best_friend->name() << ", a " << sandy_best_friend->faith() << ", is wearing a " << sandy_best_friend->get_mala_colour() << " mala on her wrist.\n" ; sandy_best_friend->set_mala_colour ("gold"); std::cout << sandy_best_friend->name() << "'s mala is now " << sandy_best_friend->get_mala_colour() << ".\n"; const std::string old_rank = sandy_best_friend->get_buddhist_rank(); sandy_best_friend->set_buddhist_rank ("Dalai Lama"); std::cout << sandy_best_friend->name() << "'s rank has changed from " << old_rank << " to " << sandy_best_friend->get_buddhist_rank() << "." << std::endl; sandy_best_friend->reincarnates<dog>(); } }
true
5553d60433a0b83fcf5eceb90cbcecf90f96be3e
C++
alexander-budanov/image_segmentation
/adjacency_operator.cpp
UTF-8
3,463
2.84375
3
[]
no_license
#include <vector> #include "adjacency_operator.h" #include "opencv2/opencv.hpp" #include "opencv2/imgproc/imgproc.hpp" class AdjacencyOperator::GradientThresholdImpl { int threshold; std::vector<cv::Mat> channels; cv::Mat gradX, gradY, gradNorm; public: GradientThresholdImpl( int threshold ) : threshold( threshold ) { } void SetThreshold( int newThreshold ) { threshold = newThreshold; } void Compute( const cv::Mat & image, cv::Mat & verticalAdjacency, cv::Mat & horizontalAdjacency ) { cv::split( image, channels ); //gradX.create( cv::Size(image.cols, image.rows) , CV_32SC1 ); //gradY.create( cv::Size(image.cols, image.rows) , CV_32SC1 ); gradNorm.create( image.rows, image.cols, CV_32F ); gradNorm = 0; for ( auto & channel : channels ) { cv::Scharr( channel, gradX, CV_32F, 1, 0, 1.0 / 32.0 ); cv::Scharr( channel, gradY, CV_32F, 0, 1, 1.0 / 32.0 ); cv::multiply( gradX, gradX, gradX ); cv::multiply( gradY, gradY, gradY ); gradX += gradY; gradX.forEach<float>( [](float & value, const int * /*position */ ){ value = std::sqrt(value); } ); gradNorm += gradX; } verticalAdjacency.create( image.rows, image.cols, CV_8U ); horizontalAdjacency.create( image.rows, image.cols, CV_8U); verticalAdjacency = 0; horizontalAdjacency = 0; for (int row = 1; row < image.rows; ++row ) { uint8_t * vertAdjVal = verticalAdjacency.ptr( row ); uint8_t * horizAdjVal = horizontalAdjacency.ptr( row ); const float * gradVal = gradNorm.ptr<float>( row ); if ( gradVal[0 - gradNorm.step1()] < threshold ) vertAdjVal[0] = 1; for ( int col = 1; col < image.cols; ++col ) { if ( gradVal[col - 1] < threshold ) horizAdjVal[col] = 1; if ( gradVal[col - gradNorm.step1()] < threshold ) vertAdjVal[col] = 1; } } } }; class AdjacencyOperator::LocalOtsuSegmentationImpl { int neighborhoodSize; public: LocalOtsuSegmentationImpl( int neighborhoodSize ) : neighborhoodSize( neighborhoodSize ) {} void Compute( const cv::Mat & image, cv::Mat & verticalAdjacency, cv::Mat & horizontalAdjacency ) const { } }; void AdjacencyOperator::operator()( const cv::Mat & image, cv::Mat & verticalAdjacency, cv::Mat & horizontalAdjacency ) { if ( algorithm == GradientThreshold ) { if ( gradientThresholdImpl == nullptr ) gradientThresholdImpl = std::make_shared<GradientThresholdImpl>( gradientThreshold ); gradientThresholdImpl->Compute( image, verticalAdjacency, horizontalAdjacency ); } else if ( algorithm == LocalOtsuSegmentation ) { if ( localOtsuSegmentationImpl == nullptr ) localOtsuSegmentationImpl = std::make_shared<LocalOtsuSegmentationImpl>( neighborhoodSize ); localOtsuSegmentationImpl->Compute( image, verticalAdjacency, horizontalAdjacency ); } else { throw std::logic_error( "Not supported algorithm" ); } } void AdjacencyOperator::SetAlgorithm( Algorithm newAlgorithm ) { if ( algorithm != GradientThreshold && algorithm != LocalOtsuSegmentation) throw std::logic_error( "Not supported algorithm" ); algorithm = newAlgorithm; }
true
4339526acc153f01b039d1584fde45869d7684d7
C++
wonny-Jo/algorithm
/알고리즘 문제 풀이/BOJ/단계별 기초 연습/큐, 덱/1021_회전하는 큐/1021.cpp
UTF-8
821
3.25
3
[]
no_license
#include<iostream> #include<deque> using namespace std; deque<int> dq; void MoveRight(int pos) { for (int i = 0; i < pos; ++i) { dq.push_back(dq.front()); dq.pop_front(); } } void MoveLeft(int pos) { for (int i = 0; i < pos; ++i) { dq.push_front(dq.back()); dq.pop_back(); } } int main() { int N, M; cin >> N >> M; int moveNum = 0; for (int i = 1; i <= N; ++i) dq.push_back(i); int arr[51]; for (int i = 0; i < M; ++i) { cin >> arr[i]; int size = dq.size(); int pos; for (pos = 0; pos < size; pos++) { if (dq[pos] == arr[i]) break; } if (pos < size - pos) { MoveRight(pos); moveNum += pos; } else { MoveLeft(size - pos); moveNum += size - pos; } dq.pop_front(); } cout << moveNum; return 0; }
true
b894c8bf70b31eed793523c77026ca8be9444467
C++
KjeldSchmidt/buzzer_games
/arduino/src/main.cpp
UTF-8
2,603
2.953125
3
[]
no_license
#include <Arduino.h> #include <HardwareSerial.h> const int buzzer1_in = 12; const int buzzer1_out = 2; const int buzzer2_in = 11; const int buzzer2_out = 3; bool pressed = false; uint8_t current_player; enum class State { IDLE, WEBCAM_GAME, LIGHT_UP, FREEPLAY_WAIT_BUZZER, }; State state = State::IDLE; void setup() { pinMode( buzzer1_in, INPUT_PULLUP ); pinMode( buzzer2_in, INPUT_PULLUP ); pinMode( buzzer1_out, OUTPUT ); pinMode( buzzer2_out, OUTPUT ); Serial.begin( 9600 ); } void init_webcam_game() { state = State::WEBCAM_GAME; digitalWrite( buzzer1_out, 0 ); digitalWrite( buzzer2_out, 0 ); pressed = false; } uint8_t get_led_from_player( uint8_t player ) { return player == 1 ? buzzer1_out : buzzer2_out; } void init_idle() { state = State::IDLE; digitalWrite( buzzer1_out, 0 ); digitalWrite( buzzer2_out, 0 ); } void init_light_up() { if ( state != State::WEBCAM_GAME ) return; state = State::LIGHT_UP; int led_port = get_led_from_player( current_player ); digitalWrite( led_port, 1 ); Serial.write( current_player ); } void init_free_play() { state = State::FREEPLAY_WAIT_BUZZER; digitalWrite( buzzer1_out, 0 ); digitalWrite( buzzer2_out, 0 ); } void process_serial() { uint8_t cmd = Serial.read(); if ( cmd == 'v' ) { init_webcam_game(); return; } else if ( cmd == 'i' ) { init_idle(); } else if ( cmd == 'f' ) { init_free_play(); } } void check_for_buzzer() { if ( !pressed ) { if ( !digitalRead( buzzer1_in )) { current_player = 1; pressed = true; } if ( !digitalRead( buzzer2_in )) { current_player = 2; pressed = true; } if ( pressed ) { init_light_up(); } } } void check_for_freeplay_buzzer() { char second_player; if ( !digitalRead( buzzer1_in )) { current_player = 1; second_player = 2; } else if ( !digitalRead( buzzer2_in )) { current_player = 2; second_player = 1; } else { return; } Serial.write( 's' ); digitalWrite( get_led_from_player( current_player ), HIGH ); delay( 5000 ); digitalWrite( get_led_from_player( current_player ), LOW ); digitalWrite( get_led_from_player( second_player ), HIGH ); delay( 5000 ); digitalWrite( get_led_from_player( second_player ), LOW ); Serial.write( 'c' ); } void loop() { if ( Serial.available() > 0 ) { process_serial(); } if ( state == State::WEBCAM_GAME ) { check_for_buzzer(); } else if ( state == State::FREEPLAY_WAIT_BUZZER ) { check_for_freeplay_buzzer(); } else if ( state == State::IDLE ) { digitalWrite( buzzer1_out, !digitalRead( buzzer1_in )); digitalWrite( buzzer2_out, !digitalRead( buzzer2_in )); } }
true
05dff772473b3b1d379b23b0c290b0ee348bf7d8
C++
mohitkumarraj/cpp-programs
/Dynamic Programming/MCQS.cpp
UTF-8
208
2.734375
3
[]
no_license
#include<iostream> using namespace std; int main(){ int m=10; //it cannot be constant value int &n=m; //reference to other variable .. refer to single address //n=6; cout<<m<<n; return 0; }
true
7015e1e63a0993d5a8acb4afd26e46601457b114
C++
alindsharmasimply/CompetitivePractice2
/Fifth.cpp
UTF-8
521
2.734375
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n, d, y; cin >> n; int s1 = 0, s2 = 0; int x = n / 1000; while (x != 0) { d = x % 10; s1 += d; x = x/10; } while (s1 != s2) { n++; y = n; s2 = 0; for (int i = 0; i < 3; i++) { d = y % 10; s2 += d; y = y/10; } } std::cout << n << '\n'; return 0; }
true
9d8e63150f89fff87e4de26bb91f9d3f8bd76f5b
C++
rafasu4/Ex4--pandemic--CPP
/sources/Player.cpp
UTF-8
7,135
3.09375
3
[]
no_license
#include "Player.hpp" #include <iostream> using namespace std; namespace pandemic { bool Player::removeCards(size_t indexStart, size_t indexEnd, int n) { int counter = 0; //going over the given indexes for (size_t i = indexStart; i < indexEnd; i++) { if (cityCards.at(i)) { counter++; } if (counter == n) { break; } } //if there isn't enugh cards if (counter < n) { return false; } //removing cards for (size_t i = indexStart; i < indexEnd; i++) { if (cityCards.at(i)) { cityCards.at(i) = false; counter--; } if (counter == 0) { break; } } return true; } Player &Player::drive(City city) { //if directly connected - drive with no cost if (board.isConnected(currentCity, city)) { currentCity = city; return *this; } string message = board.getCityName(currentCity) + " and " + board.getCityName(city) + " aren't neighbors!"; throw std::invalid_argument(message); } void Player::fly(City city, City card) { //if cityination is same as source if (currentCity == city) { string message = "Can't fly from the city to itself!"; throw std::invalid_argument(message); } //if has the right card - use it and discard if (cityCards.at(board.getCitySize(card))) { currentCity = city; cityCards.at(board.getCitySize(card)) = false;//discard } else { string message = role() + " doesn't have a " + board.getCityName(card) + " card!"; throw std::invalid_argument(message); } } Player &Player::fly_direct(City city) { fly(city, city); return *this; } Player &Player::fly_charter(City city) { fly(city, currentCity); return *this; } Player &Player::fly_shuttle(City city) { if (currentCity == city) { string message = "Can't fly from the city to itself"; throw std::invalid_argument(message); } //if one of the cities doesn't have a research lab if (!board.hasResearchLab(currentCity) || !board.hasResearchLab(city)) { string message = "Illegal action! There isn't a research lab in one of the cities!"; throw std::invalid_argument(message); } currentCity = city; return *this; } void Player::build() { //if has the current city card if (cityCards.at(board.getCitySize(currentCity))) { //if there isn't a reserach lab build, otherwise - do nothing if (!board.hasResearchLab(currentCity)) { board.build(currentCity); cityCards.at(board.getCitySize(currentCity)) = false;//discard } } else { string message = "Illegal action! doesn't have a " + board.getCityName(currentCity) + " card!"; throw std::invalid_argument(message); } } Player &Player::take_card(City city) { cityCards.at(board.getCitySize(city)) = true; return *this; } void Player::discover_cure(Color color) { //if have a reserch lab if (board.hasResearchLab(currentCity)) { bool flag = false; switch (color) { case Blue: //if a cure was found for this color - no need for action if (board.blueCure) { return; } board.blueCure = flag = removeCards(lower_blue, higher_blue, DISCOVER_CARD_COST); break; case Yellow: //if a cure was found for this color - no need for action if (board.yellowCure) { return; } board.yellowCure = flag = removeCards(lower_yellow, higher_yellow, DISCOVER_CARD_COST); break; case Black: //if a cure was found for this color - no need for action if (board.blackCure) { return; } board.blackCure = flag = removeCards(lower_black, higher_black, DISCOVER_CARD_COST); break; case Red: //if a cure was found for this color - no need for action if (board.redCure) { return; } board.redCure = flag = removeCards(lower_red, higher_red, DISCOVER_CARD_COST); break; } if (!flag) { string message = "Illegal action! Doesn't have 5 cards!"; throw std::invalid_argument(message); } } else { string message = "Current city " + board.getCityName(currentCity) + " doesn't have a research station!"; throw std::invalid_argument(message); } } Player &Player::treat(City city) { //if not in the given city if (city != currentCity) { string message = "Must be in the city for this action!"; throw std::invalid_argument(message); } Color color = board.getColor(city); //if there is no disease if (board.getDiseaseLevel(city) == 0) { string message = "Current city is already heald!"; throw std::invalid_argument(message); } switch (color) { case Blue: //if cure was found - lower disease level to zero if (!board.blueCure) { board.lowerDiseaseLevel(city); } else { board.nullifyDiseaseLevel(city); } break; case Yellow: //if cure was found - lower disease level to zero if (!board.yellowCure) { board.lowerDiseaseLevel(city); } else { board.nullifyDiseaseLevel(city); } break; case Black: //if cure was found - lower disease level to zero if (!board.blackCure) { board.lowerDiseaseLevel(city); } else { board.nullifyDiseaseLevel(city); } break; case Red: //if cure was found - lower disease level to zero if (!board.redCure) { board.lowerDiseaseLevel(city); } else { board.nullifyDiseaseLevel(city); } break; } return *this; } void Player::remove_cards() { for (size_t i = lower_blue; i < higher_red + 1; i++) { cityCards.at(i) = false; } } }
true
f50e3e7b85668c428a05fe139edce8092cded4a5
C++
Mr-Phoebe/ACM-ICPC
/OJ/Leetcode/Algorithm/137. Single Number II.cpp
UTF-8
340
2.796875
3
[]
no_license
class Solution { public: int singleNumber(vector<int>& nums) { int ans = 0; for(int i = 0; i < 32; i++) { int cnt = 0; for(auto num : nums) if((num>>i)&1) cnt++; if(cnt%3) ans |= 1<<i; } return ans; } };
true
b031d4f35aeb8d8a556ac1b0b691c0ad9f739312
C++
yuukidach/OnlineJudge
/LeetCode/dfs/Q131_PalindromePartitioning.cpp
UTF-8
974
3.203125
3
[]
no_license
class Solution { public: bool checkPalindrome(string &s, int l, int r) { for (int i = l; i < (l+r) / 2; ++i) { if (s[i] != s[r+l-i-1]) return false; } return true; } vector<vector<string>> getList(string &s, int l, int r) { vector<vector<string>> mat; if (r == l) return mat; for (int i = l+1; i <= r; ++i) { if (checkPalindrome(s, l, i)) { vector<vector<string>> vv = getList(s, i, r); if (vv.empty() && i == r) { vector<string> v = {s.substr(l, i-l)}; mat.push_back(v); } for (auto & v : vv) { v.insert(v.begin(), s.substr(l, i-l)); mat.push_back(v); } } } return mat; } vector<vector<string>> partition(string s) { int len = s.size(); return getList(s, 0, len); } };
true
ac16773c5df6e1ba6d5684f865d8623d5835089a
C++
ravibitsgoa/Implementations_of_various_algorithms_and_data_structures
/dp/card_game.cpp
UTF-8
1,079
3.59375
4
[]
no_license
//https://www.geeksforgeeks.org/dynamic-programming-set-31-optimal-strategy-for-a-game/ //story: you and another person are playing a game to take a card from either end //of a card pile. Usual game rules apply. Try to maximize your sum of cards. #include <iostream> using namespace std; int maxSum(int array[], int n, int l, int r, vector<vector<int> > &dp) { if(l>=r) return 0; if(l == r-1) dp[l][r]= array[l]; else if(dp[l][r] != -1) //cached value. return dp[l][r]; else { dp[l][r] = max( array[l] + min(maxSum(array, n, l+2, r, dp), maxSum(array, n, l+1, r-1, dp)), array[r-1] + min(maxSum(array, n, l, r-2, dp), maxSum(array, n, l+1, r-1, dp))); } //if the opponent plays optimally. //if the opponent is dumb, replace both min with max, to get the max score that this player can get. return dp[l][r]; } int main() { int array[] = {1, 2, 3, 4, 5, 6, 7}; int n=7; vector<vector<int> >dp(n+1, vector<int>(n+1, -1)); cout << maxSum(array, n, 0, n, dp); }
true
0f7950bbb107a5b66376421466ff90c36f9aa69b
C++
ravi-ojha/competitive-sport
/codeforces/822a.cpp
UTF-8
805
2.9375
3
[]
no_license
#include <bits/stdc++.h> // Some constants that are frequently used #define EPS 1e-9 #define PI 3.1415926535897932384626433832795 #define MOD 1000000007 // Something to print to console and debug #define DEBUG false #define CONSOLE(x) if(DEBUG) {cout << '>' << #x << ':' << x << endl;} using namespace std; long long gcd(long long a, long long b) { long long temp; while(b > 0) { temp = b; b = a % b; a = temp; } return a; } long long factorial(long long a) { long long res = 1; for(long long i=1; i<=a; i++) { res = res*i; } CONSOLE(res); return res; } int main() { long long a, b; cin >> a >> b; long long c, d; c = min(a, b); long long c_fact = factorial(c); cout << c_fact << endl; return 0; }
true
7751e898a78d89bbf3ed5abd3eb41dcc2df696be
C++
AbhishekPanta8/Albanero_hack_week
/1stday/two.cpp
UTF-8
496
3.140625
3
[ "MIT" ]
permissive
#include<bits/stdc++.h> using namespace std; int max(int a,int b){ if(a>b){ return a; } else return b; } int maxdepth(string st){ string:: iterator it; int curr=0; int mdepth=0; for(it = st.begin();it!=st.end();it++){ if(*it == '('){ curr++; mdepth = max(mdepth,curr); } else if(*it ==')'){ curr--; } } return mdepth; } int main(){ string str; cin>>str; int max=maxdepth(str); cout<<max<<endl; }
true
3aa2b7ec101e64330dcdf993ff7d1d01c446536e
C++
mohitsingla123/Computer-Graphics
/2d_transform.cpp
UTF-8
4,023
2.890625
3
[]
no_license
#include<GL/glut.h> #include<iostream> using namespace std; void init(void) { glClearColor(1,1,1,1); glMatrixMode(GL_PROJECTION); glClear(GL_COLOR_BUFFER_BIT); gluOrtho2D(-200,200,-200,200); glFlush(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); cout<<"Press t to translate"<<"\n"<<"Press r to rotate"<<"\n"<<"Press s to scale"<<"\n"<<"Press x for reflection in x-axis"<<"\n"<<"Press y for reflection in y-axis"<<"\n"; glColor3f(0,0,1); glBegin(GL_LINES); glVertex2i(-200,0); glVertex2i(200,0); glVertex2i(0,-200); glVertex2i(0,200); glEnd(); glFlush(); } int i=0; float xx,yy; float xval, yval; int xarr[7]; int yarr[7]; int xsend, ysend; void translate(int x1, int y1,int x2, int y2,int x3, int y3){ x1=x1+50; x2=x2+50; x3=x3+50; glColor3f(0,1,0); glBegin(GL_LINES); glVertex2i(x1,y1); glVertex2i(x2,y2); glVertex2i(x2,y2); glVertex2i(x3,y3); glVertex2i(x3,y3); glVertex2i(x1,y1); glEnd(); glFlush(); } void rotate(int x1, int y1,int x2, int y2,int x3, int y3){ int xx1=x1*(0.5)-y1*(0.86602540378); int yy1=x1*(0.86602540378)+y1*(0.5); int xx2=x2*(0.5)-y2*(0.86602540378); int yy2=x2*(0.86602540378)+y2*(0.5); int xx3=x3*(0.5)-y3*(0.86602540378); int yy3=x3*(0.86602540378)+y3*(0.5); glColor3f(0,0,1); glBegin(GL_LINES); glVertex2i(xx1,yy1); glVertex2i(xx2,yy2); glVertex2i(xx2,yy2); glVertex2i(xx3,yy3); glVertex2i(xx3,yy3); glVertex2i(xx1,yy1); glEnd(); glFlush(); } void scale(int x1, int y1,int x2, int y2,int x3, int y3){ glColor3f(0,1,1); glBegin(GL_LINES); glVertex2i(2*x1,2*y1); glVertex2i(2*x2,2*y2); glVertex2i(2*x2,2*y2); glVertex2i(2*x3,2*y3); glVertex2i(2*x3,2*y3); glVertex2i(2*x1,2*y1); glEnd(); glFlush(); } void xrefl(int x1, int y1,int x2, int y2,int x3, int y3){ glColor3f(0.7,1,0.3); glBegin(GL_LINES); glVertex2i(x1,-y1); glVertex2i(x2,-y2); glVertex2i(x2,-y2); glVertex2i(x3,-y3); glVertex2i(x3,-y3); glVertex2i(x1,-y1); glEnd(); glFlush(); } void yrefl(int x1, int y1,int x2, int y2,int x3, int y3){ glColor3f(0.5,0.2,0.8); glBegin(GL_LINES); glVertex2i(-x1,y1); glVertex2i(-x2,y2); glVertex2i(-x2,y2); glVertex2i(-x3,y3); glVertex2i(-x3,y3); glVertex2i(-x1,y1); glEnd(); glFlush(); } void tri(int x1, int y1,int x2, int y2,int x3, int y3){ glColor3f(1,0,0); glBegin(GL_LINES); glVertex2i(x1,y1); glVertex2i(x2,y2); glVertex2i(x2,y2); glVertex2i(x3,y3); glVertex2i(x3,y3); glVertex2i(x1,y1); glEnd(); glFlush(); // translate(x1,y1,x2,y2,x3,y3); } void mousePtPlot(GLint button, GLint action, GLint xMouse, GLint yMouse){ if(button == GLUT_LEFT_BUTTON && action==GLUT_DOWN) { xx=xMouse; yy=400-yMouse; xval = xx-200; yval = yy-200; // xval = xx; // yval = yy; glPointSize(5); glBegin(GL_POINTS); glColor3f(1,0,0); glVertex2i(xval,yval); glEnd(); i++; xarr[i]=xval; yarr[i]=yval; // cout<<"count="<<i<<"\n"; if(i%3==0){ tri(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } } glFlush(); } void keyy(unsigned char key, GLint xMouse, GLint yMouse){ if(key=='t' || key=='T'){ translate(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } if(key=='r' || key=='R'){ rotate(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } if(key=='s' || key=='S'){ scale(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } if(key=='x' || key=='X'){ xrefl(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } if(key=='y' || key=='Y'){ yrefl(xarr[i-2],yarr[i-2], xarr[i-1],yarr[i-1],xarr[i],yarr[i]); } } int main(int argc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowPosition(0,0); glutInitWindowSize(400,400); glutCreateWindow("2-D transformation"); init(); glutDisplayFunc(display); glutMouseFunc(mousePtPlot); glutKeyboardFunc(keyy); glutMainLoop(); return 0; }
true
bf9372d4288b3d0ef167dda38c7ff4ccc8111ee1
C++
wcsjdzz/duduo
/duduo/net/Reactor/EventLoopThread.h
UTF-8
872
2.984375
3
[]
no_license
#ifndef EVENTLOOPTHREAD_H #define EVENTLOOPTHREAD_H #include <thread> #include <mutex> #include <condition_variable> #include <functional> class EventLoop; class EventLoopThread { using ThreadInitCallback = std::function<void(EventLoop *)>; private: const std::string name_; ThreadInitCallback initCallback_; // called when // on-stack-EventLoop is established EventLoop *loop_; std::mutex mutex_; std::condition_variable condition_; void threadFunc(); // main function of current thread public: EventLoopThread(const ThreadInitCallback &cb = ThreadInitCallback(), const std::string &name= std::string()); ~EventLoopThread(); // create new thread in `statrLoop` // executing the main function `threadFunc` // and return corresponding EventLoop EventLoop *startLoop(); }; #endif /* EVENTLOOPTHREAD_H */
true
2b83c30f57bf3cf1942bdf998c03f889d605c04f
C++
CalebWalls/FinalExamCalculator
/FinalCalculator/FinalCalculator/Source.cpp
UTF-8
5,334
3.90625
4
[]
no_license
#include<iostream> #include<string> using namespace std; /*This function will determine the average of a arbitrary number of grades*/ void averageGrade(int numtest) { float testval; //set max rediculously high float arr[1000]; float result = 0.0; //loop to have th euser enter the test values for (int i = 0; i < numtest; i++) { cout << "\nEnter Grade for test " << i+1 << ":"; cin >> testval; arr[i] = testval; //adds the results together result += arr[i]; } //divides the results by the number of test result = result / numtest; //displays the average cout << "\nYour average for this category is: " << result << endl; cout << "\n"; } /*This function will get the current, goal , and final weight for the final and determien what the user needs in order to get the desired goal*/ void finalexamcalc(void) { float goal, current, finalweight, result; cout << "\nEnter your current grade in the class:"; cin >> current; cout << "\nEnter the grade you want in the class:"; cin >> goal; cout << "\nEnter the weight of the final:"; cin >> finalweight; result = (goal - current * (1 - finalweight)) / finalweight; cout << "\n\nYou need a " << result << " on the final to get a " << goal << endl; } void weightcalc(int numgrades) { float gradenum; float weightnum; //set max rediculously high float grade[1000]; float weight[1000]; float result = 0.0; //loop to have th euser enter the test values for (int i = 0; i < numgrades; i++) { cout << "\nEnter Grade for test " << i + 1 << ":"; cin >> gradenum; cout << "\nEnter Weight for category " << i + 1 << ":"; cin >> weightnum; grade[i] = gradenum; weight[i] = weightnum; //adds the results together result += (grade[i])*weight[i]; } //divides the results by the number of test //displays the average cout << "\nYour grade is: " << result << endl; cout << "\n"; } int main() { int redo; int choice; //notes to the user and credit to athor cout << "FINAL EXAM CALCULATOR" << endl; cout << "By: Caleb Walls\n\n" << endl; //system will ask user for info as long as they enter 1 when asked if they want to do another calculation do { //menu to ask the user what they want to do cout << "\nMENU" << endl; cout << "1. Average a category" << endl; cout << "2. Calculate what is needed on final to pass" << endl; cout << "3. Calculate grade with weights" << endl; cin >> choice; switch (choice) { case 1: int numtest; cout << "**NOTE: When entering test grades if you need to enter 5 test type 5." << endl; cout << "Then, when you are asked to enter the test grade, if you made a 88 enter 88." << endl; cout << "\nSample input: Enter Grade for test 2:88 " << endl; cout << "______________________________________________________________________________________" << endl; cout << "\nHow many test do you need to enter?" << endl; cin >> numtest; //function to calculate the average averageGrade(numtest); //display menu again cout << "Would you like to do another calcuation? If so type 1 other wise type any other number: "; cin >> redo; break; case 2: cout << "**NOTE: When you enter your grade, if your grade is, for example\n a 92.16 % enter the number .9216 this will also apply for the grade you\n want and the weight.Your result will also be calculated in this manner.\n So if it says you need a .281537 to pass then you really need a 28.15 % to pass\n\n" << endl; cout << "Sample Input and output: " << endl; cout << "Enter your current grade in the class:.9216\nEnter the grade you want in the class :.78\nEnter the weight of the final:.35\nYou need a 0.517029 on the final to get a 0.78" << endl; cout << "_______________________________________________________________________________________________________________________" << endl; //function to determine final exam finalexamcalc(); //display menu again cout << "\nWould you like to do another calculation ? If so type 1 otherwise type any other number: "; cin >> redo; break; case 3: cout << "**NOTE: When entering how many categories, say you have a category for homework,test,quizzes and projects,\n the number you would enter here is 4" << endl; \ cout << "When asked for the grade, if you made a 77 in the category, enter 77" << endl; cout << "When asked for the weight, if the weight is 25% of your total grade, enter .25" << endl; cout << "Sample input:How many categories do you need to enter?\n4\n Enter Grade for test 1:77\nEnter Weight for category 1:.25\nEnter Grade for test 2 : 88\nEnter Weight for category 2 : .25 " << endl; cout << "..." << endl; cout << "_________________________________________________________________________" << endl; int testnum; cout << "\nHow many categories do you need to enter?" << endl; cin >> testnum; //function to calculate the average with weights weightcalc(testnum); cout << "\nWould you like to do another calculation ? If so type 1 otherwise type any other number: "; cin >> redo; break; //default case for invalid choice default: cout << "ERROR INVALID CHOICE!" << endl; system("pause"); return 0; } } //while redo equals 1 then we keep going through loop while (redo == 1); return 0; }
true
207de77e1379eca9fbb038b18bcb591587375fdc
C++
Yann4/Final-Year-Project
/Octree.h
UTF-8
6,771
3.078125
3
[]
no_license
#pragma once #include <array> #include <vector> #include <DirectXMath.h> struct AABB { DirectX::XMFLOAT3 centre; DirectX::XMFLOAT3 hSize; AABB() :centre(DirectX::XMFLOAT3(0, 0, 0)), hSize(DirectX::XMFLOAT3(0, 0, 0)) {} AABB(DirectX::XMFLOAT3 centre, DirectX::XMFLOAT3 hSize) :centre(centre), hSize(hSize) {} private: bool testAxis(DirectX::XMFLOAT3 axis, float minA, float maxA, float minB, float maxB) { DirectX::XMVECTOR axisV = XMLoadFloat3(&axis); float axisLSq = DirectX::XMVectorGetX(DirectX::XMVector3Dot(axisV, axisV)); if (axisLSq < 1.0e-8f) { return true; } float d0 = maxB - minA; //Left side float d1 = maxA - minB; //Right side if (d0 <= 0.0f || d1 <= 0.0f) { return false; } return true; } public: bool intersects(AABB other) { DirectX::XMFLOAT3 axis = DirectX::XMFLOAT3(1, 0, 0); //Check x axis if (!testAxis(axis, centre.x - hSize.x, centre.x + hSize.x, other.centre.x - other.hSize.x, other.centre.x + other.hSize.x)) { return false; } axis = DirectX::XMFLOAT3(0, 1, 0); //Check y axis if (!testAxis(axis, centre.y - hSize.y, centre.y + hSize.y, other.centre.y - other.hSize.y, other.centre.y + other.hSize.y)) { return false; } axis = DirectX::XMFLOAT3(0, 0, 1); //Check z axis if (!testAxis(axis, centre.z - hSize.z, centre.z + hSize.z, other.centre.z - other.hSize.z, other.centre.z + other.hSize.z)) { return false; } return true; } }; template <typename T> class Octree { struct Element { AABB bounds; T data; Element(T data, AABB box) : data(data), bounds(box) {} }; private: std::array<Octree*, 8> children; AABB boundingBox; std::vector<Element> elements; unsigned int maxElements = 5; DirectX::XMFLOAT3 minSize = DirectX::XMFLOAT3(1, 1, 1); private: bool subdivide(); public: Octree(); Octree(DirectX::XMFLOAT3 centre, DirectX::XMFLOAT3 halfSize); ~Octree(); void insert(T toInsert, DirectX::XMFLOAT3 pos, DirectX::XMFLOAT3 size); inline AABB bounds() { return boundingBox; }; std::vector<T*> getElementsInBounds(DirectX::XMFLOAT3 centre, DirectX::XMFLOAT3 halfSize); std::vector<T*> getAllElements(); }; template <typename T> Octree<T>::Octree() { children = std::array<Octree*, 8>(); children.fill(nullptr); boundingBox = AABB(); elements = std::vector<Element>(); } template <typename T> Octree<T>::Octree(DirectX::XMFLOAT3 centre, DirectX::XMFLOAT3 halfSize) { boundingBox = AABB(centre, halfSize); children = std::array<Octree*, 8>(); children.fill(nullptr); elements = std::vector<Element>(); } template <typename T> Octree<T>::~Octree() { if (children[0] != nullptr) { for (auto child : children) { delete child; } } } template <typename T> bool Octree<T>::subdivide() { if (children[0] != nullptr) { return false; } DirectX::XMFLOAT3 centre = boundingBox.centre; DirectX::XMFLOAT3 qSize = DirectX::XMFLOAT3(boundingBox.hSize.x / 2, boundingBox.hSize.y / 2, boundingBox.hSize.z / 2); if (qSize.x < minSize.x || qSize.y < minSize.y || qSize.z < minSize.z) { return false; } DirectX::XMFLOAT3 newCentre = DirectX::XMFLOAT3(centre.x + qSize.x, centre.y + qSize.y, centre.z + qSize.z); children[0] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x - qSize.x, centre.y + qSize.y, centre.z + qSize.z); children[1] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x - qSize.x, centre.y - qSize.y, centre.z + qSize.z); children[2] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x + qSize.x, centre.y + qSize.y, centre.z + qSize.z); children[3] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x + qSize.x, centre.y + qSize.y, centre.z - qSize.z); children[4] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x - qSize.x, centre.y + qSize.y, centre.z - qSize.z); children[5] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x - qSize.x, centre.y - qSize.y, centre.z - qSize.z); children[6] = new Octree(newCentre, qSize); newCentre = DirectX::XMFLOAT3(centre.x + qSize.x, centre.y + qSize.y, centre.z - qSize.z); children[7] = new Octree(newCentre, qSize); for (auto object : elements) { for (auto child : children) { if (child->bounds().intersects(object.bounds)) { child->insert(object.data, object.bounds.centre, object.bounds.hSize); break; } } } elements.clear(); return true; } template <typename T> void Octree<T>::insert(T toInsert, DirectX::XMFLOAT3 pos, DirectX::XMFLOAT3 halfSize) { AABB objBox = AABB(pos, halfSize); bool inserted = false; //If has children, insert in child if (children[0] != nullptr) { for (auto child : children) { if (child->bounds().intersects(objBox)) { child->insert(toInsert, pos, halfSize); inserted = true; break; } } } else { if (elements.size() < maxElements) { elements.push_back(Element(toInsert, objBox)); inserted = true; } else { if (subdivide()) { for (auto child : children) { if (child->bounds().intersects(objBox)) { child->insert(toInsert, pos, halfSize); inserted = true; break; } } if (!inserted) { elements.push_back(Element(toInsert, objBox)); inserted = true; } } else { elements.push_back(Element(toInsert, objBox)); inserted = true; } } } if (!inserted) { elements.push_back(Element(toInsert, objBox)); } } template <typename T> std::vector<T*> Octree<T>::getElementsInBounds(DirectX::XMFLOAT3 centre, DirectX::XMFLOAT3 halfSize) { std::vector<T*> toRet = std::vector<T*>(); AABB examine = AABB(centre, halfSize); if (boundingBox.intersects(examine)) { for (unsigned int i = 0; i < elements.size(); i++) { toRet.push_back(&(elements.at(i).data)); } if (children[0] != nullptr) { for (auto child : children) { std::vector<T*> tmp = child->getElementsInBounds(centre, halfSize); toRet.insert(toRet.end(), tmp.begin(), tmp.end()); } } } return toRet; } template <typename T> std::vector<T*> Octree<T>::getAllElements() { std::vector<T*> toRet = std::vector<T*>(); for (unsigned int i = 0; i < elements.size(); i++) { toRet.push_back(&(elements.at(i).data)); } if (children[0] != nullptr) { for (auto child : children) { std::vector<T*> tmp = child->getAllElements(); toRet.insert(toRet.end(), tmp.begin(), tmp.end()); } } return toRet; }
true
f6f884c8aa90552feed5e0c4528022b6383f5c4c
C++
yular/CC--InterviewProblem
/LeetCode/leetcode_find-two-non-overlapping-sub-arrays-each-with-target-sum.cpp
UTF-8
1,056
3.171875
3
[]
no_license
/* * * Tag: Sliding Window + Hash * Time: O(n) * Space: O(n) */ class Solution { public: int minSumOfLengths(vector<int>& arr, int target) { if(arr.size() < 2) { return -1; } unordered_map<int,int> sumDic; sumDic[0] = -1; int ans = INT_MAX; int sum = 0, n = arr.size(), minVal = INT_MAX; vector<int> minLen(n, minVal); for(int i = 0; i < n; ++ i) { sum += arr[i]; sumDic[sum] = i; if(sum < target) { continue; } int v = sum - target; minLen[i] = minVal; if(sumDic.count(v) == 0) { continue; } int idx = sumDic[v], len = i - idx; if(idx >= 1 && minLen[idx] < INT_MAX) { ans = min(ans, minLen[idx] + len); } minVal = min(minVal, len); minLen[i] = minVal; } return ans == INT_MAX ? -1 : ans; } };
true
c5c15bb5c82f8b1b02793c6f06e85faa0ca81496
C++
Simon-Fuhaoyuan/LeetCode-100DAY-Challenge
/addBinary/main.cpp
UTF-8
1,644
3.453125
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Solution { public: string addBinary(string a, string b) { string ans; int pos_a = a.length() - 1; int pos_b = b.length() - 1; bool curr_a, curr_b; bool carry = false; while (pos_a >= 0 || pos_b >= 0) { curr_a = curr_b = false; if (pos_a >= 0) curr_a = a[pos_a] == '1' ? true : false; if (pos_b >= 0) curr_b = b[pos_b] == '1' ? true : false; if (curr_a && curr_b) { if (carry) ans.insert(ans.begin(), '1'); else ans.insert(ans.begin(), '0'); carry = true; } else if (curr_a || curr_b) { if (carry) { ans.insert(ans.begin(), '0'); carry = true; } else { ans.insert(ans.begin(), '1'); carry = false; } } else { if (carry) ans.insert(ans.begin(), '1'); else ans.insert(ans.begin(), '0'); carry = false; } pos_a--; pos_b--; } if (carry) ans.insert(ans.begin(), '1'); return ans; } }; int main() { Solution s; string a = "1010"; string b = "1011"; cout << s.addBinary(a, b) << endl; return 0; }
true
2c19c44841519c39deb211cb635d3fd59a8f1702
C++
rohit0000/Sorting
/Sorting/PROJECT/Untitled1.cpp
UTF-8
19,886
2.984375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> struct user{ char name[129]; char password[129]; int id; int money; }; struct admin{ char name[129]; char password[129]; int id; }; struct smartphone{ char name[129]; char brand[129]; int price; char description[200]; }; void user_editor(struct user *p_user); void smartphone_editor(struct smartphone *p_smartphone); int main() { struct user user_array[20]; struct admin admin_array[5]; struct user *p_user; struct smartphone *p_smartphone; struct smartphone smartphone_array[100]; FILE *ptr_file_userID; FILE *ptr_file_userpassword; FILE *ptr_file_username; FILE *ptr_file_usermoney; FILE *ptr_file_adminname; FILE *ptr_file_adminID; // This section declares a pointer to a file outside the program FILE *ptr_file_adminpassword; FILE *ptr_file_smartphonename; FILE *ptr_file_smartphonebrand; FILE *ptr_file_smartphoneprice; FILE *ptr_file_smartphonedescription; int i, temp_int, stopper=0, login_ID, user_or_admin=0, identity, edit_user, edit_smartphone; char temp_string[129], temp_description[200], login_password[129]; int log_in, pickloop=0, index=-1, approver=0, temp, transaction, admin_operation; ptr_file_userID = fopen("User ID Text File.txt", "r"); ptr_file_userpassword = fopen("User Password Text File.txt", "r"); ptr_file_username = fopen("User Name Text File.txt", "r"); ptr_file_usermoney = fopen("User Money Text File.txt", "r"); ptr_file_adminname = fopen("Admin Name Text File.txt", "r"); ptr_file_adminID = fopen("Admin ID Text File.txt", "r"); // this sets the pointer to the outside file. ptr_file_adminpassword = fopen("Admin Password Text File.txt", "r"); //the fopen function opens the outside file. "r" means read the file ptr_file_smartphonename = fopen("Smartphone Name Text File.txt", "r"); ptr_file_smartphonebrand = fopen("Smartphone Brand Text File.txt", "r"); ptr_file_smartphoneprice = fopen("Smartphone Price Text File.txt", "r"); ptr_file_smartphonedescription = fopen("Smartphone Description Text File.txt", "r"); for(i=0; i<20; i++){ fscanf(ptr_file_userID, "%d", &(temp_int)); user_array[i].id=temp_int; fscanf(ptr_file_usermoney, "%d", &(temp_int)); user_array[i].money=temp_int; fgets(temp_string, 129, ptr_file_username); // the id is set to 8 if it is null, so let's find a way to not let any user use 8 as his/her ID. strcpy(user_array[i].name, temp_string); fgets(temp_string, 129, ptr_file_userpassword); strcpy(user_array[i].password,temp_string); printf("id: %d\n", user_array[i].id); // ROHIT don't remove this line yet. This checks what the initial user ID's are. } system("PAUSE"); system("cls"); for(i=0; i<20; i++){ printf("Name: %s\n", user_array[i].name); } system("PAUSE"); for(i=0; i<5; i++){ fscanf(ptr_file_adminID, "%d", &(temp_int)); admin_array[i].id=temp_int; // this section reads every line from the text file and sets it to a structure variable fgets(temp_string, 129, ptr_file_adminname); strcpy(admin_array[i].name,temp_string); fgets(temp_string, 129, ptr_file_adminpassword); strcpy(admin_array[i].password,temp_string); } for(i=0; i<100; i++){ fscanf(ptr_file_smartphoneprice, "%d", &(temp_int)); smartphone_array[i].price=temp_int; fgets(temp_string, 129, ptr_file_smartphonename); strcpy(smartphone_array[i].name,temp_string); fgets(temp_string, 129, ptr_file_smartphonebrand); strcpy(smartphone_array[i].brand,temp_string); fgets(temp_description, 200, ptr_file_smartphonedescription); strcpy(smartphone_array[i].description, temp_description); } // START PROGRAM *THIS PART IS DONE* do { user_or_admin=0; stopper=0; system("cls"); printf("Welcome to the smartphone shopping cart!\nDo you wish to login or register?\n[1] - Login\n[2] - Register\n[3] - Exit the program\n"); scanf("%d", &log_in); // LOG IN *THIS PART IS DONE* if(log_in==1){ system("cls"); printf("Log In\n\n"); printf("Please enter your user ID:"); scanf("%d", &login_ID); printf("Please enter your password:"); getchar(); gets(login_password); strcat(login_password, "\n"); system("cls"); for(i=0; i<20; i++){ if((login_ID==user_array[i].id)&&(strcmp(user_array[i].password, login_password)==0)){ identity=i; user_or_admin=1; i=20; } } if((login_ID==user_array[1].id)&&(strcmp(user_array[i].password, login_password)==0)){ } else{ } system("PAUSE"); for(i=0; i<5; i++){ if((login_ID==admin_array[i].id)&&(strcmp(login_password,admin_array[i].password)==0)){ identity=i; user_or_admin=2; i=20; } if(login_ID==admin_array[i].id){ printf("MATCH!\n"); } else if (login_ID!=admin_array[i].id){ printf("Too bad..."); } printf("value: %d\n", strcmp(login_password,admin_array[i].password)); system("PAUSE"); } // LOGGED IN AS USER if(user_or_admin==1){ system("cls"); do{ pickloop=0; system("cls"); printf("\nWelcome to the smartphone shopping cart, %s\n", user_array[identity].name); printf("Please choose a transaction:\n\n"); printf("[1] - Browse smartphone database\n"); printf("[2] - Search a smartphone\n"); printf("[3] - My Account\n"); printf("[4] - Log Out\n"); scanf("%d", &transaction); switch(transaction) { case 1:{ system("cls"); printf("\t\t\t\tSmartphone Database\n\n"); for(i=0; i<20; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d\n", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } system("PAUSE"); system("cls"); for(i=20; i<40; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d\n", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } system("PAUSE"); system("cls"); for(i=40; i<60; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d\n", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } system("PAUSE"); system("cls"); for(i=60; i<80; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d\n", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } system("PAUSE"); system("cls"); for(i=80; i<100; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d\n", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } system("PAUSE"); printf("\n[1] - Add a smartphone\t\t[2] - Go Back\n"); scanf("%d", &admin_operation); break; } case 2:{ break; } case 3:{ break; } case 4:{ system("cls"); printf("Logging out...\n\n"); system("PAUSE"); pickloop=1; break; } default:{ system("cls"); printf("Invalid input!\n\n"); system("PAUSE"); } } } while(pickloop==0); } // LOGGED IN AS ADMIN *THIS PART IS DONE* else if(user_or_admin==2){ system("cls"); ptr_file_userID = fopen("User ID Text File.txt", "w"); ptr_file_userpassword = fopen("User Password Text File.txt", "w"); ptr_file_username = fopen("User Name Text File.txt", "w"); ptr_file_smartphonename = fopen("Smartphone Name Text File.txt", "w"); ptr_file_smartphonebrand = fopen("Smartphone Brand Text File.txt", "w"); ptr_file_smartphoneprice = fopen("Smartphone Price Text File.txt", "w"); ptr_file_smartphonedescription = fopen("Smartphone Description Text File.txt", "w"); do{ pickloop=0; printf("Administrator:\n\nPlease choose a transaction:\n"); printf("[1] - View users\n"); printf("[2] - View Smartphone Database\n"); printf("[3] - Log Out\n"); scanf("%d", &transaction); switch(transaction){ case 1:{ system("cls"); printf("\t\t\t\tUser Database\n\n"); for(i=0; i<20; i++){ printf("\t\t\t\tUSER #%d\n\n", i+1); if(user_array[i].id!=8){ printf("User ID: %d\n", user_array[i].id); printf("Username: %s\n", user_array[i].name); printf("User Password: %s", user_array[i].password); printf("Money of user: P%d\n\n\n", user_array[i].money); } else{ printf("NULL user\n\n\n"); } } printf("\n[1] - Edit a user\t\t[2] - Remove user\n[3] - Go Back\n"); scanf("%d", &admin_operation); switch(admin_operation){ case 1:{ printf("\n\nPlease enter the user number that you want to edit:"); scanf("%d", &edit_user); edit_user= edit_user-1; if((edit_user>=0)&&(edit_user<20)){ p_user = &user_array[edit_user]; user_editor(p_user); printf("\n\nYou have successfully editted a user!"); system("PAUSE"); } else{ printf("Invalid entry!\n"); system("PAUSE"); } break; } case 2:{ printf("\n\nPlease enter the user number that you want to remove:"); scanf("%d", &edit_user); edit_user= edit_user-1; if((edit_user>=0)&&(edit_user<20)){ user_array[edit_user].id = 8; user_array[edit_user].money = 0; strcpy(user_array[edit_user].name, ""); strcpy(user_array[edit_user].password, ""); printf("\n\nYou have successfully removed a user!"); system("PAUSE"); } else{ printf("Invalid entry!\n"); system("PAUSE"); } break; } case 3:{ printf("\n\nReturning to the Main Menu shortly\n\n"); system("PAUSE"); break; } default:{ system("cls"); printf("Invalid Input!\n\n"); system("PAUSE"); } } break; } case 2:{ system("cls"); printf("\t\t\t\tSmartphone Database\n\n"); for(i=0; i<100; i++){ printf("\t\t\t\tSMARTPHONE #%d\n\n", i+1); if(smartphone_array[i].name!= NULL){ printf("Name: %s\n", smartphone_array[i].name); printf("Brand: %s\n", smartphone_array[i].brand); printf("Price: P%d", smartphone_array[i].price); printf("Description: %s\n\n\n", smartphone_array[i].description); } else{ printf("SMARTPHONE UNAVAILABLE\n\n\n"); } } printf("\n[1] - Edit a smartphone\t\t[2] - Remove smartphone\n[3] - Go Back\n"); scanf("%d", &admin_operation); switch(admin_operation){ case 1:{ printf("\n\nPlease enter the smartphone number that you want to edit:"); scanf("%d", &edit_smartphone); edit_smartphone= edit_smartphone-1; if((edit_smartphone>=0)&&(edit_smartphone<100)){ p_smartphone = &smartphone_array[edit_smartphone]; smartphone_editor(p_smartphone); printf("\n\nYou have successfully editted a smartphonne!"); system("PAUSE"); } else{ printf("Invalid entry!\n"); system("PAUSE"); } break; } case 2:{ printf("\n\nPlease enter the smartphone number that you want to edit:"); scanf("%d", &edit_smartphone); edit_smartphone= edit_smartphone-1; if((edit_smartphone>=0)&&(edit_smartphone<100)){ strcpy(smartphone_array[edit_smartphone].name, ""); strcpy(smartphone_array[edit_smartphone].brand, ""); strcpy(smartphone_array[edit_smartphone].description, ""); smartphone_array[edit_smartphone].price = 8; printf("\n\nYou have successfully removed a smartphonne!"); system("PAUSE"); } else{ printf("Invalid entry!\n"); system("PAUSE"); } break; } case 3:{ printf("\n\nReturn to the Main Menu shortly\n\n"); system("PAUSE"); break; } default:{ system("cls"); printf("Invalid Input!\n\n"); system("PAUSE"); } } break; } case 3:{ system("cls"); printf("Logging out...\n\n"); system("PAUSE"); pickloop=1; break; } default:{ system("cls"); printf("Invalid input!\n\n"); system("PAUSE"); } } } while(pickloop=0); } else if(user_or_admin==0){ printf("I'm sorry. Your ID and password do not match!\n\n"); system("PAUSE"); } } // REGISTER *THIS PART IS DONE* else if(log_in==2){ system("cls"); ptr_file_userID = fopen("User ID Text File.txt", "w"); ptr_file_userpassword = fopen("User Password Text File.txt", "w"); // this opens the text files for writing ptr_file_username = fopen("User Name Text File.txt", "w"); // this region is very crucial when you're about to input something into the text files ptr_file_usermoney = fopen("User Money Text File.txt", "w"); for(i=0; i<20; i++){ if(user_array[i].id==8){ index=i; i=20; } } printf("index: %d\n\n", index); system("PAUSE"); if(index==-1){ system("cls"); printf("We are very sorry to inform you that the smartphone\n database has reached the maximum number of users.\n\nPlease consult one of the admins information.\n"); system("PAUSE"); } else if((index>=0)&&(index<20)){ printf("\t\t\tRegister\nPlease fill up the necessary information:\nNegative and zero ID numbers are considered invalid\n\n"); printf("Please enter a user ID:"); do{ pickloop=0; approver=0; scanf("%d", &temp); for(i=0; i<20; i++){ if(((temp==user_array[i].id)&&(index!=i))||(temp<=0)){ approver=1; } } if(approver==1){ printf("\nI'm sorry. This user ID has either already been taken or invalid.\nYou will be returned to the Main Menu...\n"); system("PAUSE"); pickloop=1; } else if(approver==0){ printf("\nPlease enter your name:"); getchar(); gets(user_array[index].name); printf("\nPlease enter a password:"); getchar(); gets(user_array[index].password); user_array[index].money = 500000; user_array[index].id = temp; system("cls"); printf("Welcome to the Smartphone Shopping Cart, %s!\n\nID: %d", user_array[index].name, user_array[index].id); printf("\nYou have an initial credit of P500, 000. Spend wisely!\n\n"); printf("\n\n\n\n\n\n\n\nYou will be returned to the Main Menu. Please log in to access your account.\n\n"); system("PAUSE"); fclose(ptr_file_userID); fclose(ptr_file_username); fclose(ptr_file_userpassword); fclose(ptr_file_usermoney); pickloop=1; } } while(pickloop==0); } } // EXIT *THIS PART IS DONE* else if(log_in==3){ system("cls"); printf("Exiting the program...\n\nThank you for using the smartphone shopping cart!\n\n"); system("PAUSE"); stopper=1; } else{ system("cls"); printf("Invalid input!\n"); system("PAUSE"); } } while(stopper==0); // THIS REGION SAVES THE DATA ON DIFFERENT TEXT FILES *THIS PART IS DONE* for(i=0; i<20; i++){ fprintf(ptr_file_userID, "%d\n", user_array[i].id); fprintf(ptr_file_usermoney, "%d\n", user_array[i].money); fprintf(ptr_file_username, "%s\n", user_array[i].name); fprintf(ptr_file_userpassword, "%s\n", user_array[i].password); } for(i=0; i<5; i++){ fprintf(ptr_file_adminID, "%d\n", admin_array[i].id); fprintf(ptr_file_adminname, "%s\n", admin_array[i].name); fprintf(ptr_file_adminpassword, "%s\n", admin_array[i].password); } for(i=0; i<100; i++){ fprintf(ptr_file_smartphonename, "%s\n", smartphone_array[i].name); fprintf(ptr_file_smartphonebrand, "%s\n", smartphone_array[i].brand); fprintf(ptr_file_smartphoneprice, "%d\n", smartphone_array[i].price); fprintf(ptr_file_smartphonedescription, "%s\n", smartphone_array[i].description); } // THIS REGION SAVES AND CLOSES THE TEXT FILES *THIS PART IS DONE* // don't forget this step because forgetting to close the text files will result to unsaved data fclose(ptr_file_userID); fclose(ptr_file_username); fclose(ptr_file_userpassword); fclose(ptr_file_usermoney); fclose(ptr_file_adminID); fclose(ptr_file_adminname); fclose(ptr_file_adminpassword); fclose(ptr_file_smartphonename); fclose(ptr_file_smartphonebrand); fclose(ptr_file_smartphoneprice); fclose(ptr_file_smartphonedescription); return 0; } void user_editor(struct user *p_user){ int temp_int; char temp_string[129]; system("cls"); printf("Current information:\n"); printf("Username: %s\n", p_user->name); printf("User Password: %s", p_user->password); printf("Money of user: %d\n\n\n", p_user->money); printf("Edit:\n"); printf("Please enter a new user ID:"); scanf("%d", &temp_int); p_user->id = temp_int; printf("Please enter a new username:"); getchar(); gets(temp_string); strcpy(p_user->name,temp_string); printf("Please enter a new user password:"); getchar(); gets(temp_string); strcpy(p_user->password,temp_string); printf("Please enter a new user credit:"); scanf("%d", &temp_int); p_user->money = temp_int; return; } void smartphone_editor(struct smartphone *p_smartphone){ int temp_int; char temp_string[129]; system("cls"); printf("Current information:\n"); printf("Smartphone Name: %s\n", p_smartphone->name); printf("Smartphone Brand: %s\n", p_smartphone->brand); printf("Smartphone Price: %d\n", p_smartphone->price); printf("Smartphone Description: %s\n", p_smartphone->description); printf("Edit:\n"); printf("Please enter a new Smartphone Name:"); getchar(); gets(temp_string); strcpy(p_smartphone->name,temp_string); printf("Please enter a new Brand:"); getchar(); gets(temp_string); strcpy(p_smartphone->brand,temp_string); printf("Please enter a new Price: P"); scanf("%d", &temp_int); p_smartphone->price = temp_int; printf("Please enter a new Description:"); getchar(); gets(temp_string); strcpy(p_smartphone->description,temp_string); return; }
true
f9da09d5d5abf8482240b4c71328343ecf35de93
C++
darkeclipz/cpp-virtual-machine
/cpp-assembler/LexicalAnalyzer.cpp
UTF-8
4,834
2.828125
3
[]
no_license
#include "LexicalAnalyzer.h" #include "sstream"; #include "../cpp-utils/utils.cpp" LexicalAnalyzer::LexicalAnalyzer(SourceFile& source) { this->vm = new VirtualMachine(1); this->source = &source; init_mnemonic_table(); init_symbol_table(); init_function_table(); init_register_table(); } LexicalAnalyzer::~LexicalAnalyzer() { this->source = nullptr; delete this->vm; } void LexicalAnalyzer::init_mnemonic_table() { // Mnemonic identifiers should be capital cased. for (auto& instruction : vm->lookup) { std::string mnemonic = to_upper(instruction.mnemonic); if (!mnemonic_table.count(mnemonic)) { mnemonic_table[mnemonic] = true; } } } void LexicalAnalyzer::init_function_table() { // Function identifiers must be capital cased. function_table["DB"] = true; } void LexicalAnalyzer::init_symbol_table() { // Symbol identifiers must be capital cased. symbol_table["$"] = 0; } void LexicalAnalyzer::init_register_table() { // Register identifiers must be capital cased. register_table["AX"] = VirtualMachine::REGISTERS::AX; register_table["BX"] = VirtualMachine::REGISTERS::BX; register_table["CX"] = VirtualMachine::REGISTERS::CX; register_table["DX"] = VirtualMachine::REGISTERS::DX; register_table["SP"] = VirtualMachine::REGISTERS::SP; register_table["SB"] = VirtualMachine::REGISTERS::SB; register_table["BP"] = VirtualMachine::REGISTERS::BP; register_table["IP"] = VirtualMachine::REGISTERS::IP; } bool LexicalAnalyzer::end() { return source->end(); } bool LexicalAnalyzer::is_alphanumeric(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '$'; // $ is current address. } bool LexicalAnalyzer::is_digit(char ch) { return ch >= '0' && ch <= '9'; } void LexicalAnalyzer::read_whitespace() { char ch = source->next_char(); while (is_whitespace(ch)) { ch = source->next_char(); } source->put_back(ch); } void LexicalAnalyzer::read_comment() { char ch = source->next_char(); if (ch == ';') { while (ch != '\n') { ch = source->next_char(); } } source->put_back(ch); } bool LexicalAnalyzer::is_whitespace(char ch) { switch (ch) { case ' ': case '\n': case '\r': case '\t': case ',': return true; default: return false; } } bool LexicalAnalyzer::is_delimeter(char ch) { return ch == ';' || ch == ','; } Token::TOKEN_TYPE LexicalAnalyzer::token_type(std::string value) { if (value[0] == '%') { return Token::TOKEN_TYPE::PREPROCESS; } else if (register_table.count(to_upper(value))) { return Token::TOKEN_TYPE::REG; } else if (mnemonic_table.count(to_upper(value))) { return Token::TOKEN_TYPE::MNEMONIC; } else if (function_table.count(to_upper(value))) { return Token::TOKEN_TYPE::FUNCTION; } else if (value[0] == '"' && value[value.size() - 1] == '"') { return Token::TOKEN_TYPE::STRING; } else if (value[0] == '\'' && value[value.size() - 1] == '\'') { return Token::TOKEN_TYPE::CHAR; } else if (value[value.size() - 1] == ':') { return Token::TOKEN_TYPE::LABEL; } else if (value[0] == '[' && value[value.size()-1] == ']') { value = value.substr(1, value.size() - 2); if (is_digit(value[0]) && value.substr(0, 2) == "0x") { return Token::TOKEN_TYPE::MEM; } else if (register_table.count(to_upper(value))) { return Token::TOKEN_TYPE::PTR; } else if (!register_table.count(to_upper(value))) { return Token::TOKEN_TYPE::MEM; } } else { if (is_alphanumeric(value[0])) { return Token::TOKEN_TYPE::IDENTIFIER; } else if (is_digit(value[0]) || value.substr(0, 2) == "0x") { return Token::TOKEN_TYPE::CONSTANT; } } throw std::invalid_argument("Unable to determine token type for " + value); } std::string LexicalAnalyzer::read_str() { bool escape = false; std::stringstream str; str << source->next_char(); char ch = source->next_char(); for (; !source->end() && (ch != '"' || escape); ch = source->next_char()) { escape = ch == '\\'; str << ch; } str << ch; return str.str(); } std::string LexicalAnalyzer::read_word() { std::stringstream word; char ch = source->next_char(); for (; !source->end() && !is_whitespace(ch) && !is_delimeter(ch); ch = source->next_char()) { word << ch; } source->put_back(ch); return word.str(); } bool LexicalAnalyzer::next_token(Token& tok) { if (buffer_full) { buffer_full = false; tok = buffered_token; return true; } std::string word; read_whitespace(); read_comment(); char ch = source->next_char(); source->put_back(ch); if (ch == '"') { word = read_str(); } else { word = read_word(); } if (word.size() > 0) { std::string val = word; tok = Token(token_type(val), val); return true; } if (!source->end()) { return next_token(tok); } throw std::invalid_argument("an error occured."); } void LexicalAnalyzer::put_back(Token tok) { buffered_token = tok; buffer_full = true; }
true
d73187971e057bf62d5f45be17290d5cc2f40f8e
C++
manjurrashed/coding-solution
/c_plus_plus/Algorithm_expert/Easy/Easy_RunLength_Encoding.cpp
UTF-8
709
2.921875
3
[]
no_license
using namespace std; string runLengthEncoding(string str) { // Write your code here. #if 0 int slow = 0; int fast = 0; int cnt = 0; string result = ""; for (; fast < str.length(); fast++) { if (str[slow] == str[fast] && cnt < 9) { cnt++; } else { result += std::to_string(cnt) + str[slow]; slow = fast; cnt = 1; } } result += std::to_string(cnt) + str[fast - 1]; return result; #endif #if 1 string result = ""; int i; int cnt = 1; for (i = 1; i < str.length(); i++) { if (str[i - 1] == str[i] && cnt < 9) { cnt++; } else { result += std::to_string(cnt) + str[i - 1]; cnt = 1; } } result += std::to_string(cnt) + str[i - 1]; return result; #endif }
true
2dc5ed7a78e0646983ee9b04c3721ebe44c0c033
C++
mardelgabo/Ejercicios-sin-arreglos
/Ejercicio 17.cpp
UTF-8
794
3.03125
3
[]
no_license
#include <stdio.h> #include <conio.h> main() { int e,c; float b,potencia=1; printf("Ingrese un valor entero para el exponente \n"); scanf("%d",&e); printf("Ingrese un valor real para la base \n"); scanf("%f",&b); if (e==0) { printf("La potencia de %f elevado a %d es 1 \n",b,e); getche(); } if ((b==0)&&(e<0)) { printf("No existe solucion para esta potencia \n"); getche(); } if (e==1){ printf("La potencia de %f elevado a %d es igual a %f \n",b,e,b); } if (e>1) { for (c=0;c<e;++c) { potencia *= b; } printf("La potencia de %f elevado a %d es %f \n",b,e,potencia); getche(); } else if (e<0) { for (c=0;c>e;--c) { potencia *= (1/b); } printf("La potencia de %f elevado a %d es %f \n",b,e,potencia); getche(); } }
true
3ce99d46428fd5e18dc944b041c627ac2654c218
C++
biqar/interviewbit
/Hashing/Hash search/2 Sum/two_sum.cpp
UTF-8
1,363
3.5
4
[ "MIT" ]
permissive
// // Created by Islam, Abdullah Al Raqibul on 5/29/20. // // update the index_1 and index_2 according to the folllowing rule: // - If multiple solutions exist, output the one where index2 is minimum. void update_interval(int &cur_1, int &cur_2, int new_1, int new_2) { if(new_2 < cur_2) { cur_1 = new_1; cur_2 = new_2; } } vector<int> Solution::twoSum(const vector<int> &A, int B) { map<int, vector<int>> m; int sz = A.size(); int idx_1 = sz, idx_2 = sz; vector<int> ret; for(int i=0; i<sz; i+=1) { m[A[i]].push_back(i+1); } // note: the following loop will run to search for the first index for(int i=0; i<sz; i+=1) { if(m.find(B-A[i]) != m.end()) { // case: 4 = 2 + 2 if(A[i] == B-A[i]) { if(m[A[i]].size() >= 2) { update_interval(idx_1, idx_2, m[A[i]][0], m[A[i]][1]); } } else { // as noted earlier, loop on "i" runs to find the first index // and problem statement clarify "index1 < index2" if(m[B-A[i]][0] > i+1) { update_interval(idx_1, idx_2, i+1, m[B-A[i]][0]); } } } } if(idx_1 != sz && idx_2 != sz) { ret.push_back(idx_1); ret.push_back(idx_2); } return ret; }
true
b49bd91a17299f08ff3da0859a1e3aecfd9219ac
C++
aaryan6789/cppSpace
/Matrix/rotate_matrix.cpp
UTF-8
1,968
3.9375
4
[]
no_license
#include "_matrix.h" /** * CTCI * Rotate Matrix: * Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, * Write a method to rotate the image by 90 degrees. Can you do this in place? * * Examples : Input 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 */ #include <vector> #include <algorithm> using namespace std; // Anti Clock Wise Rotation : // Transpose the Matrix --> Reverse Colums // Clock Wise Rotation : // Transpose the Matrix --> Reverse Rows // Time complexity : O(n2) // Space complexity : O(1) since we do a rotation in place. void rotate(vector<vector<int>>& matrix) { int R = matrix.size(); // Transpose the Matrix for(int i=0; i<R; i++) for(int j=0; j<i; j++) swap(matrix[i][j], matrix[j][i]); // Reverse the Rows for(int i=0; i<R; i++) reverse(matrix[i].begin(), matrix[i].end()); } // Transpose a NxN Matrix only means the rows becomes columns and cols becomes rows void transpose(vector<vector<int>>& mat){ cout << "Transposing " << endl; printMatrix(mat); cout << endl; int R = mat.size(); int C = mat[0].size(); for(int r = 0; r< R; r++){ for(int c = r; c< C; c++){ std::swap(mat[r][c], mat[c][r]); } } printMatrix(mat); } void reverseColums(vector<vector<int>>& mat){ cout << "Reversing Colums" << endl; int R = mat.size(); int C = mat[0].size(); for (int i = 0; i< R; i++){ for(int j = 0, k = C-1; j< k; j++, k--){ swap(mat[j][i], mat[k][i]); } } printMatrix(mat); } void rotateMatrix(vector<vector<int>>& mat){ cout << "Rotating" << endl; transpose(mat); reverseColums(mat); }
true
5211b7a9ed46c23c2a25cd9e92843fd7bc9645c9
C++
imalerich/imDX11
/imDX11/Model.h
UTF-8
510
2.640625
3
[]
no_license
#pragma once #include <stdlib.h> #include <memory> #include <vector> #include "Material.hpp" #include "d3dutil.h" #include "Mesh.h" class Model { public: Model(); Model(const char * Filename); /** * Release all buffers stored by this model. */ void Release(); /** * Loops through each mesh in the model, * and Draw's them to the current DX11 * graphics context. */ void Draw(); private: std::vector<std::shared_ptr<Mesh>> meshes; std::vector<std::shared_ptr<Material>> materials; };
true
4fece38ba0d203fd4ec894d3cc93bff5e50a2b09
C++
feverzsj/jkl
/include/jkl/util/concepts.hpp
UTF-8
4,117
2.71875
3
[ "MIT" ]
permissive
#pragma once #include <jkl/config.hpp> #include <jkl/util/type_traits.hpp> #include <jkl/util/std_concepts.hpp> #include <memory> #include <tuple> #include <climits> namespace jkl{ // In Most Cases: // for type traits, apply std::remove_cv_t on the tested type; // for concepts, apply std::remove_cvref_t on the tested type; template<class T, class... Args> concept _trivially_constructible_ = std::is_trivially_constructible_v<std::remove_cvref_t<T>, Args...>; template<class T> concept _trivially_copyable_ = std::is_trivially_copyable_v<std::remove_cvref_t<T>>; template<class T> concept _trivial_ = _trivially_constructible_<T> && _trivially_copyable_<T>; template<class T> concept _standard_layout_ = std::is_standard_layout_v<std::remove_cvref_t<T>>; template<class T> concept _pod_ = _trivial_<T> && _standard_layout_<T>; template<class T> concept _class_ = std::is_class_v<std::remove_cvref_t<T>>; template<class T> concept _pointer_ = std::is_pointer_v<std::remove_reference_t<T>>; template<class T> concept _nullptr_ = std::is_null_pointer_v<std::remove_reference_t<T>>; template<class T> concept _arithmetic_ = std::is_integral_v<std::remove_reference_t<T>> || std::is_floating_point_v<std::remove_reference_t<T>>; template<class T> concept _unsigned_ = std::is_unsigned_v<std::remove_reference_t<T>>; // for unsigned arithmetic template<class T> concept _signed_ = std::is_signed_v<std::remove_reference_t<T>>; // for signed arithmetic, also including floating point template<class T> concept _strict_integral_ = std::is_integral_v<std::remove_reference_t<T>> && ! std::is_same_v<std::remove_cvref_t<T>, bool>; template<class T> concept _char_ = is_one_of_v<std::remove_cvref_t<T>, char, signed char, unsigned char, wchar_t, char8_t, char16_t, char32_t>; template<class T> concept _byte_ = (sizeof(T) == sizeof(std::byte)) && _pod_<T>; template<class T> concept _8bits_ = (sizeof(T) * CHAR_BIT == 8 ) && _pod_<T>; template<class T> concept _16bits_ = (sizeof(T) * CHAR_BIT == 16) && _pod_<T>; template<class T> concept _32bits_ = (sizeof(T) * CHAR_BIT == 32) && _pod_<T>; template<class T> concept _64bits_ = (sizeof(T) * CHAR_BIT == 64) && _pod_<T>; template<class T> concept _array_ = std::is_array_v<std::remove_reference_t<T>>; // array types are considered to have the same cv-qualification as their element types, https://stackoverflow.com/questions/27770228/what-type-should-stdremove-cv-produce-on-an-array-of-const-t template<class T> concept _std_array_ = is_std_array_v<std::remove_reference_t<T>>; template<class T> concept _std_tuple_ = requires(T& t){ std::tuple_size<std::remove_reference_t<T>>::value; std::get<0>(t); }; template<class T> concept _unique_ptr_ = is_unique_ptr_v<std::remove_reference_t<T>>; template<class T> concept _shared_ptr_ = is_shared_ptr_v<std::remove_reference_t<T>>; template<class T> concept _smart_ptr_ = _unique_ptr_<T> || _shared_ptr_<T>; template<class T> concept _optional_ = is_optional_v<std::remove_reference_t<T>>; // unlike is_invocable_r which matches void return type to any type, this only matches void return type to void template<class R, class F, class... Args> concept _callable_r_ = requires(F&& f, Args&&... args){ {std::invoke(static_cast<F&&>(f), static_cast<Args&&>(args)...)} -> std::convertible_to<R>; }; template<class T> concept _range_ = requires(T& r){ std::begin(r); std::end(r); }; template<class T> concept _random_access_range_ = _range_<T> && requires(T& r){ {std::end(r) - std::begin(r)} -> std::integral; }; template<_range_ R> using range_value_t = std::remove_cvref_t<decltype(*std::begin(std::declval<R&>()))>; template<class T, class R> concept _similar_random_access_range_ = _random_access_range_<R> && _random_access_range_<T> && std::same_as<range_value_t<T>, range_value_t<R>>; template<class T, class R> concept _similar_random_access_range_or_val_ = _random_access_range_<R> && (std::same_as<T, range_value_t<R>> || (_random_access_range_<T> && std::same_as<range_value_t<T>, range_value_t<R>>)); } // namespace jkl
true
d0058ac078d3f670a47883aca90ef746f42cec57
C++
graceyangfan/Leetcode
/整数拆分.CPP
UTF-8
1,147
3.234375
3
[]
no_license
class Solution { public: int integerBreak(int n) { if (n <= 3) { return n - 1; } int quotient = n / 3; int remainder = n % 3; if (remainder == 0) { return (int)pow(3, quotient); } else if (remainder == 1) { return (int)pow(3, quotient - 1) * 4; } else { return (int)pow(3, quotient) * 2; } } }; /***动态规划 从小到大一次求解保存到vector中 ***/ class Solution { public: int integerBreak(int n) { if (n < 4) { return n - 1; } vector<int> dp(n+1); dp[2]=1; for(int i=3;i<=n;i++) { dp[i]=max(max(2*(i-2),2*dp[i-2]),max(3*(i-3),3*dp[i-3])); } return dp[n]; } }; class Solution { public: int integerBreak(int n) { if (n < 4) { return n - 1; } vector<int> dp(n+1); dp[2]=1; for(int i=2;i<=n;i++) { for(int j=1;j<i;j++) { dp[i]=max(dp[i],j*max(i-j,dp[i-j])); } } return dp[n]; } };
true
742e783ee42ccec54bd781afe386af5d45dcc289
C++
hasbegun/BiometricLib
/src/Iris/Iris/AlignLRPupilPos.h
UTF-8
1,890
3.1875
3
[]
no_license
/********************************************************* ** @file AlignLRPupilPos.h ** Functions for aligning the left and right eye position. ** **********************************************************/ #ifndef ALIGN_LR_PUPIL_POS_H #define ALIGN_LR_PUPIL_POS_H #include "ImageUtility.h" class AlignLRPupilPos { public: AlignLRPupilPos(void); ~AlignLRPupilPos(void); /** * Determine the degree difference between the left and the right eye based the pupil center info. * Extracts the left ("_L") and right ("_R") eye as files. * * @param img Input image * @param rIrisMax Maximum radius of a potential pupil circle * @param circle1 (OUT) Returns the right pupil info * (Biggest circle-> 0:x, 1:y, 2:radius, Secondary circle->3:x, 4:y, 5:radius,) * @param circle2 (OUT) Returns the left pupil info * (Biggest circle-> 0:x, 1:y, 2:radius, Secondary circle->3:x, 4:y, 5:radius,) * @param lImg (OUT) Returns the left iris image * @param rImg (OUT) Returns the right iris image */ static void alignDegreeDiff(IplImage* img, int rIrisMax, int* circle1, int* circle2, IplImage*& lImg, IplImage*& rImg); /** * Rotate an image based on a specified angle. * * @param eyeImg Input image * @param angle Degree difference * @return (OUT) Rotated image */ static IplImage* rotate(IplImage* eyeImg, double angle); /** * Get the angle difference between the right and left pupil position. * * @param px1 Right puil center X * @param py1 Right puil center Y * @param px2 Left puil center X * @param py2 Left puil center Y * @return (OUT) Angle */ static double getAngle(int px1, int py1, int px2, int py2); }; #endif // !ALIGN_LR_PUPIL_POS_H
true
a48171c7556fe6177388a52150d98a1d40a88ebc
C++
MatteoMorisoli/MultiTreeRouting
/MultiTreeRouting/MultiTreeRouting/DataAnalyser.cpp
UTF-8
9,615
2.5625
3
[]
no_license
// // DataAnalyser.cpp // MultiTreeRouting // // Created by Matteo Morisoli on 26.04.18. // Copyright © 2018 MatteoMorisoli. All rights reserved. // #include "DataAnalyser.hpp" // // main.cpp // DataAnalyzer // // Created by Matteo Morisoli on 12.04.18. // Copyright © 2018 MatteoMorisoli. All rights reserved. // DataAnalyser::DataAnalyser(std::string f, std::string suf, bool isStar, int treeN){ filePath = f; sizeCounter = 0; sum = 0; hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8" ,"9", "A", "B", "C", "D", "E", "F"}; suffix = suf; treeNum = treeN; if(isStar){ suffix.append("star"); }else{ suffix.append("all"); } suffix.append(std::to_string(treeNum)); } void DataAnalyser::addData(diagMatrixFloat &sm){ for(int i = 0; i < sm.size1(); ++i){ for(int j = i; j < sm.size2(); j++){ long double value = sm(i, j); sum += value; ++sizeCounter; if(valueMap.find(value) == valueMap.end()){ valueMap.insert(std::pair<double, long>(value, 1)); }else{ valueMap[value] += 1; } } } } void DataAnalyser::addAndPrintCongestionData(diagMatrixFloat &sm, std::map<int, std::string> &nm){ long double max = -1; for(int i = 0; i < sm.size1(); ++i){ for(int j = i; j < sm.size2(); j++){ long double value = sm(i, j); if(value > max){ max = value; } sum += value; ++sizeCounter; if(valueMap.find(value) == valueMap.end()){ valueMap.insert(std::pair<double, long>(value, 1)); }else{ valueMap[value] += 1; } } } std::size_t dotPos = filePath.find_last_of("."); std::string graphFilePath = filePath.substr(0, dotPos); graphFilePath.append(suffix); graphFilePath.append("graph.dot"); std::ofstream graph(graphFilePath); graph << "graph D {\n"; graph << " graph[label=\"congestion average for " << treeNum << " trees\"];\n"; for(std::map<int, std::string>::iterator it = nm.begin(); it != nm.end(); ++it){ graph << it->first << " [label=\"" << it->second << "\"];\n"; } std::vector<std::string> nonZeroStrings; for(int i = 0; i < sm.size1(); ++i){ for(int j = i; j < sm.size2(); j++){ int num = ((int) sm(i, j) * 255 * 2 / (max)); if(num > 255){ num = 255; } std::stringstream s; s << "#" << std::hex << hex[num /16] << hex[num % 16] << "0000"; std::string h(s.str()); if(sm(i, j) >= 1){ //graph << i << " -- " << j+1 << "[label=\"" << sm(i,j) << "\"" << ", color=\"" << h << "\", penwidth=3];\n"; graph << i << " -- " << j+1 << "[color=\"" << h << "\", penwidth=3];\n"; } } } graph << "}\n"; graph.close(); } void DataAnalyser::generateStretchFiles(){ long double mean = sum / (long double) sizeCounter; double min = DataAnalyser::valueOfIndex(valueMap, 0); double max = DataAnalyser::valueOfIndex(valueMap, sizeCounter); long double median; long double firstQuartile; long double thirdQuartile; if(sizeCounter % 2 == 0){ median = (DataAnalyser::valueOfIndex(valueMap, sizeCounter/2) + valueOfIndex(valueMap, sizeCounter/2 + 1)) / 2.0; if(sizeCounter % 4 == 0){ firstQuartile = (DataAnalyser::valueOfIndex(valueMap, sizeCounter/4) + DataAnalyser::valueOfIndex(valueMap, sizeCounter/4 + 1)) / 2.0; thirdQuartile = (DataAnalyser::valueOfIndex(valueMap, 3 * sizeCounter/4) + DataAnalyser::valueOfIndex(valueMap, 3 * sizeCounter/4 + 1)) / 2.0; }else{ firstQuartile = valueOfIndex(valueMap, sizeCounter/4 + 1); thirdQuartile = valueOfIndex(valueMap, 3 * sizeCounter/4 + 1); } }else{ median = valueOfIndex(valueMap, sizeCounter/2 + 1); if(sizeCounter % 4 == 0){ firstQuartile = (valueOfIndex(valueMap, sizeCounter/4) + valueOfIndex(valueMap, sizeCounter/4 + 1)) / 2.0; thirdQuartile = (valueOfIndex(valueMap, 3 * sizeCounter/4) + valueOfIndex(valueMap, 3 * sizeCounter/4 + 1)) / 2.0; }else{ firstQuartile = valueOfIndex(valueMap, sizeCounter/4 + 1); thirdQuartile = valueOfIndex(valueMap, 3 * sizeCounter/4 + 1); } } std::size_t dotPos = filePath.find_last_of("."); std::string refinedFilePath = filePath.substr(0, dotPos); refinedFilePath.append(suffix); refinedFilePath.append("refined.csv"); std::string reviewFilePath = filePath.substr(0, dotPos); reviewFilePath.append(suffix); reviewFilePath.append("review.txt"); std::string valueFilePath = filePath.substr(0, dotPos); valueFilePath.append(suffix); valueFilePath.append("value.txt"); std::ofstream refined(refinedFilePath); refined << min << "," << firstQuartile << "," << median << "," << thirdQuartile << "," << max; refined.close(); std::ofstream review(reviewFilePath); review << "The number of datapoints is: " << sizeCounter << std::endl; review << "The minimum is: " << min << std::endl; review << "The first quartile is: " << firstQuartile << std::endl; review << "The median is: " << median << std::endl; review << "The third quartile is: " << thirdQuartile << std::endl; review << "The maximum is: " << max << std::endl; review << "The mean is: " << mean << std::endl; review << "The results are: " << std::endl; for(std::map<double, long>::iterator it = valueMap.begin(); it != valueMap.end(); ++it){ review << "We have " << it->second << " instances of the value " << it->first << std::endl; } review.close(); std::ofstream values(valueFilePath); for(std::map<double, long>::iterator it = valueMap.begin(); it != valueMap.end(); ++it){ values << it->first << "," << it->second << std::endl; } } void DataAnalyser::generateCongestionFiles(){ std::map<double, long> newMap = valueMap; long newCounter = sizeCounter - valueMap[0]; newMap.erase(0); long double median; long double firstQuartile; long double thirdQuartile; double min = DataAnalyser::valueOfIndex(newMap, 0); double max = DataAnalyser::valueOfIndex(newMap, newCounter); long double mean = sum / (long double) newCounter; if(newCounter % 2 == 0){ median = (DataAnalyser::valueOfIndex(newMap, newCounter/2) + valueOfIndex(newMap, newCounter/2 + 1)) / 2.0; if(newCounter % 4 == 0){ firstQuartile = (DataAnalyser::valueOfIndex(newMap, newCounter/4) + DataAnalyser::valueOfIndex(newMap, newCounter/4 + 1)) / 2.0; thirdQuartile = (DataAnalyser::valueOfIndex(newMap, 3 * newCounter/4) + DataAnalyser::valueOfIndex(newMap, 3 * newCounter/4 + 1)) / 2.0; }else{ firstQuartile = valueOfIndex(newMap, newCounter/4 + 1); thirdQuartile = valueOfIndex(newMap, 3 * newCounter/4 + 1); } }else{ median = valueOfIndex(newMap, newCounter/2 + 1); if(newCounter % 4 == 0){ firstQuartile = (valueOfIndex(newMap, newCounter/4) + valueOfIndex(newMap, newCounter/4 + 1)) / 2.0; thirdQuartile = (valueOfIndex(newMap, 3 * newCounter/4) + valueOfIndex(newMap, 3 * newCounter/4 + 1)) / 2.0; }else{ firstQuartile = valueOfIndex(newMap, newCounter/4 + 1); thirdQuartile = valueOfIndex(newMap, 3 * newCounter/4 + 1); } } std::size_t dotPos = filePath.find_last_of("."); std::string refinedFilePath = filePath.substr(0, dotPos); refinedFilePath.append(suffix); refinedFilePath.append("refined.csv"); std::string reviewFilePath = filePath.substr(0, dotPos); reviewFilePath.append(suffix); reviewFilePath.append("review.txt"); std::string valueFilePath = filePath.substr(0, dotPos); valueFilePath.append(suffix); valueFilePath.append("value.txt"); std::ofstream refined(refinedFilePath); refined << min << "," << firstQuartile << "," << median << "," << thirdQuartile << "," << max; refined.close(); std::ofstream review(reviewFilePath); review << "The number of datapoints is: " << sizeCounter << std::endl; review << "The number of non-zero datapoints is: " << newCounter << std::endl; review << "The minimum is: " << min << std::endl; review << "The first quartile is: " << firstQuartile << std::endl; review << "The median is: " << median << std::endl; review << "The third quartile is: " << thirdQuartile << std::endl; review << "The maximum is: " << max << std::endl; review << "The mean is: " << mean << std::endl; review << "The results are: " << std::endl; for(std::map<double, long>::iterator it = valueMap.begin(); it != valueMap.end(); ++it){ review << "We have " << it->second << " instances of the value " << it->first << std::endl; } review.close(); std::ofstream values(valueFilePath); for(std::map<double, long>::iterator it = valueMap.begin(); it != valueMap.end(); ++it){ values << it->first << "," << it->second << std::endl; } } double DataAnalyser::valueOfIndex(const std::map<double, long> & map, long index)const{ long reachedIndex = 0; for( std::map<double, long>::const_iterator it = map.begin(); it != map.end(); ++it){ reachedIndex += it->second; if( reachedIndex >= index){ return it->first; } } return -1.0; }
true
439e56229ef3e3ee6bed09605ca826da9706ced9
C++
zecrotic/CoffeeKing
/displaySugarDigit.ino
UTF-8
3,052
2.59375
3
[]
no_license
void displaySugarDigit(int digit) { switch (digit) //Case number will be the displayed digit { case 0: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, HIGH); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, LOW); break; case 1: digitalWrite(a_sugar, LOW); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, LOW); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, LOW); digitalWrite(g_sugar, LOW); break; case 2: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, LOW); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, HIGH); digitalWrite(f_sugar, LOW); digitalWrite(g_sugar, HIGH); break; case 3: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, LOW); digitalWrite(g_sugar, HIGH); break; case 4: digitalWrite(a_sugar, LOW); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, LOW); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, HIGH); break; case 5: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, LOW); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, HIGH); break; case 6: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, LOW); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, HIGH); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, HIGH); break; case 7: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, LOW); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, LOW); digitalWrite(g_sugar, LOW); break; case 8: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, HIGH); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, HIGH); break; case 9: digitalWrite(a_sugar, HIGH); digitalWrite(b_sugar, HIGH); digitalWrite(c_sugar, HIGH); digitalWrite(d_sugar, HIGH); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, HIGH); digitalWrite(g_sugar, HIGH); break; case 10: digitalWrite(a_sugar, LOW); digitalWrite(b_sugar, LOW); digitalWrite(c_sugar, LOW); digitalWrite(d_sugar, LOW); digitalWrite(e_sugar, LOW); digitalWrite(f_sugar, LOW); digitalWrite(g_sugar, LOW); break; } }
true
7f434bbed2c963aad8ffb5181722d4f74f60eb81
C++
KwintenSchram/Frogger
/src/Level.cpp
UTF-8
11,024
2.625
3
[]
no_license
/* * Level.cpp * * This object will execute the playing part of the game. * It creates and manages the entities by moving them and checking for collision. * * Created on: 8-apr.-2016 * Author: Kwinten */ #include <Level.h> #include <levelGenerator/levelProperties.h> #include "levelGenerator/RowProp.h" using namespace frogger; Level::Level(Factory* F, Window* win, std::list<Player*>* players, int rowHeight, LevelProperties* lvlprop) : F(F), win(win), players(players), rowHeight(rowHeight), lvlprop(lvlprop) { initLevel(); } Level::~Level() { for(std::list<Props*> props:*propsOnRow) { for(Props* prop:props) delete(prop); props.clear(); } propsOnRow->clear(); for(Row* row:*rows) delete(row); rows->clear(); } void Level::levelExecution(std::string keyStroke) { int factor = 3; int freeRows = 4; freeRows = (lvlprop->getDifficulty() == 'M') ? 3 : freeRows; freeRows = (lvlprop->getDifficulty() == 'H') ? 2 : freeRows; for (Player* player : *players) { int tempFactor = 0; if (player->getRemainingTime() == 0) player->hit(); else { player->takeAction(keyStroke); } if (lvlprop->getMode() == 'E' && player->getY() < *win->getGameWindowHeight() - rowHeight * freeRows) { tempFactor = 1; tempFactor =player->getY()< *win->getGameWindowHeight()- rowHeight * (freeRows + 1) ? 2 : tempFactor; tempFactor =player->getY()< *win->getGameWindowHeight()- rowHeight * (freeRows + 2) ? 3 : tempFactor; tempFactor =player->getY()< *win->getGameWindowHeight()- rowHeight * (freeRows + 3) ? 4 : tempFactor; tempFactor =player->getY()< *win->getGameWindowHeight()- rowHeight * (freeRows + 4) ? 5 : tempFactor; } if (!player->isDead()) factor = (factor > tempFactor) ? tempFactor : factor; } if (lvlprop->getMode() == 'E') followFrog(rows, players, factor); if (lvlprop->getMode() == 'E') extraRowNeeded(*win->getGameWindowHeight(), *win->getWidth(), F, rows, propsOnRow, lvlprop); win->generateBackground(rows); propsGenerator(F, rows, propsOnRow); drawGameElements(propsOnRow, players); collisionDetection(propsOnRow, players); objectiveDone = lvlprop->getMode() == 'E' ? false : objectiveCompleteCheck(propsOnRow); } void Level::rowGenerator(int rowHeight, int screenHight, Factory* F, std::vector<Row*>* rows, std::vector<std::list<Props*>>* propsOnRow, LevelProperties* lvlprop) { int numberOfRows = (screenHight) / rowHeight; std::list<Props*> enemies; char dir = 'L'; RowProp* rowProp; if (lvlprop->getMode() == 'E') { for (int n = 0; n < numberOfRows + 2; n++) { int yloc; yloc = (screenHight - rowHeight) - (n * rowHeight); if (n == (0)) rowProp = lvlprop->getFirstRow(); else rowProp = lvlprop->getRandomRow(); rows->push_back(F->createRow(dir, yloc, rowHeight, n, rowProp)); propsOnRow->push_back(enemies); dir = dir == 'R' ? 'L' : 'R'; } } else { for (int n = 0; n < numberOfRows; n++) { if (n == 0) rowProp = lvlprop->getLastRow(); else if (n == (numberOfRows - 1)) rowProp = lvlprop->getFirstRow(); else if (n == numberOfRows / 2) rowProp = lvlprop->getMiddleRow(); else if (n <= (numberOfRows / 4)) rowProp = lvlprop->getSeg4(); else if (n <= (numberOfRows / 2)) rowProp = lvlprop->getSeg3(); else if (n < (3 * numberOfRows / 4)) rowProp = lvlprop->getSeg2(); else if (n <= (numberOfRows)) rowProp = lvlprop->getSeg1(); rows->push_back(F->createRow(dir, n * rowHeight, rowHeight, n, rowProp)); propsOnRow->push_back(enemies); dir = dir == 'R' ? 'L' : 'R'; } } } void Level::propsGenerator(Factory* F, std::vector<Row*>* rows, std::vector<std::list<Props*>>* propsOnRow) { for (Row* row : *rows) { if ((row->getRowProperties()->getType() == 'B') || (row->getRowProperties()->getType() == 'C')) { std::list<Props*>* PreProp = &propsOnRow->at(row->getNumber()); if ((PreProp->empty()) || ((PreProp->front())->isRoom())) { Props* prop = obsOrLane(PreProp, row); propsOnRow->at(row->getNumber()).push_front(prop); } } } } int Level::collisionDetection(std::vector<std::list<Props*>>* propsOnRow, std::list<Player*>* players) { for (std::list<Props*> temp : *propsOnRow) { for (Props* temp2 : temp) { for (Player* player : *players) { temp2->collision(player); } } } for (Player* playerx : *players) for (Player* playery : *players) playerx->collision(playery); return false; } void Level::fillEnemyList(Factory* F, std::vector<Row*>* rows, std::vector<std::list<Props*>>* propsOnRow, int screenWidth) { for (Row* row : *rows) { fillOneRow(F, row, propsOnRow, screenWidth); } } void Level::drawGameElements(std::vector<std::list<Props*>>* propsOnRow, std::list<Player*>* players) { int i = 0; for (std::list<Props*> temp : *propsOnRow) { propsOnRow->at(i).remove_if(drawMoveRemove()); i++; } for (Player* player : *players) { player->draw(); } } Props* Level::obsOrLane(std::list<Props*>* PreProp, Row* row, bool frontOrBack, int x) { Props* prop; int number = rand() % 100; int laneRow = row->getRowProperties()->getType() == 'C'; if (frontOrBack) { bool prevVisible = PreProp->empty() ? true : PreProp->front()->isVisible(); if ((laneRow && prevVisible) || ((number < row->getRowProperties()->getObsticleRate()) && !prevVisible)) { Obstacle* obs=F->createObstacle1(); obs->setF(F); obs->setProjAniList(lvlprop->getProjAni()); obs->setAni(lvlprop->getObstiAni(row->getRandomObsInd()).clone()); obs->queryW(row->getHeight()); obs->setProperties(row, win->getWidth(), win->getGameWindowHeight(),x, obs->getW(), row->isObstacleVis()); prop=obs; } else { Lane* lane=F->createLane1(); lane->setF(F); lane->setItemAniList(lvlprop->getItemAni()); lane->setAni(lvlprop->getLaneAni((row->getRandomLaneInd())).clone()); lane->queryW(row->getHeight()); lane->setProperties(row, win->getWidth(), win->getGameWindowHeight(), x,lane->getW(), row->isLaneVis()); lane->spawnItem(); prop=lane; } } else { bool prevVisible = PreProp->empty() ? true : PreProp->back()->isVisible(); if ((laneRow && prevVisible)|| ((number < row->getRowProperties()->getObsticleRate()) && !prevVisible)) { Obstacle* obs=F->createObstacle1(); obs->setF(F); obs->setProjAniList(lvlprop->getProjAni()); obs->setAni(lvlprop->getObstiAni(row->getRandomObsInd()).clone()); obs->queryW(row->getHeight()); obs->setProperties(row, win->getWidth(), win->getGameWindowHeight(),x, obs->getW(), row->isObstacleVis()); prop=obs; } else { Lane* lane=F->createLane1(); lane->setF(F); lane->setItemAniList(lvlprop->getItemAni()); lane->setAni(lvlprop->getLaneAni((row->getRandomLaneInd())).clone()); lane->queryW(row->getHeight()); lane->setProperties(row, win->getWidth(), win->getGameWindowHeight(), x,lane->getW(), row->isLaneVis()); lane->spawnItem(); prop=lane; } } return prop; } bool Level::followFrog(std::vector<Row*>* rows, std::list<Player*>* players, int factor) { for (Row* row : *rows) { row->setLocY(*row->getLocY() + factor); } for (Player* player : *players) { player->followScreen(factor); } return true; } bool Level::isObjectiveDone() const { return objectiveDone; } bool Level::objectiveCompleteCheck(std::vector<std::list<Props*> >* propsOnRow) { bool ready = true; for (Props* prop : propsOnRow->at(0)) { if(prop->getX()<=(*win->getWidth()-prop->getW())) ready = prop->itemListEmpty() && ready ? true : false; } return ready; } void Level::resetLevel() { rows->clear(); propsOnRow->clear(); initLevel(); } void Level::initLevel() { rowGenerator(rowHeight, *win->getGameWindowHeight(), F, rows, propsOnRow, lvlprop); fillEnemyList(F, rows, propsOnRow, *win->getWidth()); } void Level::extraRowNeeded(int screenHeight, int screenWidth, Factory* F, std::vector<Row*>* rows, std::vector<std::list<Props*>>* propsOnRow, LevelProperties* lvlprop) { Row* lowestRow = rows->back(); Row* highestRow = rows->back(); for (Row* row : *rows) { if (*row->getLocY() < *lowestRow->getLocY()) { lowestRow = row; } else if (*row->getLocY() > *highestRow->getLocY()) { highestRow = row; } } if (*highestRow->getLocY() > screenHeight+highestRow->getHeight()) { highestRow->setLocY(*lowestRow->getLocY() - lowestRow->getHeight()); highestRow->setRowProperties(lvlprop->getRandomRow()); propsOnRow->at(highestRow->getNumber()).clear(); fillOneRow(F, highestRow, propsOnRow, screenWidth); } } Props* Level::obsOrLane(std::list<Props*>* PreProp, Row* row) { Props* prop; int number = rand() % 100; int laneRow = row->getRowProperties()->getType() == 'C'; bool prevVisible = PreProp->empty() ? true : PreProp->front()->isVisible(); if ((laneRow && prevVisible) || ((number < row->getRowProperties()->getObsticleRate()) && !prevVisible)) { Obstacle* obs=F->createObstacle1(); obs->setF(F); obs->setProjAniList(lvlprop->getProjAni()); obs->setAni(lvlprop->getObstiAni(row->getRandomObsInd()).clone()); obs->queryW(row->getHeight()); obs->setProperties(row, win->getWidth(), win->getGameWindowHeight(),row->isDirLeft() ? *win->getWidth() : -obs->getW(), obs->getW(), row->isObstacleVis()); prop=obs; } else { Lane* lane=F->createLane1(); lane->setF(F); lane->setItemAniList(lvlprop->getItemAni()); lane->setAni(lvlprop->getLaneAni((row->getRandomLaneInd())).clone()); lane->queryW(row->getHeight()); lane->setProperties(row, win->getWidth(), win->getGameWindowHeight(), row->isDirLeft() ? *win->getWidth() : -lane->getW(), lane->getW(), row->isLaneVis()); lane->spawnItem(); prop=lane; } return prop; } void Level::fillOneRow(Factory* F, Row* row, std::vector<std::list<Props*> >* propsOnRow, int screenWidth) { int x = 0; while (x < screenWidth) { if ((row->getRowProperties()->getType() == 'B') || (row->getRowProperties()->getType() == 'C') || row->getRowProperties()->getType() == 'D' || row->getRowProperties()->getType() == 'E') { std::list<Props*>* PreProp = &propsOnRow->at(row->getNumber()); Props* prop = obsOrLane(PreProp, row, row->isDirLeft(), x); if (row->isDirLeft()) propsOnRow->at(row->getNumber()).push_front(prop); else propsOnRow->at(row->getNumber()).push_back(prop); x = prop->getW() + x; } else { x = screenWidth; } } } bool frogger::Level::drawMoveRemove::operator ()(Props* prop) const { bool temp = false; if (!prop->inframe()) { temp = true; delete (prop); } else { prop->moveForward(); prop->draw(); } return temp; }
true
5a6f3e891c33ccf1e8e4f334e395244c0819ffd6
C++
abhinavkshitij/scicomp
/ch6/arrayAssign.cpp
UTF-8
488
3.703125
4
[]
no_license
// Exmaple from pg 164 class Array { public: Array(int n){}; // Single-argument constructor Array(const Array&){}; // Copy array Array& operator=(const Array&){return *this;}; // Assign array Array& operator=(const int){return *this;}; operator int() const {return 0;}; }; #include <iostream> using namespace std; int main(int argc, char const *argv[]) { Array a(5); a = 5; // ERROR: int 5 creates an Array object and assigns to Array a. cout << a << endl; return 0; }
true
6fda5a6cdf3e6ab288511af260b44c4c18c07e3a
C++
sxxlearn2rock/HODRep
/HOD/Processors/DenoiseStrategies/Localshannon.cpp
GB18030
2,261
2.75
3
[ "Apache-2.0" ]
permissive
#include "./Processors/DenoiseStrategies/Localshannon.h" #include "math.h" #include "string.h" //ྲ̬.cppļ Localshannon* Localshannon::mSingleton = NULL; void Localshannon::denoise(const Mat& srcImg, Mat& desImg) { unsigned char* cvtImg = mat2GrayImgPointer(srcImg, desImg); localshannon( cvtImg, desImg.rows, desImg.cols, mKsize); Mat outimage(desImg.rows, desImg.cols, CV_8UC1, cvtImg); desImg = outimage; } void Localshannon::localshannon(unsigned char *image, int height, int width, int LL) { int i, j, k, x, y; // ѭ int lLBytes = ((width * 8) + 31) / 32 * 4; float *OutImage = new float[lLBytes*height]; memset(OutImage, 0, sizeof(float)*lLBytes*height); int *histArray_1D = new int[256]; //1.ͼľֵ(Ϊֻھֵĵټ) float avg = 0; int S_LL = (2 * LL + 1)*(2 * LL + 1); float Shannnon; for (j = 0; j<height; j++) { for (i = 0; i<width; i++) avg += float(image[j*lLBytes + i]); } avg = avg / (width*height); for (j = LL; j<height - LL; j++) { for (i = LL; i<width - LL; i++) { k = j*lLBytes + i; if (image[k]>avg) //Сھֵĵ㲻 { memset(histArray_1D, 0, sizeof(int) * 256); //2.ֱֲͼ for (y = j - LL; y <= j + LL; y++) { for (x = i - LL; x <= i + LL; x++) { int index = image[y*lLBytes + x]; histArray_1D[index]++; } } //3.ֲShannon Shannnon = 0; for (int len = 0; len<256; len++) { float p = float(histArray_1D[len]) / float(S_LL); if (p<0.00000001) continue; Shannnon += -float(p*log10(p)); } OutImage[k] = Shannnon; } } } float maxT = 0; //ԽͼйһʾĶԱȶ for (y = 0; y<height; y++) { for (x = 0; x<width; x++) { if (OutImage[y*lLBytes + x]>maxT) maxT = OutImage[y*lLBytes + x]; // ͼֵ } } for (y = 0; y<height; y++) { for (x = 0; x<width; x++) { image[y*lLBytes + x] = (unsigned char)(OutImage[y*lLBytes + x] * 255 / maxT);//Բֵͼйһ } } delete[] OutImage; delete[] histArray_1D; // int a ; // int b ; // RegionGrow(image,width,height,a,b,4); }
true
658117782b30980b11192718d93eb0e756cac028
C++
chenhongbo-topscomm/gitlernen
/hallo.cpp
UTF-8
278
2.765625
3
[]
no_license
#include"iostream" using namespace std; int main() { cout<<"Hallo!"<<endl; int wuhu=0; cout<<"Ein Num giben Sie bitte!"<<endl; cin>>wuhu; if(wuhu>=10||wuhu<0) { cout<<"Du bist Scheisse!"<<endl; } else { cout<<"Fantastisch und Ausgezeichnet!"<<endl; } return 0; }
true
cc8dd2af2557bfb873eed89d31feea0ce75c81e7
C++
GoogleBing/Led_RGB
/Led_RGB.cpp
UTF-8
10,590
2.6875
3
[ "MIT" ]
permissive
#include "Led_RGB.h" //-------------------------------------------------------------------------------------------------------------------------------------- led_RGB::led_RGB(){} //-------------BEGIN SETUP-------------------------------------------------------------------------------------------------------------- void led_RGB::begin(uint8_t RED_PIN,uint8_t GREEN_PIN,uint8_t BLUE_PIN,bool type) { _bright=100; begin(RED_PIN,GREEN_PIN,BLUE_PIN,type,_bright); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::begin(uint8_t RED_PIN,uint8_t GREEN_PIN,uint8_t BLUE_PIN,bool type,uint8_t bright) { _redPin=RED_PIN; _greenPin=GREEN_PIN; _bluePin=BLUE_PIN; _bright=bright; pinMode(_redPin,OUTPUT); pinMode(_greenPin,OUTPUT); pinMode(_bluePin,OUTPUT); } //-------------EFFECT------------------------------------------------------------------------------------------------------------------ void led_RGB::turnoff() { digitalWrite(_redPin,LOW); digitalWrite(_greenPin,LOW); digitalWrite(_bluePin,LOW); } //-------------DISPLAY----------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t color[3]) { display(color,_bright); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t color[3],uint8_t bright) { if (type) for (byte i=0;i<=2;i++) color[i]=~(color[i]*bright/100); else for(byte i=0;i<=2;i++) color[i]=color[i]*bright/100; Serial.print(" Xuat ra : "); batbo(color); dem++; analogWrite(_redPin,color[0]); analogWrite(_greenPin,color[1]); analogWrite(_bluePin,color[2]); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t color[3],uint8_t bright,int time) { display(color,bright); delay(time); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE) { uint8_t color[3]; color[0]=_RED; color[1]=_GREEN; color[2]=_BLUE; display(color,_bright); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE,uint8_t bright) { uint8_t color[3]; color[0]=_RED; color[1]=_GREEN; color[2]=_BLUE; display(color,bright); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display(uint8_t _RED,uint8_t _GREEN,uint8_t _BLUE,uint8_t bright,int time) { uint8_t color[3]; color[0]=_RED; color[1]=_GREEN; color[2]=_BLUE; display(color,bright); delay(time); } //--------------CHANGE COLOR----------------------------------------------------------------------------------------------------------- void led_RGB::changeColor(uint8_t _from_color[3], uint8_t _to_color[3],uint8_t level,uint8_t bright,int time) { dem=0; byte i; for (i=0;i<=2;i++) { from_color[i]=_from_color[i]; to_color[i]=_to_color[i]; } step=level_exact[level]; group_start=classify_group(from_color); max1_start=max1; max2_start=max2; min_start=max3; group_stop=classify_group(to_color); max1_stop=max1; max2_stop=max2; min_stop=max3; //Chuyen gia tri ve gan step nhat for (i=0;i<=2;i++) { from_color[i]=round(float(from_color[i])/float(step))*step; to_color[i]=round(float(to_color[i])/float(step))*step; } Serial.println("Lam tron"); batbo(from_color); batbo(to_color); Serial.print("group_start="); Serial.println(group_start); Serial.print("group_stop="); Serial.println(group_stop); //----------------------------------------------------------------------------------------------------------------------------- delay_step=calc_time(time); // chuyen ve cac gia tri chia het cho step de code----------------------------------------------------------------------------- Serial.println("Giai doan chuyen thanh format"); //chuyen RGB Start thanh gia tri theo format (1 gia tri =225 va mot gia tri la 0) while ( (from_color[max1_start]<255)|(from_color[min_start]>0) ) { display(from_color,bright,delay_step); if (from_color[max1_start]<255) { from_color[max1_start]+=step; from_color[max2_start]+=step; } if (from_color[min_start]>0) from_color[min_start]-=step; } //Giai doan display_per_step------------------------------------------------------------------------------- repeat=false; Serial.println("Giai doan display per step"); display_per_step(bright); if (repeat==true) display_per_step(bright); //Giai doan cung nhom from_color[0]=red; from_color[1]=green; from_color[2]=blue; for (i=1;i<=b-1;i++) { display(from_color,bright,delay_step); if (group_stop%2==0) from_color[max2_start]-=step; else from_color[max2_start]+=step; } display(from_color,bright,delay_step); //Step change to stop--------------------------------------------------------------------------------------- Serial.println("Giai doan change to stop"); while ((from_color[0]!=to_color[0])||(from_color[1]!=to_color[1])||(from_color[2]!=to_color[2])) { if (from_color[0]>to_color[0]) from_color[0]-=step; else if (from_color[0]<to_color[0])from_color[0]+=step; if (from_color[1]>to_color[1]) from_color[1]-=step; else if (from_color[1]<to_color[1]) from_color[1]+=step; if (from_color[2]>to_color[2]) from_color[2]-=step; else if (from_color[2]< to_color[2]) from_color[2]+=step; display(from_color,bright,delay_step); } Serial.print("Dem la "); Serial.println(dem); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::display_per_step(uint8_t bright) { switch (group_start) { case 1: { red=255;green=from_color[max2_start];blue=0; if (group_stop==group_start) {max2_start=1;break;} else { group_start++; for (green;green<=(255-step);green+=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=255; } } case 2: { red=from_color[max2_start];green=255;blue=0; if (group_stop==group_start) {max2_start=0;break;} else { group_start++; for (red;red>=step;red-=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=0; } } case 3: { red=0;green=255;blue=from_color[max2_start]; if (group_stop==group_start) {max2_start=2;break;} else { ++group_start; for (blue;blue<=(255-step);blue+=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=255; } } case 4: { red=0;green=from_color[max2_start];blue=255; if (group_stop==group_start) {max2_start=1;break;} else { group_start++; for (green;green>=step;green-=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=0; } } case 5: { red=from_color[max2_start];green=0;blue=255; if (group_stop==group_start) {max2_start=0;break;} else { group_start++; for (red;red<=(255-step);red+=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=255; } } case 6: { red=255;blue=from_color[max2_start];green=0; if (group_stop==group_start) {max2_start=2;break;} else { group_start=1; for (blue;blue>=step;blue-=step) display(red,green,blue,bright,delay_step); from_color[max2_start]=0; repeat=true; } } } } //-------------------------------------------------------------------------------------------------------------------------------------- uint8_t led_RGB::classify_group(uint8_t array1[3]) { max1=0; max2=1; max3=2; //max 3 la Min cua mang if (array1[max1]<array1[max2]) {max1=1; max2=0;} if (array1[max1]<array1[2]) {max2=max1; max1=2;} else if (array1[max2]<array1[2]) max2=2; for (byte i=0;i<=2;i++) if ((max1!=i) && (max2!=i)) max3=i; byte a=max1*10+max2; switch (a) { case 01: { if ((array1[max1]-array1[max2])<=22){return(2);break;} else {return(1);break;} } case 10: {return(2);break;} case 12: { if ((array1[max1]-array1[max2])<=22){return(4);break;} else {return(3);break;} } case 21: {return(4);break;} case 20: {return(5);break;} case 02: {return(6);break;} } } //-------------------------------------------------------------------------------------------------------------------------------------- int led_RGB::calc_time(int time) { int step_get_format,step_changeto_stop,step_change_group; step_get_format=max(((255-from_color[max1_start])/step+1),(from_color[min_start]/step+1)); step_changeto_stop=max(((255-to_color[max1_stop])/step),(to_color[min_stop]/step))-1; if (group_start%2==1) a=(from_color[max1_start]-from_color[max2_start])/step; else a=(255-from_color[max1_start]+from_color[max2_start])/step; if (group_stop%2==1) b=(255-to_color[max1_stop]+to_color[max2_stop])/step+1; else b=(to_color[max1_stop]-to_color[max2_stop])/step+1; if (group_start<group_stop) step_change_group=(group_stop-group_start-1)*(255/step)+a+b; else if (group_start>group_stop) step_change_group=((5-group_start+group_stop)*(255/step))+a+b; else //(group_start==group_stop) { if ((a+b)>(255/step)) step_change_group=a+b-255/step ; else if((a+b)<(255/step)) step_change_group=255/step-a-b+2; else step_change_group=1; //from_color=to_color @@ } Serial.print("So buoc la: "); Serial.println(step_get_format+step_change_group+step_changeto_stop); return(time/(step_get_format+step_change_group+step_changeto_stop)); } //-------------------------------------------------------------------------------------------------------------------------------------- void led_RGB::batbo(uint8_t value[3]) { //Serial.print("Mang la "); for (uint8_t j=0; j<=2;j++) { Serial.print(value[j]); Serial.print(" "); } Serial.println(); // delay(2000); }
true
e3067d7066954f2c4bddb28618cb14a68f7f621d
C++
libcxxrt/libcxxrt
/test/test_demangle.cc
UTF-8
1,720
3.03125
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#include "test.h" #include <cxxabi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <typeinfo> void test(const char* mangled, const char* expected, int expstat, int line) { int status = 0; using abi::__cxa_demangle; char* demangled = __cxa_demangle(mangled, NULL, NULL, &status); printf("mangled='%s' demangled='%s', status=%d\n", mangled, demangled, status); if (expstat == 0) { TEST_LOC(status == 0, "should be able to demangle", __FILE__, line); } else { TEST_LOC(status == expstat, "should fail with expected status", __FILE__, line); } if (expected == NULL) { TEST_LOC(demangled == NULL, "should fail to demangle", __FILE__, line); } else { TEST_LOC(demangled != NULL, "should be able to demangle", __FILE__, line); TEST_LOC(strcmp(expected, demangled) == 0, "should be able to demangle", __FILE__, line); TEST_LOC(strcmp(mangled, demangled) != 0, "should be able to demangle", __FILE__, line); } free(demangled); } template <typename T> void test(const char* expected, int line) { test(typeid(T).name(), expected, 0, line); } namespace N { template<typename T, int U> class Templated { virtual ~Templated() {}; }; } void test_demangle(void) { using namespace N; // Positive tests (have to demangle successfully) test<int>("int", __LINE__); test<char[4]>("char [4]", __LINE__); test<char[]>("char []", __LINE__); test<Templated<Templated<long, 7>, 8> >( "N::Templated<N::Templated<long, 7>, 8>", __LINE__); test<Templated<void(long), -1> >( "N::Templated<void (long), -1>", __LINE__); // Negative tests (expected to fail with the indicated status) test("NSt3__15tupleIJibEEE", NULL, -2, __LINE__); }
true
4ed4579a35764d4271d51a25762ac0ff53de77c3
C++
isysoi3/Programming
/c++/1 сем/Stack/Stack/Stack.h
UTF-8
3,417
3.359375
3
[]
no_license
#pragma once #include <iostream> #include <list> using namespace std; template<typename T> class Stack { public: virtual ~Stack() {}; virtual void push(T smth) = 0 ; virtual void pop() = 0 ; virtual T top() const = 0 ; virtual int size() const = 0 ; virtual bool isEmpty() const = 0 ; }; template<typename T> class StackArray : public Stack<T> { private: T *stack; int t; int max_s; public: StackArray(int size); virtual ~StackArray(); virtual void push(T smth); virtual void pop(); virtual T top() const; virtual bool isEmpty() const; virtual int size() const; }; template<typename T> StackArray<T>::StackArray(int asize) { if (asize < 1) throw invalid_argument("size <= 0"); stack = new T[asize]; max_s = asize; t = -1; } template<typename T> StackArray<T>::~StackArray() { delete[]stack; } template <typename T> void StackArray<T>::push(T smth) { if (t == max_s - 1) throw exception("push is incorrect (stack is full)"); stack[++t] = smth; } template <typename T> void StackArray<T>::pop() { if (isEmpty()) throw exception("pop is incorrect (stack is empty)"); t--; } template <typename T> T StackArray<T>::top() const { if (isEmpty()) throw exception("top is incorrect (stack is empty)"); return stack[t]; } template <typename T> bool StackArray<T>::isEmpty() const { return t == -1; } template <typename T> int StackArray<T>::size() const { return t + 1; } template<typename T> class StackList : public Stack<T> { private: list<T> List; public: StackList(); virtual ~StackList(); virtual void push(T smth); virtual T top() const; virtual void pop(); virtual bool isEmpty() const; virtual int size() const; }; template<typename T> StackList<T>::StackList() { } template<typename T> StackList<T>::~StackList() { } template<typename T> void StackList<T>::push(T smth) { List.push_back(smth); } template<typename T> T StackList<T>::top() const { if (isEmpty()) throw exception("top is incorrect (stack is empty)"); return List.back(); } template<typename T> void StackList<T>::pop() { if (isEmpty()) throw exception("pop is incorrect (stack is empty)"); List.pop_back(); } template<typename T> bool StackList<T>::isEmpty() const { return List.empty(); } template<typename T> int StackList<T>::size() const { return List.size(); } /*template<typename T> class StackList : public Stack<T> { private: int _size; struct list { list *next; T element; }; list *t; public: StackList(); virtual ~StackList(); virtual void push(T smth); virtual T top() const; virtual void pop(); virtual bool isEmpty() const; virtual int size() const; }; template<typename T> StackList<T>::StackList() { t = nullptr; _size = 0; } template<typename T> StackList<T>::~StackList() { while (t != nullptr) { list *pos = t; t = t->next; delete pos; } delete t; } template<typename T> void StackList<T>::push(T smth) { list *pos = new list; pos->element = smth; pos->next = t; t = pos; _size++; } template<typename T> T StackList<T>::top() const{ if (isEmpty()) throw exception("top is incorrect (stack is empty)"); return t->element; } template<typename T> void StackList<T>::pop() { if (isEmpty()) throw exception("pop is incorrect (stack is empty)"); list* pos = t; t = t->next; delete pos; _size--; } template<typename T> bool StackList<T>::isEmpty() const { return t == nullptr; } template<typename T> int StackList<T>::size() const { return _size; }*/
true
88eb67635d70320fd33b8e125aa6fa5e05b9aabe
C++
gtu-homeworks-and-projects/CSE-241-Object-Oriented-Programming-2017-Fall
/HW6/GTUMap.cpp
UTF-8
615
2.640625
3
[]
no_license
// // Created by cecen on 12/13/2017. // #include "GTUMap.h" #include "GTUSet.cpp" namespace containers{ template<class K, class V> GTUMap<K, V>::GTUMap(): GTUSet<std::pair<K,V> >::GTUSet () {} template<class K, class V> V &GTUMap<K, V>::operator[](const K& k) { shared_ptr<DataNode> currentData = this->testDataHead; for(;currentData->data->first != k && currentData->next != nullptr; currentData = currentData->next); return currentData->data->second; // Returns matching k's value, if its not present returns last element } }
true
5f4cad0cf07107afb5d762253555eddbc75e6731
C++
virovets64/Hadronium
/Engine/Vector.h
UTF-8
1,452
3.609375
4
[]
no_license
#pragma once #include <array> template<typename Number, int Dim> struct Vector { std::array<Number, Dim> Data; Vector() : Data{} {} Number LengthSquared() { Number result{}; for (auto d : Data) result += d * d; return result; } Number Length() { return sqrt(LengthSquared()); } inline Vector<Number, Dim> operator += (const Vector<Number, Dim>& other) { for (int i = 0; i < Dim; i++) Data[i] += other.Data[i]; return *this; } inline Vector<Number, Dim> operator -= (const Vector<Number, Dim>& other) { for (int i = 0; i < Dim; i++) Data[i] -= other.Data[i]; return *this; } inline Vector<Number, Dim> operator *= (Number k) { for (int i = 0; i < Dim; i++) Data[i] *= k; return *this; } }; template<typename Number, int Dim> inline Vector<Number, Dim> operator + (const Vector<Number, Dim>& a, const Vector<Number, Dim>& b) { auto tmp(a); return tmp += b; } template<typename Number, int Dim> inline Vector<Number, Dim> operator - (const Vector<Number, Dim>& a, const Vector<Number, Dim>& b) { auto tmp(a); return tmp -= b; } template<typename Number, int Dim> inline Vector<Number, Dim> operator * (const Vector<Number, Dim>& a, Number k) { auto tmp(a); return tmp *= k; } template<typename Number, int Dim> inline Vector<Number, Dim> operator * (Number k, const Vector<Number, Dim>& a) { auto tmp(a); return tmp *= k; }
true
4358588047d6d605a7b0d9a2806a1efb1f4daa51
C++
wangwshuai/t2h
/src/common/utility/thread_pool.hpp
UTF-8
3,373
3.078125
3
[]
no_license
#ifndef THREAD_POOL_HPP_INCLUDED #define THREAD_POOL_HPP_INCLUDED #include <vector> #include <boost/thread.hpp> #include <boost/noncopyable.hpp> #include <iostream> namespace utility { namespace details { class default_policy { public : typedef std::size_t size_type; default_policy() : lock_(), threads_(), thread_holder_() { } explicit default_policy(size_type max_threads) : lock_(), threads_(), thread_holder_() { thread_holder_.resize(max_threads); } ~default_policy() { } template <class Func> inline void add_task(size_type id, Func func) { boost::lock_guard<boost::mutex> guard(lock_); if (id < thread_holder_.size()) { if (thread_holder_.at(id) == NULL) { boost::thread * new_thread = threads_.create_thread(func); thread_holder_.at(id) = new_thread; } // !if } // !if } inline void join_task_and_remove(size_type id) { boost::lock_guard<boost::mutex> guard(lock_); boost::thread * thread_ptr = NULL; if (id < thread_holder_.size()) { if ((thread_ptr = thread_holder_.at(id)) != NULL) { thread_holder_.at(id) = NULL; thread_ptr->join(); threads_.remove_thread(thread_ptr); } // !if } // !if } inline void stop_all_tasks() { boost::lock_guard<boost::mutex> guard(lock_); threads_.interrupt_all(); clear_task_holder(); } inline void wait_all_tasks() { boost::lock_guard<boost::mutex> guard(lock_); threads_.join_all(); clear_task_holder(); } bool has_unfinished_task() const { boost::lock_guard<boost::mutex> guard(lock_); bool state = false; std::vector<boost::thread *>::const_iterator it = thread_holder_.begin(), end = thread_holder_.end(); for (; it != end; ++it) { if (*it != NULL) state = (*it)->joinable(); } return state; } inline void resize_max_threads(size_type max_threads) { boost::lock_guard<boost::mutex> guard(lock_); std::vector<boost::thread *> old_holder = thread_holder_; clear_task_holder(); thread_holder_.resize(max_threads); thread_holder_.swap(old_holder); } private : inline void clear_task_holder() { size_type const holder_size = thread_holder_.size(); thread_holder_.clear(); thread_holder_.resize(holder_size); } boost::mutex mutable lock_; boost::thread_group threads_; std::vector<boost::thread *> thread_holder_; }; } // namespace details template <class Policy = details::default_policy> class base_thread_pool : private boost::noncopyable { public : typedef Policy policy_type; typedef typename Policy::size_type size_type; base_thread_pool() : impl_policy_() { } explicit base_thread_pool(size_type max_threads) : impl_policy_(max_threads) { } ~base_thread_pool() { wait_all_tasks(); } template <class Func> inline void add_task(size_type id, Func func) { impl_policy_.add_task<Func>(id, func); } inline void join_task_and_remove(size_type id) { impl_policy_.remove_task_and_join(id); } inline void stop_all_tasks() { impl_policy_.stop_all_tasks(); } inline void wait_all_tasks() { impl_policy_.wait_all_tasks(); } inline bool has_unfinished_task() const { return impl_policy_.has_unfinished_task(); } inline void resize_max_threads(size_type max_threads) { impl_policy_.resize_max_threads(max_threads); } private : policy_type impl_policy_; }; } // namespace utility #endif
true
f11fb6ee39ea34f14d0c5b8a14e15df9379bdf09
C++
merelmourik/Webserver
/srcs/Cluster/serverCluster.hpp
UTF-8
776
2.515625
3
[ "MIT" ]
permissive
#ifndef SERVERCLUSTER_HPP # define SERVERCLUSTER_HPP # include "../Server/server.hpp" # include "../Utils/defines.hpp" # include "../webserv.hpp" # include <algorithm> class serverCluster { public: fd_set readFds; fd_set writeFds; private: std::vector<server*> _servers; int _nrOfServers; long _highestFd; public: typedef void (server::*setter)(std::string&); class duplicatePortException : public std::exception { public: virtual const char* what() const throw(); }; serverCluster(); serverCluster(const serverCluster &original); ~serverCluster(); serverCluster& operator=(const serverCluster &original); void addServer(server *newServ); bool isEmpty() const; void duplicatePorts() const; void startup(); void startListening(); }; #endif
true
c0a67692ae91c260daa474fbc9ba8ebdef08d01c
C++
ucas-joy/my_leetcode
/315Count of Smaller Numbers After Self.cpp
WINDOWS-1252
2,058
3.6875
4
[]
no_license
/* You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. Example: Given nums = [5, 2, 6, 1] To the right of 5 there are 2 smaller elements (2 and 1). To the right of 2 there is only 1 smaller element (1). To the right of 6 there is 1 smaller element (1). To the right of 1 there is 0 smaller element. Return the array [2, 1, 1, 0]. Subscribe to see which companies asked this question Show Tags Show Similar Problems */ // #include<iostream> #include<vector> using namespace std; class Solution { public: struct TreeNode { int val; int count; TreeNode *left; TreeNode *right; TreeNode(int v,int c = 0, TreeNode*l =NULL,TreeNode*r = NULL) : val(v),count(c), left(l), right(r) {} }; void insert(TreeNode *&root, int num, int &ret){ if (root == NULL){ root = new TreeNode(num); return; } if (num > root->val){ ret += root->count + 1; insert(root->right, num, ret); } else{ root->count++; insert(root->left, num, ret); } } vector<int> countSmaller(vector<int>& nums) { vector<int> res; int n = nums.size(); if (n == 0) return res; res.resize(n, 0); TreeNode *root = new TreeNode(nums[n-1]); for (int i = n-2; i >=0; --i) { insert(root, nums[i], res[i]); } return res; } }; int main() { vector<int>a = { 5,2,6,1 }; Solution sol; vector<int> b = sol.countSmaller(a); for (int i = 0; i < b.size(); ++i) { cout << b[i] << " "; } cout << endl; return 0; } /* vector<int> countSmaller(vector<int>& nums) { vector<int> s; vector<int> ans; for (int i = nums.size() - 1; i >= 0; i--) { if (s.empty()) { s.push_back(nums[i]); ans.push_back(0); continue; } int l = 0, r = s.size() - 1; while (l <= r) { int mid = (l + r) / 2; if (s[mid] < nums[i]) { l = mid + 1; } else r = mid - 1; } s.insert(s.begin() + l, nums[i]); ans.push_back(l); } reverse(ans.begin(), ans.end()); return ans; } */
true
e4b179614257075ce71a6e3d89c4691b17e4277f
C++
mohammadVatandoost/SplayTree
/splaytree.cpp
UTF-8
819
3.171875
3
[]
no_license
#include "splaytree.h" SplayTree::SplayTree(int value) { // root = {value, null, nullptr, nullptr}; // has problem root = new node(); root->value = value; } node *SplayTree::findNearest(node *headNode, int value) { if(headNode->value == value) { return headNode; } else if(headNode->right == nullptr && headNode->left == nullptr) { if(abs(value-headNode->parent->value) > abs(value - headNode->value)) { return headNode; } else { return headNode->parent; } } else if(value > headNode->value && headNode->right != nullptr) { findNearest(headNode->right, value); } else if(value < headNode->value && headNode->left != nullptr) { findNearest(headNode->left, value); } else { // return headNode; } }
true
df6311bee35b8ea834ca1dc91ec8d708c8d8de56
C++
zhuhuijia0001/leetcode
/219-Contains Duplicate II.cpp
UTF-8
835
2.984375
3
[]
no_license
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { int i; map<int, int> mymap; map<int, int>::iterator mapitr; for (vector<int>::iterator itr = nums.begin(); itr != nums.end(); ++itr) { mapitr = mymap.find(*itr); if (mapitr != mymap.end()) { //find if (itr - nums.begin() - mapitr->second <= k) { return true; } else { mapitr->second = itr - nums.begin(); } } else { mymap.insert(pair<int, int>(*itr, itr - nums.begin())); } } return false; } };
true
1689acf37e4884de5e41198cdd823c80e3594bb1
C++
vandersonmr/ProgrammingContest
/URI/1521.cpp
UTF-8
499
2.765625
3
[]
no_license
#include <cstdio> int main() { while(true){ int n; scanf("%d\n", &n); if (n == 0) return 0; int alunos[n]; char rest[10000]; scanf("%[^\n]", rest); for(int i=0; i < n; i++) { int who; sscanf(rest, "%d %[^\n]", &who, rest); alunos[i] = who; } int start; scanf("%d", &start); int i = start-1; int next = alunos[i]-1; while(next != i) { i = next; next = alunos[i]-1; } printf("%d\n", i+1); } return 0; }
true
1558f7639b79bcceaecde5d81e02a93d40d3afb8
C++
Vitor-Mendes/TP2_Solar_System_CG
/src/Camera.cpp
UTF-8
1,207
2.8125
3
[]
no_license
#include <GL/glu.h> #include "Camera.h" void Camera::use() { gluLookAt(position[Vector3d::X], position[Vector3d::Y], position[Vector3d::Z], target[Vector3d::X], target[Vector3d::Y], target[Vector3d::Z], up[Vector3d::X], up[Vector3d::Y], up[Vector3d::Z]); } void Camera::use(double aspectRatio) { gluLookAt(position[Vector3d::X], position[Vector3d::Y]*aspectRatio, position[Vector3d::Z], target[Vector3d::X], target[Vector3d::Y], target[Vector3d::Z], up[Vector3d::X], up[Vector3d::Y], up[Vector3d::Z]); } const Vector3d &Camera::getPosition() const { return position; } void Camera::setPosition(const Vector3d &position) { Camera::position = position; } void Camera::addToPosition(const Vector3d &position) { Camera::position += position; } const Vector3d &Camera::getTarget() const { return target; } void Camera::setTarget(const Vector3d &target) { Camera::target = target; } void Camera::addToTarget(const Vector3d &target) { Camera::target += target; } const Vector3d &Camera::getUp() const { return up; } void Camera::setUp(const Vector3d &up) { Camera::up = up; }
true
69ce51febb04fc61caf4a4fcfa30f0b032128d17
C++
supercaracal/game-programmer-book-build
/src/08_2DCollision/Reaction2/main.cpp
SHIFT_JIS
2,576
2.671875
3
[]
no_license
#include "GameLib/Framework.h" class Square{ public: void set( int x, int y, int halfSize ){ mX = x; mY = y; mHalfSize = halfSize; } bool isIntersect( const Square& b ) const { int al = mX - mHalfSize; //left A int ar = mX + mHalfSize; //right A int bl = b.mX - b.mHalfSize; //left B int br = b.mX + b.mHalfSize; //right B if ( ( al < br ) && ( ar > bl ) ){ int at = mY - mHalfSize; //top A int ab = mY + mHalfSize; //bottom A int bt = b.mY - b.mHalfSize; //top B int bb = b.mY + b.mHalfSize; //bottom B if ( ( at < bb ) && ( ab > bt ) ){ return true; } } return false; } int mX; int mY; int mHalfSize; }; bool gFirstFrame = true; Square gPlayer; //L̂‚ Square gWall; // namespace GameLib{ void Framework::update(){ if ( gFirstFrame ){ setFrameRate( 60 ); gFirstFrame = false; gPlayer.set( 16, 16, 16 ); gWall.set( 160, 120, 16 ); } //ړʃQbg int dx = 0; int dy = 0; if ( isKeyOn( 'a' ) ){ dx = -7; }else if ( isKeyOn( 's' ) ){ dx = 7; } if ( isKeyOn( 'w' ) ){ dy = -7; }else if ( isKeyOn( 'z' ) ){ dy = 7; } unsigned* vram = videoMemory(); //Փˏ(ő4) unsigned color = 0xffff0000; int numerator = 1; //q int denominator = 1; // int testDx = dx; //ꂩ玎dx,dy int testDy = dy; int lastDx = 0; //vődx,dy int lastDy = 0; for ( int i = 0; i < 4; ++i ){ Square tSquare; //e| tSquare.set( gPlayer.mX + testDx, gPlayer.mY + testDy, gPlayer.mHalfSize ); numerator *= 2; denominator *= 2; if ( tSquare.isIntersect( gWall ) ){ color = 0xffffffff; numerator -= 1; }else{ numerator += 1; lastDx = testDx; //XV lastDy = testDy; } testDx = dx * numerator / denominator; testDy = dy * numerator / denominator; } //ړ gPlayer.mX += lastDx; gPlayer.mY += lastDy; //` //UNA for ( int i = 0; i < width() * height(); ++i ){ vram[ i ] = 0; } //Ȃق` for ( int y = 0; y < 32; ++y ){ for ( int x = 0; x < 32; ++x ){ int tx = x + gWall.mX - 16; int ty = y + gWall.mY - 16; vram[ ty * width() + tx ] = 0xff0000ff; } } //ق` for ( int y = 0; y < 32; ++y ){ for ( int x = 0; x < 32; ++x ){ int tx = x + gPlayer.mX - 16; int ty = y + gPlayer.mY - 16; vram[ ty * width() + tx ] = color; } } } }
true
809b9eb39dadc7789313666a9d17ae861c8c8a73
C++
luismgg86/Lista
/src/Lista.cpp
UTF-8
2,843
3.609375
4
[]
no_license
#include "Lista.h" using namespace std; Lista::Lista(){//contructor vacio this->H=NULL; this->T=NULL; } Lista::Lista(int dato){//constructor con un dato Nodo *m=new Nodo(dato); this->H=m; this->T=H; } bool Lista::IsVacio(){ //metodo que verifica si la lista esta vacia return(this->T==NULL && this->H==NULL); } void Lista::insertarP(int dato){ //metodo para insertar nodo al principio Nodo *m=new Nodo(dato,this->H); if (IsVacio()) { this->T=m; } this->H=m; } void Lista::insertarF(int dato){ //metodo para insertar nodo al final Nodo *m=new Nodo(dato); if(IsVacio()){ this->T=m; this->H=m; return; } this->T->sig=m->sig; this->T=m; } void Lista::insertarRef(int dato,int ref){ //metodo para insertar nodo por referencia if(IsVacio()){ cout<<"Error la lista esta vacia"<<endl; return; } Nodo *m=buscar(ref); if (m==NULL) { cout<<"Error la referencia no esta en la lista"<<endl; return; } if(m->sig==NULL){ insertarF(dato); return; } Nodo *n=new Nodo(dato,m->sig); m->sig=n->sig; return; } Nodo* Lista::buscar(int ref){ //metodo para buscar nodo Nodo *aux=this->H; if(IsVacio()){ cout<<"error la lista esta vacia"<<endl; return NULL; } while(aux->dato!=ref) if(aux->sig==NULL){ cout<<"la referencia no esta en la lista"<<endl; } aux=aux->sig; return aux; } Nodo* Lista::buscar(int ref,Nodo *n){ //metodo para buscar nodo, a este se le pasa un nodo if(IsVacio()){ cout<<"error la lista esta vacia"<<endl; return NULL; } if(n->dato!=ref){ if(n->sig==NULL){ cout<<"error la referencia no esta en la lista"<<endl; return NULL; } return buscar(ref,n->sig); } return n; } int Lista::borrarP(){ //funcion para borrar al principio int d=this->H->dato; if(IsVacio()){ cout<<"error la lista esta vacia"<<endl; return d; } Nodo *aux=this->H; this->H=this->H->sig; if (this->H==NULL) this->T=NULL; aux->sig=NULL; return d; } int Lista::borrarF(){ //metodo para borrar al final int d=this->H->dato; if(IsVacio()){ cout<<"error la lista esta vacia"<<endl; return d; } Nodo *aux=this->H; if (this->H == this->T) { this->H=NULL; this->T=NULL; return d; } while(aux->sig!=this->T) aux=aux->sig; this->T=aux; this->T->sig=NULL; return d; } int Lista::borrarRef(int ref){ //metodo para borrar por referencia if(IsVacio()){ cout<<"error la lista esta vacia"<<endl; return ref; } Nodo *r=buscar(ref); if(r==NULL){ cout<<"error la referencia no esta en la lista"<<endl; return ref; } if (this->H == this->T){ this->H = NULL; this->T = NULL; return ref; } Nodo *ant=this->H; while(ant->sig!=r) ant=ant->sig; ant->sig=r->sig; r->sig=NULL; return ref; }
true
c65c050090effc6c760b15ba02780a8f9530f357
C++
THLEE-KR/Baekjoon-Online-Judge_THLEE
/20200830_13023/main.cpp
UTF-8
1,203
2.9375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; bool a[2010][2010]; // 인접 행렬 vector<int> g[2000]; // 인접 리스트 vector<pair<int,int>> edges; // 간선 리스트 int main() { int N, M; cin >> N >> M; // 5 4 for(int i=0; i<M; i++){ int from, to; cin >> from >> to; edges.push_back({from, to}); edges.push_back({to, from}); a[from][to] = a[to][from] = true; g[from].push_back(to); g[to].push_back(from); } M *= 2; for(int i=0; i<M; i++){ for(int j=0; j<M; j++){ // A -> B int A = edges[i].first; int B = edges[i].second; // C -> D int C = edges[j].first; int D = edges[j].second; if(A == B || A == C || A == D || B == C || B == D || C == D) continue; // B -> C if(!a[B][C]) continue; // D -> E for(int E : g[D]){ if(A == E || B == E || C == E || D == E) continue; cout << 1 << '\n'; return 0; } } } cout << 0 << '\n'; return 0; }
true
7a1dd26d71a385df1c382805eb7992342e6e6eb2
C++
cugbacmbsworks/ALGORITHMS
/第7章/7.1-4.cpp
UTF-8
608
3.46875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int PARTITION(int* arr,int l,int r) { int t = l; for(int i = l;i < r;++i) if(arr[i] > arr[r]) swap(arr[i],arr[t++]);//用了stl的swap()函数 swap(arr[t],arr[r]); return t; } void QUICK_SORT(int* arr,int l,int r) { if(l < r) { int nextpos = PARTITION(arr,l,r); QUICK_SORT(arr,l,nextpos - 1); QUICK_SORT(arr,nextpos + 1,r); } } //测试数据 int main() { int arr[10] = {1,4,3,9,1,1,4,1,2,1}; QUICK_SORT(arr,0,9); for(int i = 0;i < 10;++i) cout << arr[i]; return 0; }
true
1ce458cbf5a11fd050ff1f2fac15e042e7e987bf
C++
hunkabhicupid/General
/rowmajor/main.cpp
UTF-8
201
3.125
3
[]
no_license
#include <stdio.h> int main () { unsigned int M,N; // construct a 2D array say M*N cin >> M >> N; int * arr = new int[M*N]; // input as row major return 0; }
true
b56bd446a99ab4c79820299df0074f7d18d8a23d
C++
qeedquan/challenges
/codingtrain/4-purple-rain.cpp
UTF-8
3,327
2.953125
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstdarg> #include <cstdint> #include <chrono> #include <random> #include <vector> #include <SDL.h> using namespace std; struct Drop { float x, y, z; float yspeed; float len; void init(float width); void fall(float height); void draw(SDL_Renderer *renderer); }; struct App { SDL_Window *window; SDL_Renderer *renderer; int width; int height; uint32_t start; bool pause; vector<Drop> drops; void init(); void reset(); void event(); void update(); void draw(); }; [[noreturn]] void fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); exit(1); } float unlerp(float t, float a, float b) { return (t - a) / (b - a); } float linear_remap(float x, float a, float b, float c, float d) { return lerp(c, d, unlerp(x, a, b)); } float randn(float a, float b) { default_random_engine engine; engine.seed(chrono::system_clock::now().time_since_epoch().count()); uniform_real_distribution<float> distribution(a, b); return distribution(engine); } void Drop::init(float width) { x = randn(0, width); y = randn(-500, -50); z = randn(0, 20); yspeed = linear_remap(z, 0, 20, 5, 20); len = linear_remap(z, 0, 20, 10, 50); } void Drop::fall(float height) { auto gravity = linear_remap(z, 0, 20, 0, 0.2); y += yspeed; yspeed += gravity; if (y > height) { y = randn(-200, -100); yspeed = linear_remap(z, 0, 20, 4, 10); } } void Drop::draw(SDL_Renderer *renderer) { auto thick = linear_remap(z, 0, 20, 1, 3); SDL_SetRenderDrawColor(renderer, 138, 43, 226, 255); SDL_RenderSetScale(renderer, thick * 4, 1); SDL_RenderDrawLineF(renderer, x, y, x, y + len); } void App::init() { if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) < 0) fatal("Failed to init SDL: %s", SDL_GetError()); width = 800; height = 600; auto wflag = SDL_WINDOW_RESIZABLE; if (SDL_CreateWindowAndRenderer(width, height, wflag, &window, &renderer) < 0) fatal("Failed to create a window: %s", SDL_GetError()); SDL_SetWindowTitle(window, "Purple Rain"); SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND); } void App::reset() { drops.resize(width * 2); for (auto &drop : drops) drop.init(width); start = SDL_GetTicks(); } void App::event() { SDL_Event ev; while (SDL_PollEvent(&ev)) { switch (ev.type) { case SDL_QUIT: exit(0); case SDL_KEYDOWN: switch (ev.key.keysym.sym) { case SDLK_ESCAPE: exit(0); case SDLK_SPACE: reset(); break; case SDLK_RETURN: pause = !pause; break; } break; case SDL_WINDOWEVENT: switch (ev.window.event) { case SDL_WINDOWEVENT_RESIZED: case SDL_WINDOWEVENT_SIZE_CHANGED: width = ev.window.data1; height = ev.window.data2; break; } break; } } } void App::update() { auto now = SDL_GetTicks(); if (now - start < 16) return; if (!pause) { for (auto &drop : drops) drop.fall(height); } start = now; } void App::draw() { SDL_SetRenderDrawColor(renderer, 230, 230, 250, 255); SDL_RenderClear(renderer); for (auto &drop : drops) drop.draw(renderer); SDL_RenderPresent(renderer); } int main() { auto app = new App(); app->init(); app->reset(); for (;;) { app->event(); app->update(); app->draw(); } return 0; }
true
348d8082a9f38433dcf9314b54cb53d832796891
C++
frankylin1111/1081ML
/Cpp_ex/C_ex/ch11/ch11 hw07.cpp
BIG5
299
2.859375
3
[]
no_license
#include <stdio.h> #include <cstdlib> #include <cstring> /* 2018/07/01 ߱o ch11 }C ------------------ HW 7 ϥΦr}CCXr */ int main() { int i=10,j,sum; int a[i]={'C',' ','L','a','n','g','u','a','g','e'}; for (int j=0;j<10;j++) { printf("%c",a[j]); } }
true
7035a27711b675b8084c72268dff306a0a6c5019
C++
n-jing/njinglib
/src/rational_number.cpp
UTF-8
4,106
2.796875
3
[]
no_license
#include "rational_number.h" #ifdef RN RationalNumber::RationalNumber(const RationalNumber &a) { mpq_init(p); mpq_set(p, a.p); } RationalNumber::RationalNumber(double a) { mpq_init(p); mpq_set_d(p, a); } RationalNumber::RationalNumber(int a) { mpq_init(p); mpq_set_d(p, double(a)); } RationalNumber::RationalNumber(mpq_t a) { mpq_init(p); mpq_set(p, a); } RationalNumber::RationalNumber() { mpq_init(p); } RationalNumber::~RationalNumber() { mpq_clear(p); } RationalNumber RationalNumber::operator+(const RationalNumber &a) const { mpq_t re; mpq_init(re); mpq_add(re, p, a.p); RationalNumber rt(re); mpq_clear(re); return rt; } RationalNumber RationalNumber::operator-(const RationalNumber &a) const { mpq_t re; mpq_init(re); mpq_sub(re, p, a.p); RationalNumber rt(re); mpq_clear(re); return rt; } RationalNumber RationalNumber::operator*(const RationalNumber &a) const { mpq_t re; mpq_init(re); mpq_mul(re, p, a.p); RationalNumber rt(re); mpq_clear(re); return rt; } RationalNumber RationalNumber::operator/(const RationalNumber &a) const { mpq_t re; mpq_init(re); mpq_div(re, p, a.p); RationalNumber rt(re); mpq_clear(re); return rt; } void RationalNumber::operator=(const RationalNumber &a) { mpq_set(p, a.p); } bool RationalNumber::operator==(const RationalNumber &a) const { return mpq_equal(p, a.p); } bool RationalNumber::operator!=(const RationalNumber &a) const { return !bool(mpq_equal(p, a.p)); } double RationalNumber::get_value() const { return mpq_get_d(p); } bool RationalNumber::operator<(const RationalNumber &a) const { int cmp = mpq_cmp(p, a.p); return (cmp < 0); } bool RationalNumber::operator>(const RationalNumber &a) const { int cmp = mpq_cmp(p, a.p); return (cmp > 0); } bool RationalNumber::operator<=(const RationalNumber &a) const { int cmp = mpq_cmp(p, a.p); return (cmp <= 0); } bool RationalNumber::operator>=(const RationalNumber &a) const { int cmp = mpq_cmp(p, a.p); return (cmp >= 0); } #else RationalNumber::RationalNumber(const RationalNumber &a) { mpf_init2(p, 256); mpf_set(p, a.p); } RationalNumber::RationalNumber(double a) { mpf_init2(p, 256); mpf_set_d(p, a); } RationalNumber::RationalNumber(int a) { mpf_init(p); mpf_set_d(p, double(a)); } RationalNumber::RationalNumber(mpf_t a) { mpf_init2(p, 256); mpf_set(p, a); } RationalNumber::RationalNumber() { mpf_init2(p, 256); } RationalNumber::~RationalNumber() { mpf_clear(p); } RationalNumber RationalNumber::operator+(const RationalNumber &a) const { mpf_t re; mpf_init2(re, 256); mpf_add(re, p, a.p); RationalNumber rt(re); mpf_clear(re); return rt; } RationalNumber RationalNumber::operator-(const RationalNumber &a) const { mpf_t re; mpf_init2(re, 256); mpf_sub(re, p, a.p); RationalNumber rt(re); mpf_clear(re); return rt; } RationalNumber RationalNumber::operator*(const RationalNumber &a) const { mpf_t re; mpf_init2(re, 256); mpf_mul(re, p, a.p); RationalNumber rt(re); mpf_clear(re); return rt; } RationalNumber RationalNumber::operator/(const RationalNumber &a) const { mpf_t re; mpf_init2(re, 256); mpf_div(re, p, a.p); RationalNumber rt(re); mpf_clear(re); return rt; } void RationalNumber::operator=(const RationalNumber &a) { mpf_set(p, a.p); } bool RationalNumber::operator==(const RationalNumber &a) const { return mpf_equal(p, a.p); } bool RationalNumber::operator!=(const RationalNumber &a) const { return !bool(mpf_equal(p, a.p)); } double RationalNumber::get_value() const { return mpf_get_d(p); } bool RationalNumber::operator<(const RationalNumber &a) const { int cmp = mpf_cmp(p, a.p); return (cmp < 0); } bool RationalNumber::operator>(const RationalNumber &a) const { int cmp = mpf_cmp(p, a.p); return (cmp > 0); } bool RationalNumber::operator<=(const RationalNumber &a) const { int cmp = mpf_cmp(p, a.p); return (cmp <= 0); } bool RationalNumber::operator>=(const RationalNumber &a) const { int cmp = mpf_cmp(p, a.p); return (cmp >= 0); } #endif
true
08d726e04c78e93c51815c232e723d9d8f06b0b4
C++
waynezhangw/some-sorting-algorithms
/daily_sorting/wayne_sortThem.cpp
ISO-8859-9
5,737
3.390625
3
[]
no_license
#include "wayne_sortThem.h" #include <utility> // std::swap #include<iostream> #include <algorithm> using namespace std; wayne_sortThem::wayne_sortThem(void) { } wayne_sortThem::~wayne_sortThem(void) { } bool wayne_sortThem::ascending(double& x, double& y) { return x < y; } bool wayne_sortThem::descending(double& x, double& y) { return x > y; } void wayne_sortThem::selectionSort(vector<double> &vec1,const vector<double> &vec2) { cout << "selectionSort:" << endl; vec1=vec2; int times=10000; int temp_i; for(unsigned int i=0;i<vec2.size()-1;i++) { //only use to n-1 temp_i=i; for(unsigned int j=i+1;j<vec2.size();j++) { if(vec1[j]<vec1[temp_i]) { //non descending order temp_i=j; } } if(temp_i!=i) { swap(vec1[i], vec1[temp_i]); //non stable(5,8,5,2,9; 5 and 2 will swap, so the original two "5" will change) } if(i==times) { cout<<i<<endl; times=times+10000; } } } void wayne_sortThem::bubbleSort(vector<double> &vec1,const vector<double> &vec2) { cout << "bubbleSort:" << endl; vec1=vec2; int times=10000; bool flag=true; for(unsigned int i=0;i<vec2.size()-1;i++) { flag=false; for(unsigned int j=0;j<vec2.size()-i-1;j++) { if(vec1[j]>vec1[j+1]) { swap(vec1[j], vec1[j+1]); // stable sort, relative order will not change flag=true; } } if(i==times) { cout<<i<<endl; times=times+10000; } if(!flag) { //if flag is false here, proved that the second for not exchange, so it is already sorted cout<<"improved bubble sort "<<i<<endl; // only good for nearly sorted data break; } } } void wayne_sortThem::insertionSort(vector<double> &vec1,const vector<double> &vec2, bool (*comp)(double& a, double& b)) { cout << "insertionSort:" << endl; vec1=vec2; double temp; int times=10000; int insertPos; for(unsigned int i=1;i<vec2.size();i++) { temp=vec1[i]; //waiting for insertion insertPos=i; //if no exchange below, it might already the biggest when inserting for(unsigned int j=i-1;j>=0 && comp(temp, vec1[j]);j--) { vec1[j+1]=vec1[j]; //stable sort, relative order will not change insertPos=j; if(j==0) { //cout<<"j is unsigned,so no j-- when j==0, choose to break"<<endl; break; } } vec1[insertPos]=temp; /*if(i==times) { cout<<i<<endl; times=times+10000; }*/ } } void wayne_sortThem::quickSort(vector<double> &vec1,const vector<double> &vec2, bool (*comp)(double& a, double& b)) { cout << "quickSort:" << endl; vec1=vec2; quickSortSub(0,vec1.size()-1,vec1, comp); //the implemention of quicksort } void wayne_sortThem::quickSortSub(int left,int right,vector<double> &vec1, bool (*comp)(double& a, double& b)) { int i=left; //start from the very left to the right until meet j int j=right; //start from the very right to the left until meet i double tempBi=vec1[left]; //store base value for comparison(random algorithm will sample a index between left and right) if(i>j) { //i cannot beyond j cout<<"i is now at the rightside of j"<<endl; system("pause"); return; } while(i!=j && i<j) { //start from the right side while(!comp(vec1[j], tempBi) && i<j) j--; //to find a value from right part that is bigger than base value, and then exchange that value to the front side while(!comp(tempBi, vec1[i]) && i<j) i++; if(i==j) { //time to move base value vec1[left]=vec1[j]; //move meeting value to the very left vec1[j]=tempBi; //move the original very left value to the meeting position break; //break when base value was exchanged } swap(vec1[i], vec1[j]); // front and behind exchange } if(i!=j) { cout<<"i is not equal to jhow come!"<<endl; system("pause"); } if(left<j-1) { quickSortSub(left,j-1,vec1, comp); //quicksort left sub } if(j+1<right) { quickSortSub(j+1,right,vec1, comp); //quicksort right sub } } void wayne_sortThem::heapSortLazy(vector<double>& vec1, const vector<double>& vec2, bool (*comp)(double& a, double& b)) { cout << "heapSortLazy:" << endl; vec1 = vec2; for (unsigned int i = 0; i < vec1.size(); i++) { std::make_heap(vec1.begin(), vec1.end() - i, comp); std::pop_heap(vec1.begin(), vec1.end() - i, comp); } } void wayne_sortThem::heapSort(vector<double>& vec1, const vector<double>& vec2, bool (*comp)(double& a, double& b)) { cout << "heapSort:" << endl; vec1 = vec2; this->buildHeap(vec1, comp); int currentSize = (int)vec1.size(); for (int i = 1; i < (int)vec1.size(); i++) { std::swap(vec1[0], vec1[currentSize - i]); this->adjustHeap(vec1, currentSize - i, 0, comp); } } void wayne_sortThem::buildHeap(vector<double>& vec, bool (*comp)(double& a, double& b)) { int heapSize = (int)vec.size(); for (int i = heapSize / 2; i >= 0; i--) { this->adjustHeap(vec, heapSize, i, comp); } } void wayne_sortThem::adjustHeap(vector<double>& vec, int heapSize, int index, bool (*comp)(double& a, double& b)) { int left = 2 * index + 1; int right = 2 * index + 2; int largest = index; if (left < heapSize && !comp(vec[left], vec[largest])) largest = left; if (right < heapSize && !comp(vec[right], vec[largest])) largest = right; if (largest != index) { std::swap(vec[largest], vec[index]); this->adjustHeap(vec, heapSize, largest, comp); } }
true
0ef3a65a1e6365f7e8ccf743fd455dae887c29cb
C++
chjon/InfiniteChess
/src/io/inputHandler.h
UTF-8
1,297
2.65625
3
[]
no_license
#ifndef CHESS_INPUT_HANDLER_H #define CHESS_INPUT_HANDLER_H #include <SFML/Graphics.hpp> #include "../renderer.h" // Forward declarations class Game; class Renderer; class WindowLayer; // Class declaration class InputHandler { private: // Configuration constants const float MOVE_STEP_SIZE = 0.005f; // Movement keybinds const sf::Keyboard::Key KEY_MOVE_UP = sf::Keyboard::Key::W; const sf::Keyboard::Key KEY_MOVE_DOWN = sf::Keyboard::Key::S; const sf::Keyboard::Key KEY_MOVE_LEFT = sf::Keyboard::Key::A; const sf::Keyboard::Key KEY_MOVE_RIGHT = sf::Keyboard::Key::D; // Options keybinds const sf::Keyboard::Key KEY_DEBUG = sf::Keyboard::Key::F3; const sf::Keyboard::Key KEY_MENU = sf::Keyboard::Key::Escape; // Members Game* game; sf::RenderWindow* window; Renderer* renderer; std::vector<WindowLayer*> layers; // Methods void checkKeyboard(); void checkEvents(); void onKeyPress(sf::Event::KeyEvent keyEvent); bool isCritical(sf::Event::EventType eventType); void onMousePress(sf::Event::MouseButtonEvent event); public: // Constructors InputHandler(Game* g, sf::RenderWindow* w, Renderer* r); ~InputHandler(); // Methods inline void addLayer(WindowLayer* layer) { layers.push_back(layer); } void tick(); }; #endif // CHESS_INPUT_HANDLER_H
true
4889b38dd388b46c52c4f2aaadd8fd39deda9c54
C++
Tvorobey/BINSGUI
/Utilities/lock.h
UTF-8
698
2.84375
3
[]
no_license
#ifndef LOCK_H #define LOCK_H #include <QMutex> #include <memory> /*! * \brief Класс - Lock * \details Класс служит для того, чтобы можно было * не беспокоиться о том, что забудешь открыть заново мьютекс * Достаточно создать объект этого класса, в параметр бросить * указатель на мьютек. При выходе из функции функция чистильщика * shared_ptr, откроет мьютекс сама */ class Lock { public: Lock(QMutex *pm); private: std::shared_ptr<QMutex> mutexPtr; }; #endif // LOCK_H
true
1808e3edaad76561cf89b83ce436b081f5275306
C++
ThaiNhatMinh/Math
/Helper.cpp
UTF-8
924
3.078125
3
[]
no_license
#include "Helper.h" #pragma once // Remove the quotes from a string void RemoveQuotes( std::string& str ) { size_t n; while ( ( n = str.find('\"') ) != std::string::npos ) str.erase(n,1); } // Get's the size of the file in bytes. int GetFileLength( std::istream& file ) { int pos = file.tellg(); file.seekg(0, std::ios::end ); int length = file.tellg(); // Restore the position of the get pointer file.seekg(pos); return length; } void IgnoreLine( std::istream& file, int length ) { file.ignore( length, '\n' ); } // Computes the W component of the quaternion based on the X, Y, and Z components. // This method assumes the quaternion is of unit length. void ComputerQuatW( Quat& quat ) { float t = 1.0f - ( quat.x * quat.x ) - ( quat.y * quat.y ) - ( quat.z * quat.z ); if ( t < 0.0f ) { quat.w = 0.0f; } else { quat.w = -sqrtf(t); } }
true
04ec045548071f7dc8b0b5de0c923f72599f7067
C++
AviadKlein1/Cpp-basic-2021
/תרגיל בית 6 שאלה 5 - בודק אוטומטי/Source.cpp
UTF-8
1,218
3.71875
4
[]
no_license
//Aviad Klein ID 315552679 //Intro to computer science //6.5. //the program prints the difference between two groups of numbers. #include <iostream> using namespace std; void diff(int* s1, int* s2, int*dif) { bool flag = false; int counter = 0; for (int i = 0; i < 6; i++) { flag = false; for (int j = 0; j < 6; j++) { if (s1[i] == s2[j]) flag = true; } if (!flag) { dif[counter] = s1[i]; counter++; } } } int main() { int set1[6], set2[6], dif[6]; int x, y; cout << "enter first 6 numbers:\n"; for (int i = 0; i < 6; i++) { cin >> x; if (x >= 0 && x % 1 == 0) set1[i] = x; else { cout << "ERROR"; i--; } } cout << "enter next 6 numbers:\n"; for (int i = 0; i < 6; i++) { cin >> y; if (y >= 0 && y % 1 == 0) set2[i] = y; else { cout << "ERROR"; i--; } } diff(set1, set2, dif); cout << "set difference is :\n"; if (dif[0]<0 || dif[0]> 9999)cout << "empty"; else { for (int i = 0; dif[i] > 0 && dif[i] < 999; i++) { cout << dif[i] << " "; } } return 0; } /* enter first 6 numbers: 3 9 5 7 1 10 enter next 6 numbers: 1 6 3 4 5 2 set difference is: 10 9 */
true
337faee0896156a5cd10437d7075f706af33596d
C++
alesegdia/secs
/src/lib/secs/systemmanager.h
UTF-8
1,602
2.59375
3
[]
no_license
#pragma once #include "entityobserver.h" #include "system.h" #include "entitysystem.h" #include "componentflagsmanager.h" #include <unordered_map> namespace secs { typedef size_t SystemGroupIndex; class SystemManager : public EntityObserver { public: static constexpr SystemGroupIndex MaxSystemGroups = 32; SystemManager( ComponentFlagsManager& flags_manager ); ~SystemManager(); // EntityObserver interface void OnEntitiesChanged(const std::vector<Entity> &entities) final; void OnEntitiesAdded(const std::vector<Entity> &entities) final; void OnEntitiesRemoved(const std::vector<Entity> &entities) final; void PushSystem( secs::System::Ptr system, EntitySystem::Ptr entity_system ); void ActivateSystemGroup( SystemGroupIndex sgi ); void SetSystemGroup( System::Ptr system, SystemGroupIndex group ); void DisableSystemGroup( SystemGroupIndex sgi ); void EnableSystemGroup( SystemGroupIndex sgi ); void Step(double delta ); void Render(); private: void insertSorted(System::Ptr system, std::vector<System::Ptr> &vec ); /** * @brief m_systems all systems to execute on step() */ std::vector<System::Ptr> m_processingSystems; /** * @brief m_renderingSystems all rendering systems to execute on render() */ std::vector<System::Ptr> m_renderingSystems; /** * @brief m_entitySystems all entity systems for entity change/add/removal notification */ std::vector<EntitySystem::Ptr> m_entitySystems; ComponentFlagsManager& m_flagsManager; std::vector<System::Ptr>* m_systemsByGroup[MaxSystemGroups]{}; }; }
true
186bea618e4397ff8cb0b2a1fd24f413838e5934
C++
mark-borg/CheckProductLabel
/qvcore/ContainerAreaFinder.h
UTF-8
2,257
2.5625
3
[]
no_license
#ifndef __CONTAINER_AREA_FINDER_H__ #define __CONTAINER_AREA_FINDER_H__ #include "common.h" ///EXPIMP_TEMPLATE template class DLL_EXPORT std::vector< CvRect >; ///EXPIMP_TEMPLATE template class DLL_EXPORT std::vector< IplImage* >; ///EXPIMP_TEMPLATE template class DLL_EXPORT std::vector< CvPoint3D32f >; class DLL_EXPORT ContainerAreaFinder { private: std::vector< CvRect > template_roi; CvRect search_roi; CvRect label_roi; bool model_initialised; std::vector< IplImage* > label_templates; std::vector< CvPoint3D32f > ref_eqn; bool debug; IplImage* debug_image; IplImage* debug_image2; IplImage* debug_image3; double min_line_angle_threshold; // in degrees double rotation_correction; CvPoint3D32f displacement_correction; // pre-allocated temporary objects std::vector< IplImage* > wrk; std::vector< CvRect > roi; public: ContainerAreaFinder(); bool add_template_area( CvRect& roi ); int num_templates() const { return template_roi.size(); } void set_debug( bool debug = true ) { this->debug = debug; } void set_label_area( const CvRect& area ) { assert( ! model_initialised ); label_roi = area; } CvRect get_label_area() const { return label_roi; } void set_search_area( const CvRect& area ) { assert( ! model_initialised ); search_roi = area; } CvRect get_search_area() const { return search_roi; } virtual ~ContainerAreaFinder(); double get_rotation_correction( bool in_degrees = true ) const { return in_degrees ? rotation_correction * 180 / CV_PI : rotation_correction; } CvPoint2D32f get_displacement_correction() const { return cvPoint2D32f( displacement_correction.x / displacement_correction.z, displacement_correction.y / displacement_correction.z ); } void set_min_line_angle_threshold( double line_angle_threshold ) { assert( line_angle_threshold > 0.0 && line_angle_threshold < 90.0 ); min_line_angle_threshold = line_angle_threshold; } double get_min_line_angle_threshold() const { return min_line_angle_threshold; } bool finalise_model( IplImage* image ); bool process_image( IplImage* image, CvMat* registration_matrix ); }; #endif
true
96cdf8aaeb25e448a16996fd7b80122a290d0948
C++
EKISUKE/GitHubTest
/GameEngine/src/gmAABBTree.h
SHIFT_JIS
5,508
2.734375
3
[]
no_license
//----------------------------------------------------------------------------- //! //! @file gmAABBTree.h //! @brief AABB-Tree //! @author YukiIshigaki //! //----------------------------------------------------------------------------- #pragma once //! C̕` (Flat) //! @param [in] p1 W1 //! @param [in] p1 W2 //! @param [in] color J[ void drawLineF(const Vector3& p1, const Vector3& p2, const Vector4& color); //----------------------------------------------------------------------------- //! oEfBO{bNX //----------------------------------------------------------------------------- struct AABB { //! ̃oEfBO{bNX쐬 void setEmpty() { _min = Vector3(+FLT_MAX, +FLT_MAX, +FLT_MAX); _max = Vector3(-FLT_MAX, -FLT_MAX, -FLT_MAX); } //! wW܂ރoEfBOɊg void expand(const Vector3& position) { _min._x = min(_min._x, position._x); _min._y = min(_min._y, position._y); _min._z = min(_min._z, position._z); _max._x = max(_max._x, position._x); _max._y = max(_max._y, position._y); _max._z = max(_max._z, position._z); } Vector3 _min; Vector3 _max; }; namespace AABBCollision { inline //! AABB vs AABB //! @param [in] a AABBIuWFNg //! @param [in] b AABBIuWFNg bool isHit(const AABB& a, const AABB& b) { if( a._max._x < b._min._x ) return false; if( a._max._y < b._min._y ) return false; if( a._max._z < b._min._z ) return false; if( b._max._x < a._min._x ) return false; if( b._max._y < a._min._y ) return false; if( b._max._z < a._min._z ) return false; return true; } inline //! ߂荞ݗʂ擾 //! @param [in] a AABBIuWFNg //! @param [in] b AABBIuWFNg Vector3 getSinkVal(const AABB& a, const AABB& b) { Vector3 result = Vector3(0,0,0); if( isHit(a, b) ) { //---- ׂĂ̍߂ f32 sinkX1 = a._max._x - b._min._x; f32 sinkX2 = b._min._x - a._max._x; f32 sinkX3 = a._min._x - b._max._x; f32 sinkX4 = b._max._x - a._min._x; /*f32 sinkY1 = a._max._y - b._min._y; f32 sinkY2 = b._min._y - a._max._y; f32 sinkY3 = a._min._y - b._max._y; f32 sinkY4 = b._max._y - a._min._y;*/ f32 sinkZ1 = a._max._z - b._min._z; f32 sinkZ2 = b._min._z - a._max._z; f32 sinkZ3 = a._min._z - b._max._z; f32 sinkZ4 = b._max._z - a._min._z; //--- ꂼňԏ߂荞ݗʂ߂ f32 sinkMinX = min( min(abs(sinkX1), abs(sinkX2)) , min(abs(sinkX3), abs(sinkX4)) ); ////--- ꂼňԏ߂荞ݗʂ߂ //f32 sinkMinY = min( min(abs(sinkY1), abs(sinkY2)) // , min(abs(sinkY3), abs(sinkY4)) ); f32 sinkMinZ = min( min(abs(sinkZ1), abs(sinkZ2)) , min(abs(sinkZ3), abs(sinkZ4)) ); //f32 minVal = min( min(sinkMinX, sinkMinY), sinkMinZ ); f32 minVal = min( sinkMinX, sinkMinZ ); //---- ΒlŔrĂ̂Œl߂ sinkMinX = math::getSameValofFour(sinkMinX, sinkX1, sinkX2, sinkX3, sinkX4); //sinkMinY = math::getSameValofFour(sinkMinY, sinkY1, sinkY2, sinkY3, sinkY4); sinkMinZ = math::getSameValofFour(sinkMinZ, sinkZ1, sinkZ2, sinkZ3, sinkZ4); //---- ԏ߂荞ݗʂ‚Ăɂ if( minVal == abs(sinkMinX) ) { result = Vector3(sinkMinX, 0, 0); }else{ result = Vector3( 0, 0, sinkMinZ); } } return result; } } // namespace AABBCollision extern void drawLineF(const Vector3& p1, const Vector3& p2, const Vector4& color); extern void drawAABB(const AABB& aabb, const Vector4& color, const Vector3& offset = Vector3(0,0,0)); struct CollisionData; //----------------------------------------------------------------------------- //! AABB-Tree //----------------------------------------------------------------------------- class AABBTree { public: struct Node { //! RXgN^ Node() { _aabb.setEmpty(); _pChild[0] = nullptr; _pChild[1] = nullptr; } //vector<Triangle> _triangles; //!< Op`̔z //vector<CollisionData> _colData; //!< 蔻 CollisionData* _col; //!< 蔻 AABB _aabb; //!< ׂĂ͂ރoEfBO{bNX s32 _dataCount; //!< ŏIm[hȊO̓f[^Ȃ std::unique_ptr<AABBTree::Node> _pChild[2]; //!< qm[h //! Op`Xgm[h\z //! @param [in] colData 蔻̔zf[^ bool build(vector<CollisionData> colData); // aabbƏՓ˃`FbN //! @param [in] aabb 蔻sAABB //! @param [in] hitFunc Op`Ƃ̏Փ˔p̊֐|C^ bool hitCheck(const AABB& aabb, bool(*hitFunc)(Triangle* tri)); //! fobO` //! @param [in] nest ǂ̐[`悷邩 void debugDraw(u32 nest); }; //! RXgN^ AABBTree(); //! fXgN^ virtual ~AABBTree(); //! c[\z bool build(vector<CollisionData>& colData); //! fobOp̏ bool debugSetup(); //! fobO` void debugRender(); private: AABBTree::Node _rootNode; //!< [gm[h }; //=========================================================================== // END OF FILE //===========================================================================
true
60cc0978111b06071c46976683e99b236de4655d
C++
thienphucst92/algorithm-training
/Blue/ss1-dynamic-array/Codeforces_L01P01_691A.cpp
UTF-8
649
3.328125
3
[]
no_license
// Problem from Codeforces // http://codeforces.com/problemset/problem/691/A #include <iostream> #include <vector> #include <algorithm> #include <string> using namespace std; bool isFastenedRightWay(const vector<int> a) { if (a.size() == 1 && a[0] == 0) return false; if (a.size() == 1 && a[0] == 1) return true; int unfastened = std::count(a.begin(), a.end(), 0); return (unfastened == 1); } int main() { int n = 0; vector<int> a; cin >> n; int number; for (int i = 0; i < n ; ++i) { cin >> number; a.push_back(number); } string solution = (isFastenedRightWay(a) ? "YES" : "NO"); cout << solution; return 0; }
true