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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c27a3f8ad139fd6016fa3c308bace4e9d7433eb9 | C++ | scanberg/bilateral-tonemap | /src/Texture2D.cpp | UTF-8 | 1,849 | 2.921875 | 3 | [] | no_license | #include "Texture2D.h"
Texture2D::Texture2D(GLsizei width, GLsizei height, const GLvoid * data,
GLint internalFormat, GLenum format, GLenum type, GLboolean mipmap)
{
glGenTextures(1, &m_textureID);
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, width, height, 0, format, type, data);
if(mipmap)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
else
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
m_width = width;
m_height = height;
}
Texture2D::~Texture2D()
{
if(glIsTexture(m_textureID))
glDeleteTextures(1, &m_textureID);
}
GLuint Texture2D::getID() const
{
return m_textureID;
}
GLsizei Texture2D::getWidth() const
{
return m_width;
}
GLsizei Texture2D::getHeight() const
{
return m_height;
}
void Texture2D::bind(GLuint channel) const
{
glActiveTexture(channel);
glBindTexture(GL_TEXTURE_2D, m_textureID);
}
void Texture2D::generateMipmap()
{
glBindTexture(GL_TEXTURE_2D, m_textureID);
glGenerateMipmap(GL_TEXTURE_2D);
}
void Texture2D::setParameter(GLenum name, GLint param)
{
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexParameteri(GL_TEXTURE_2D, name, param);
}
void Texture2D::setParameter(GLenum name, GLfloat param)
{
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexParameterf(GL_TEXTURE_2D, name, param);
}
void Texture2D::setData(GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
const GLvoid * data, GLenum format, GLenum type)
{
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexSubImage2D(GL_TEXTURE_2D, level, xoffset, yoffset,
width, height, format, type, data);
} | true |
7ee4680ed6d1ebd5f0822ad4f06e78fe1422ba14 | C++ | AlexApps99/sead | /include/hostio/seadHostIOCurve.h | UTF-8 | 4,590 | 2.796875 | 3 | [] | no_license | #pragma once
#include <array>
#include "basis/seadRawPrint.h"
#include "basis/seadTypes.h"
#include "math/seadVector.h"
namespace sead::hostio
{
class ICurve
{
public:
virtual f32 interpolateToF32(f32 t) = 0;
virtual Vector2f interpolateToVec2f(f32 t) = 0;
};
enum class CurveType
{
Linear = 0,
Hermit = 1,
Step = 2,
Sin = 3,
Cos = 4,
SinPow2 = 5,
Linear2D = 6,
Hermit2D = 7,
Step2D = 8,
NonUniformSpline = 9,
Hermit2DSmooth = 10,
};
inline constexpr int cNumCurveType = 11;
struct CurveDataInfo
{
u8 curveType;
u8 _1;
u8 numFloats;
u8 numUse;
};
struct CurveData
{
u32 numUse;
u32 curveType;
f32 f[30];
};
static_assert(sizeof(CurveData) == 0x80);
template <typename T>
class Curve : public ICurve
{
public:
Curve()
{
mInfo.curveType = 0;
mInfo.numUse = 0;
mInfo._1 = 4;
mInfo.numFloats = 0;
mFloats = nullptr;
}
f32 interpolateToF32(f32 t) override;
Vector2f interpolateToVec2f(f32 t) override;
CurveType getCurveType() const { return CurveType(mInfo.curveType); }
void setData(CurveData* data, CurveType type, u32 num_floats, u32 num_use)
{
data->curveType = u8(type);
data->numUse = num_use;
setCurveType(type);
setFloats(data, num_floats);
setNumUse(num_use);
}
void setFloats(CurveData* data, u32 num_floats)
{
mInfo.numFloats = num_floats;
mFloats = data->f;
}
void setCurveType(CurveType type)
{
SEAD_ASSERT(mInfo.curveType < cNumCurveType);
mInfo.curveType = u8(type);
}
void setNumUse(u32 numUse)
{
SEAD_ASSERT(numUse <= 0xff);
mInfo.numUse = numUse;
}
f32* mFloats;
CurveDataInfo mInfo;
};
template <typename T>
T curveLinear_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveHermit_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveStep_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveSin_(f32 t_, const CurveDataInfo* info, const T* f);
template <typename T>
T curveCos_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveSinPow2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveLinear2D_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveHermit2D_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveStep2D_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveNonuniformSpline_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
T curveHermit2DSmooth_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
using CurveFunctionTable = std::array<decltype(curveLinear_<T>)*, cNumCurveType>;
extern CurveFunctionTable<f32> sCurveFunctionTbl_f32;
extern CurveFunctionTable<f64> sCurveFunctionTbl_f64;
template <typename T>
Vector2<T> curveLinearVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveHermitVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveStepVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveSinVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveCosVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveSinPow2Vec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveLinear2DVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveHermit2DVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveStep2DVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveNonuniformSplineVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
Vector2<T> curveHermit2DSmoothVec2_(f32 t, const CurveDataInfo* info, const T* f);
template <typename T>
using CurveFunctionTableVec2 = std::array<decltype(curveLinearVec2_<T>)*, cNumCurveType>;
extern CurveFunctionTableVec2<f32> sCurveFunctionTbl_Vec2f;
extern CurveFunctionTableVec2<f64> sCurveFunctionTbl_Vec2d;
template <>
inline f32 Curve<f32>::interpolateToF32(f32 t)
{
return sCurveFunctionTbl_f32[u8(mInfo.curveType)](t, &mInfo, mFloats);
}
template <>
inline Vector2f Curve<f32>::interpolateToVec2f(f32 t)
{
return sCurveFunctionTbl_Vec2f[u8(mInfo.curveType)](t, &mInfo, mFloats);
}
} // namespace sead::hostio
| true |
7deeb964a9122fae490ac35b498ab4b5297a5937 | C++ | ksand012/UCR-Files | /cs12_programs/program03/Message.cpp | UTF-8 | 389 | 3 | 3 | [] | no_license | #include "Message.h"
Message::Message()
{
this->author = "";
this->subject = "";
this->body = "";
}
Message::Message(const string &athr, const string &sbjct, const string &body)
{
this->author = athr;
this->subject = sbjct;
this->body = body;
}
void Message::display() const
{
cout << this->subject << endl << "from " << this->author << ": " << this->body;
} | true |
78423396f0a98e8f975fd3e37a61ed42d2edabbd | C++ | warehouse-picking-automation-challenges/ru_pracsys | /src/prx_utilities/prx/utilities/distance_functions/l_infinite_norm.hpp | UTF-8 | 1,076 | 2.578125 | 3 | [] | no_license | /**
* @file l_infinite_norm.hpp
*
* @copyright Software License Agreement (BSD License)
* Copyright (c) 2013, Rutgers the State University of New Jersey, New Brunswick
* All Rights Reserved.
* For a full description see the file named LICENSE.
*
* Authors: Andrew Dobson, Andrew Kimmel, Athanasios Krontiris, Zakary Littlefield, Kostas Bekris
*
* Email: pracsys@googlegroups.com
*/
#pragma once
#ifndef PRX_L_INFINITE_NORM_HPP
#define PRX_L_INFINITE_NORM_HPP
#include "prx/utilities/definitions/defs.hpp"
#include "prx/utilities/distance_functions/distance_function.hpp"
namespace prx
{
namespace util
{
/**
* A class that computes the l_infinite norm of two points.
*
* @brief <b> A class that computes the l_infinite norm of two points.</b>
*
* @author Athanasios Krontiris
*/
class l_infinite_norm_t : public distance_function_t
{
public:
l_infinite_norm_t(){ }
~l_infinite_norm_t(){ }
virtual double distance(const space_point_t* s1, const space_point_t* s2);
};
}
}
#endif | true |
1c22a1e8d69363060aa6af79c1d839904f92a853 | C++ | Davian99/Acepta_El_Reto | /AR_376.cpp | UTF-8 | 494 | 2.71875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int picos(int v[], int n) {
int ret = 0;
int i = 1;
while (i < n - 1) {
if (v[i - 1] < v[i] && v[i + 1] < v[i])
++ret;
++i;
}
if (v[0] > v[1] && v[0] > v[n - 1])
++ret;
if (v[n - 1] > v[n - 2] && v[n - 1] > v[0])
++ret;
return ret;
}
int main() {
//freopen("in.txt", "r", stdin);
int a[1000], n;
cin >> n;
while (n != 0) {
for (int i = 0; i < n; ++i)
cin >> a[i];
cout << picos(a, n) << "\n";
cin >> n;
}
return 0;
} | true |
5ded7ad51cc8de16789aa4101afbc76bde47587a | C++ | radtek/IMClassic | /Common/Dundas/ug97mfc/Source/UGDrwHnt.cpp | UTF-8 | 6,304 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | /***********************************************
Ultimate Grid 97
Copyright 1994 - 1997 Dundas Software Ltd.
Class
CUGDrawHint
Purpose
This class is used internally by the grid
to keep track of which cells need redrawing
The grid draws its cells in an extremely
optimized manner which gives it is great
speed.
This is the class which helps the optimization
process by maintaining a list of cells that
need to be redrawn.
Datails
-cells are added to this list by the grid
when movement is made and/or changes to the
grid are made. Only the cells that are
affected are added.
-when the grid is going to redraw itself
it calls this classes IsInvalid function
to see if the cell really needs to be
redrawn
************************************************/
#include "stdafx.h"
#include "UGCtrl.h"
//#include "ugdrwhnt.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/******************************************
*******************************************/
CUGDrawHint::CUGDrawHint(){
m_List = NULL;
m_VList = NULL;
}
/******************************************
*******************************************/
CUGDrawHint::~CUGDrawHint(){
ClearHints();
}
/******************************************
*******************************************/
void CUGDrawHint::AddHint(int col,long row){
AddHint(col,row,col,row);
}
/******************************************
*******************************************/
void CUGDrawHint::AddHint(int startCol,long startRow,int endCol,long endRow){
UGDrwHintList *next = m_List;
UGDrwHintList *newhint = new UGDrwHintList;
if(m_List != NULL){
while(next->next != NULL){
next = next->next;
}
next->next = newhint;
}
else{
m_List = newhint;
m_minCol = startCol;
m_minRow = startRow;
m_maxCol = endCol;
m_maxRow = endRow;
}
newhint->next = NULL;
newhint->startCol = startCol;
newhint->startRow = startRow;
newhint->endCol = endCol;
newhint->endRow = endRow;
if(startCol < m_minCol)
m_minCol = startCol;
if(endCol > m_maxCol)
m_maxCol = endCol;
if(startRow < m_minRow)
m_minRow = startRow;
if(endRow > m_maxRow)
m_maxRow = endRow;
}
/******************************************
*******************************************/
void CUGDrawHint::AddToHint(int col,long row){
AddToHint(col,row,col,row);
}
/******************************************
*******************************************/
void CUGDrawHint::AddToHint(int startCol,long startRow,int endCol,long endRow){
if(m_List == NULL)
AddHint(startCol,startRow,endCol,endRow);
if(m_List->startCol > startCol)
m_List->startCol = startCol;
if(m_List->endCol < endCol)
m_List->endCol = endCol;
if(m_List->startRow > startRow)
m_List->startRow = startRow;
if(m_List->endRow < endRow)
m_List->endRow = endRow;
if(startCol < m_minCol)
m_minCol = startCol;
if(endCol > m_maxCol)
m_maxCol = endCol;
if(startRow < m_minRow)
m_minRow = startRow;
if(endRow > m_maxRow)
m_maxRow = endRow;
}
/******************************************
*******************************************/
void CUGDrawHint::ClearHints(){
//clear the Invalid list
UGDrwHintList *current = m_List;
UGDrwHintList *next;
while(current != NULL){
next = current->next;
delete current;
current = next;
}
m_List = NULL;
//clear the valid list
UGDrwHintVList *currentV = m_VList;
UGDrwHintVList *nextV;
while(currentV != NULL){
nextV = currentV->next;
delete currentV;
currentV = nextV;
}
m_VList = NULL;
}
/******************************************
*******************************************/
int CUGDrawHint::IsInvalid(int col,long row){
if(m_List == NULL)
return FALSE;
if(col < m_minCol || col > m_maxCol)
return FALSE;
if(row < m_minRow || row > m_maxRow)
return FALSE;
UGDrwHintList *current = m_List;
//check the invalid list
while(current != NULL){
//check to see if the item in the list covers a greater range
if(col >= current->startCol && col <= current->endCol){
if(row >= current->startRow && row <= current->endRow){
return TRUE;
}
}
current = current->next;
}
//if the item is not in the invalid list assume it is valid
return FALSE;
}
/******************************************
*******************************************/
int CUGDrawHint::IsValid(int col,long row){
if(m_VList == NULL)
return FALSE;
UGDrwHintVList *currentV = m_VList;
UGDrwHintVList *nextV;
//check the valid list
while(currentV != NULL){
nextV = currentV->next;
if(col == currentV->Col && row == currentV->Row)
return TRUE;
currentV = nextV;
}
return FALSE;
}
/******************************************
*******************************************/
int CUGDrawHint::GetTotalRange(int *startCol,long *startRow,int *endCol,long *endRow){
if(m_List == NULL){
*startCol = 0; //put in def values just in case the return
*startRow = 0; //value is not checked
*endCol = 0;
*endRow = 0;
return FALSE;
}
*startCol = m_List->startCol;
*startRow = m_List->startRow;
*endCol = m_List->endCol;
*endRow = m_List->endRow;
UGDrwHintList *current = m_List;
UGDrwHintList *next;
while(current != NULL){
next = current->next;
//check to see if the item in the list covers a greater range
if(*startCol > current->startCol)
*startCol = current->startCol;
if(*startRow > current->startRow)
*startRow = current->startRow;
if(*endCol < current->endCol)
*endCol = current->endCol;
if(*endRow < current->endRow)
*endRow = current->endRow;
current = next;
}
return TRUE;
}
/******************************************
*******************************************/
void CUGDrawHint::SetAsValid(int col,long row){
UGDrwHintVList *nextV = m_VList;
UGDrwHintVList *newhintV = new UGDrwHintVList;
if(m_VList != NULL){
while(nextV->next != NULL){
nextV = nextV->next;
}
nextV->next = newhintV;
}
else
m_VList = newhintV;
newhintV->next = NULL;
newhintV->Col = col;
newhintV->Row = row;
} | true |
bf84ef7baf40139aa48316c9ad24520e3c6fea18 | C++ | sebas095/Competitive-Programming | /COJ/3317 - Jumping Frogs.cpp | UTF-8 | 706 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define LIMIT 1000004
#define MOD 1000000007
using namespace std;
//674 - Coin Change: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=615
int jumps[] = {1,2};
int n;
//Forma Iterativa
long long ways [LIMIT];
void count (){
ways [0] = 1;
for (int i = 0; i < 2; i++ ){
for (int j = jumps [i]; j < LIMIT; j++){
ways [j] += ways [j - jumps [i]];
if(ways[j] > MOD)
ways[j] %= MOD;
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
count();
while(t--){
cin>>n;
cout<<ways[n]<<endl;
}
return 0;
} | true |
0b7d67a5450c59d28440e832601f7a05441976e8 | C++ | blackbird806/interview-projects | /median-cpp/median.cpp | UTF-8 | 5,181 | 3.59375 | 4 | [] | no_license | #include "median.hpp"
#include <stdexcept>
#include <algorithm>
#include <random>
#include <cassert>
// #define MY_QUICKSELECT
#ifdef SORT_MEDIAN
double median(const std::vector<int>& numbers) {
if(numbers.size() == 0)
throw std::invalid_argument("No median for empty vector");
auto mutableNumbers = numbers;
std::sort(mutableNumbers.begin(), mutableNumbers.end());
const bool isOdd = numbers.size() % 2;
return isOdd
? mutableNumbers[numbers.size() / 2]
: (mutableNumbers[numbers.size() / 2 - 1] + mutableNumbers[numbers.size() / 2]) / 2.0;
}
#elif defined(MY_QUICKSELECT)
// quickselect algorithm, average complexity is O(n) worst case is O(n log n)
// based on: https://rcoh.me/posts/linear-time-median-finding/
// quickselect find the nth smallest element in the range [first .. last]
double quickselect(std::vector<int>::iterator first, std::vector<int>::iterator last, size_t nth)
{
auto const len = std::distance(first, last);
if (len == 1)
{
assert(nth == 0);
return *first;
}
// choose a random pivot in the array / sub-array
std::default_random_engine random_generator;
std::uniform_int_distribution<int> distribution(0, static_cast<int>(len) - 1);
int const pivot = first[distribution(random_generator)];
// partition the vector in order to regroup all elem that are less than the pivot
// complexity of std::partition is O(n) see: https://en.cppreference.com/w/cpp/algorithm/partition
auto const low_end = std::partition(first, last, [pivot](auto const& e)
{
return e < pivot;
});
// get all elements that are equal with the pivot
auto const pivots_start = low_end;
auto const pivots_end = std::partition(low_end, last, [pivot](auto const& e)
{
return e == pivot;
});
auto const up_start = pivots_end;
auto const low_size = std::distance(first, low_end);
auto const pivot_size = std::distance(pivots_start, pivots_end);
// at this point the array / sub-array is partitionned like this
// [first .. low_end] [pivots_start .. pivots_end] [up_start .. last]
//
// where the range [first .. low_end] contains all elements that are less than the pivot
// [pivots_start .. pivots_end] contains all elements that are equal to the pivot
// [up_start .. last] contains all elements higher than the pivot
assert(low_size >= 0);
assert(pivot_size >= 0);
// if the nth is contained in the lower range recurse on it
if (nth < static_cast<size_t>(low_size))
return quickselect(first, low_end, nth);
// if the nth is in the pivot range then nth is the median of this array / sub-array
if (nth < static_cast<size_t>(low_size + pivot_size))
return *low_end;
// else if the th_element is contained in the upper range recurse on it
// search for the {nth - low_size - pivot_size} since we recurse on the upper range
return quickselect(up_start, last, nth - low_size - pivot_size);
}
double median(std::vector<int> const& numbers) {
size_t const array_size = std::size(numbers);
if(array_size == 0)
throw std::invalid_argument("No median for empty vector");
// work on a copy since quickselect func will modify the array
std::vector<int> cpy(numbers);
bool const is_odd = array_size % 2 == 1;
if (is_odd)
// if the array is odd, the median is the {array_size / 2} smallest element of the array
return quickselect(cpy.begin(), cpy.end(), array_size / 2);
// else it is the average between the {array_size / 2} and the {array_size / 2 - 1} smallests elements of the array
return 0.5 *
( quickselect(cpy.begin(), cpy.end(), array_size / 2 - 1) +
quickselect(cpy.begin(), cpy.end(), array_size / 2) );
}
#else
// this implementation uses std::nth_element which have O(n) average complexity too
// fastest function so far
double median(std::vector<int> const& numbers) {
size_t const array_size = std::size(numbers);
if (array_size == 0)
throw std::invalid_argument("No median for empty vector");
// work on a copy since std::nth_element func will modify the array
std::vector<int> cpy(numbers);
bool const is_odd = array_size % 2 == 1;
// if the array is odd, the median is the {array_size / 2} smallest element of the array
// according to the std::nth_element doc :
// "The element pointed at by nth is changed to whatever element would occur in that position if [first, last) were sorted. "
// see: https://en.cppreference.com/w/cpp/algorithm/nth_element
// so if the array length is odd the median is placed at {cpy.begin() + array_size / 2}
std::nth_element(cpy.begin(), cpy.begin() + array_size / 2, cpy.end());
if (is_odd)
return cpy[array_size / 2];
int const n1 = cpy[array_size / 2];
// if the array length is even then we need to compute the average between elements placed at {array_size / 2} and {array_size / 2 - 1}
// we need to call a second time nth_element in order to get the {array_size / 2 - 1} smallest element of the array
std::nth_element(cpy.begin(), cpy.begin() + array_size / 2 - 1, cpy.end());
int const n2 = cpy[array_size / 2 - 1];
// cast to long long to avoid int overflow
return 0.5 * (static_cast<long long int>(n1) + static_cast<long long int>(n2));
}
#endif
| true |
9ed75efa1b5e04738db95aaf74036ba9a2bea64e | C++ | zhucebuliaopx/algorithm009-class02 | /Week_03/homework/236.二叉树的最近公共祖先.cpp | UTF-8 | 1,489 | 3.453125 | 3 | [] | no_license | /*
* @lc app=leetcode.cn id=236 lang=cpp
*
* [236] 二叉树的最近公共祖先
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// class Solution {
// public:
// TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
// if (!root || root == p || root == q) return root;
// TreeNode* left = lowestCommonAncestor(root->left, p, q);
// TreeNode* right = lowestCommonAncestor(root->right, p, q);
// if (!left) return right;
// if (!right) return left;
// return root;
// }
// };
class Solution {
public:
TreeNode* res;
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
traverse(root, p, q);
return res;
}
bool traverse(TreeNode* cur, TreeNode*p, TreeNode*q) {
if (cur == NULL ) return false;
int left = traverse(cur->left, p, q);
int right = traverse(cur->right, p, q);
int mid = (cur == p || cur == q) ? 1 : 0;
if (mid + left + right >= 2){ // 这里相当于把第一种做法的最后2个返回 和开头的pq判断合并到了一起,只要2个满足条件,将该值返回或者说赋给res节点
this->res = cur;
}
return (mid + left + right > 0);
}
};
/*
效率更高
*/
// @lc code=end
| true |
a165a012445c186a721f77ad3343d2a98fc73c53 | C++ | EthanGriffee/SoftwareDev | /assignment4/array.h | UTF-8 | 44,056 | 3.84375 | 4 | [] | no_license | #pragma once
#include <stdlib.h>
#include "object.h"
#include "string.h"
// Wrapper for a Float
class FloatObj : public Object {
public:
float f;
// sets the value of f to input_f
FloatObj(float input_f) {
f = input_f;
}
FloatObj(FloatObj& f) {
f = f.getFloat();
}
// returns if other is a float that has the same f
bool equals(Object *other) {
float epsilon = .01;
FloatObj * f2 = dynamic_cast<FloatObj*> (other);
if (f2 && (f2->getFloat() - f < epsilon) && (f2->getFloat() - f > -epsilon)){
return true;
}
return false;
}
// returns f
float getFloat() {
return f;
}
};
// Wrapper for a Boolean
class BoolObj : public Object {
public:
bool b;
// sets the value of b to input_b
BoolObj(bool input_b) {
b = input_b;
}
BoolObj(BoolObj& b) {
b = b.getBool();
}
// returns if other is a boolean that has the same b
bool equals(Object *other){
BoolObj * b2 = dynamic_cast<BoolObj*> (other);
if (b2 && b2->getBool() == b ){
return true;
}
return false;
}
// returns b
bool getBool() {
return b;
}
};
// Wrapper for a Integer
class IntObj : public Object{
public:
int i;
// sets the value of i to input_i
IntObj(int input_i) {
i = input_i;
}
// returns if other is a integer that has the same i
bool equals(Object *other){
IntObj * i2 = dynamic_cast<IntObj*> (other);
if (i2 && i2->getInt() == i ){
return true;
}
return false;
}
IntObj(IntObj& i) {
i = i.getInt();
}
// returns i
int getInt() {
return i;
}
};
/**
* This class represents an Array, more akin to a dynamic ArrayList type
* versus a fixed-sized array, which may already be represented or built-in in CwC.
* This interface offers the overall main functionalities:
* Addition of elements
* Addition of Arrays
* Removal of elements
* Indexing by Element
* Get Element by Index
* Equality
* Replacing elements at an Index
* This class CAN be implemented using an underlying array structure that is dynamically resized.
* Note that the inital memory outlay is an array of pointers of size 10. We wish to reduce
* the amount of resizing of the array, which would make several operations have O(n) time instead
* of O(1) time. The below fields exist to serve as an example of how to implement.
* There are several STUB implementations in this API: In order to write a StringArray
* you will need to extend Array and correctly override the virtual functions.
**/
class Array : public Object {
public:
Object** array;
size_t size;
size_t max_capacity;
/**
* Default constructor which will set the initial max-capacity to the array to 10.
**/
Array() {
max_capacity = 10;
size = 0;
array = new Object*[max_capacity];
}
Array(Array& arr) {
size = arr.getSize();
max_capacity = arr.max_capacity;
array = new Object*[max_capacity];
for (size_t i = 0; i < arr.getSize(); i++) {
Object obj(*(arr.get(i)));
array[i] = &obj;
}
}
/**
* Destructor which will free the memory of the underlying array as well.
**/
~Array() {
delete[] array;
}
/**
* Will return the Object pointer at the provided index. if the index is invalid,
* then the method will return NULL.
* @arg index Location to get the value in the array at.
**/
virtual Object* get(size_t index) {
if (index > size) {
return nullptr;
}
return array[index];
}
/**
* Clears the array and reinitializes the underlying array to 10 spots with no elements.
* Reinitializes the size to 0.
**/
virtual void clear() {
delete[] array;
max_capacity = 10;
size = 0;
array = new Object*[max_capacity];
}
/**
* Resizing the underlying array. And then copying over the elements to a new array with
* the updated size.
* Default is doubling the array size when the max capacity of the
* underlying array less the number of elements is 2.
**/
virtual void resize() {
max_capacity = max_capacity * 2;
Object** new_array = new Object*[max_capacity];
for (int x = 0; x < size; x++) {
new_array[x] = array[x];
}
delete[] array;
array = new_array;
}
/**
* Returns the first index of the of given Object pointer.
* If the object pointer is not found then -1 is returned.
* @arg to_find Object to find the index of.
**/
virtual int indexOf(Object* to_find) {
for (int x = 0; x < size; x++) {
if(array[x]->equals(to_find)) {
return x;
}
}
return -1;
}
/**
* Adds the element provided to the end of the list, unless the given element is NULL,
* then it will not be added. The size is incremented by 1. If resizing the array is necessary,
* then that should be done.
* @arg to_add Object to be added to the array.
**/
virtual void add(Object* to_add) {
if (!to_add) {
return;
}
if (size + 2 >= max_capacity) {
resize();
}
array[size] = to_add;
size += 1;
}
/**
* Adds the provided array to the end of the list, unless the given array is NULL,
* then it will not be added.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects that all need to be added to this array.
**/
virtual void addAll(Array* to_add) {
size_t add_length = to_add->getSize();
while (size + add_length + 2 >= max_capacity) {
resize();
}
for (size_t i = 0; i < add_length; i++) {
add(to_add->get(i));
}
}
/**
* Adds the provided object at the given index, unless the given object is NULL,
* then it will not be added. Otherwise, all elements previously at the index and
* to the right will be shifted accordingly.
* If the index is invalid, then nothing will be added/shifted.
* The size of this array is incremented by 1.
* If resizing the array is necessary, then that should be done.
* @arg to_add Object to be added to the array
* @arg index Location to add the Object at
**/
virtual void add(Object* to_add, size_t index) {
if (index > size) {
return;
}
if (size + 2 >= max_capacity) {
resize();
}
size += 1;
for (int x = size; x > index; x--){
array[x] = array[x - 1];
}
array[index] = to_add;
}
virtual void set(Object* to_add, size_t index) {
if (index > size) {
return;
}
if (index == size) {
add(to_add);
return;
}
if (size + 2 >= max_capacity) {
resize();
}
array[index] = to_add;
}
/**
* Adds all the elements of the provided array at the given index,
* unless the given array is NULL, then it will not be added. Otherwise,
* all elements previously at the index and
* to the right will be shifted accordingly by the size of the procided array,
* If the index is invalid, then nothing will be added/shifted.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects to be added to the array
* @arg index Location to add the objects to the array at
**/
virtual void addAll(Array* to_add, size_t index) {
if (index > size) {
return;
}
size_t add_length = to_add->getSize();
while (size + add_length + 2 >= max_capacity) {
resize();
}
size += add_length;
for (int x = size - 1; x >= index + add_length; x--){
array[x] = array[x - add_length];
}
for (int x = 0; x < add_length; x++){
array[index + x] = to_add->get(x);
}
}
/**
* Returns the subarray starting from the provided index to the end of the array.
* If the index is invalid, then the method returns NULL
* @arg index Starting place for the subarray
**/
virtual Array* subArray(size_t index) {
return subArray(index, size);
}
/**
* Returns the subarray starting from the provided index to the ending index
* The starting index must always be greater than the ending index. If either index is invalid,
* then NULL is returned. The set is [start, end)
* @arg startIndex starting place for the subarray
* @arg endIndex location of the last object to be put in the subarray
**/
virtual Array* subArray(size_t startIndex, size_t endIndex) {
if (startIndex > endIndex || endIndex > size) {
return NULL;
}
Array* arr = new Array();
while (startIndex < endIndex) {
arr->add(this->get(startIndex));
startIndex += 1;
}
return arr;
}
/**
* Removes the first instance of the given Object in this array. If nothing
* is found, then no action will occur. The size reduces by 1 if the
* element is found.
* @arg to_remove Object to be removed from the array
**/
virtual void remove(Object* to_remove) {
for (size_t i = 0; i < size; i ++) {
if (this->get(i)->equals(to_remove)) {
size -= 1;
for (int x = i; x < size; x++) {
array[x] = array[x + 1];
}
return;
}
}
}
/**
* Removes all instances of the given Object in this array. If nothing
* is found, then no action will occur. The size reduces the number of found
* elements there are.
* @arg to_remove Object that all instances in the array will be removed of
**/
virtual void removeAll(Object* to_remove) {
for (size_t i = 0; i < size; i ++) {
if (this->get(i)->equals(to_remove)) {
size -= 1;
for (int x = i; x < size; x++) {
array[x] = array[x + 1];
}
i-=1;
}
}
}
/**
* Returns number of elements in the array.
**/
virtual size_t getSize() {
return size;
}
/**
* Overriding the Object equals method.
* Returns if all the elements in this array and the given object are equal and
* in the same other.
* If the given object is NULL or not an array, then false will be returned.
* @arg other Object to check if this array is equal to
**/
bool equals(Object* other) {
Array * arr = dynamic_cast<Array*>(other);
if (arr == nullptr || arr->getSize() != size) {
return false;
}
for (size_t x = 0; x < size; x++) {
if (!array[x]->equals(arr->get(x))) {
return false;
}
}
return true;
}
/**
* Overriding the Object hash_me() method.
* Hashes the array based on user specifications. Default implementation is
* to hash all internal elements and sum them up.
**/
size_t hash_me_() {
size_t n = 0;
for(int x = 0; x < size; x++) {
n += array[x]->hash();
}
return n;
}
};
/**
* Incomplete implementation of String Array. No methods overriden from
* Array. Created for testing purposes, so we can design tests.
**/
class StringArray : public Object {
public:
Array* str_arr;
/**
* Default constructor which will set the initial max-capacity to the array to 10.
**/
StringArray() {
str_arr = new Array();
}
/**
* Initalized this array with the characteristics of the passed in array.
* @arg arr Array containing values to be used in initialization.
**/
StringArray(StringArray* arr) {
str_arr = arr->str_arr;
}
/**
* Destructor which will free the memory of the underlying array as well.
**/
~StringArray() {
delete str_arr;
}
/**
* Will return the String pointer at the provided index. if the index is invalid,
* then the method will return NULL.
* @arg index Location to get the value in the array at.
**/
String* get(size_t index) {
return static_cast <String*> (str_arr->get(index));
}
/**
* Clears the array and reinitializes the underlying array to 10 spots with no elements.
* Reinitializes the size to 0.
**/
void clear() {
str_arr->clear();
}
/**
* Resizing the underlying array. And then copying over the elements to a new array with
* the updated size.
* Default is doubling the array size when the max capacity of the
* underlying array less the number of elements is 2.
**/
void resize() {
str_arr->resize();
}
/**
* Returns the first index of the of given String pointer.
* If the pointer is not a String, return -1.
* If the string pointer is not found then -1 is returned.
* @arg to_find String to find the index of.
**/
int indexOf(Object* to_find) {
return str_arr->indexOf(to_find);
}
/**
* Adds the element provided to the end of the list, unless the given element is NULL,
* then it will not be added. The size is incremented by 1. If resizing the array is necessary,
* then that should be done.
* @arg to_add Object to be added to the array.
**/
void add(String* to_add) {
return str_arr->add(to_add);
}
/**
* Adds the provided array to the end of the list, unless the given array is NULL,
* then it will not be added.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of String that all need to be added to this array.
**/
void addAll(StringArray* to_add) {
return str_arr->addAll(to_add->str_arr);
}
/**
* Adds the provided String at the given index, unless the given object is NULL,
* then it will not be added. Otherwise, all elements previously at the index and
* to the right will be shifted accordingly.
* If the index is invalid, then nothing will be added/shifted.
* The size of this array is incremented by 1.
* If resizing the array is necessary, then that should be done.
* If the object provided is not a String, then do nothing.
* @arg to_add Object to be added to the array
* @arg index Location to add the Object at
**/
void add(String* to_add, size_t index) {
return str_arr->add(to_add, index);
}
virtual void set(String* to_add, size_t index) {
return str_arr->add(to_add, index);
}
/**
* Adds all the elements of the provided array at the given index,
* unless the given array is NULL, then it will not be added. Otherwise,
* all elements previously at the index and
* to the right will be shifted accordingly by the size of the procided array,
* If the index is invalid, then nothing will be added/shifted.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects to be added to the array
* @arg index Location to add the objects to the array at
**/
void addAll(StringArray* to_add, size_t index) {
str_arr->addAll(to_add->str_arr, index);
}
/**
* Returns the subarray starting from the provided index to the end of the array.
* If the index is invalid, then the method returns NULL
* @arg index Starting place for the subarray
**/
StringArray* subArray(size_t index) {
StringArray* returning = new StringArray();
if (index > getSize()) {
return NULL;
}
while(index < getSize()) {
returning->add(get(index));
index += 1;
}
return returning;
}
/**
* Returns the subarray starting from the provided index to the ending index
* The starting index must always be greater than the ending index. If either index is invalid,
* then NULL is returned. The set is [start, end)
* @arg startIndex starting place for the subarray
* @arg endIndex location of the last object to be put in the subarray
**/
StringArray* subArray(size_t startIndex, size_t endIndex) {
StringArray* returning = new StringArray();
if (endIndex > getSize() || startIndex > endIndex) {
return NULL;
}
while(startIndex < endIndex) {
returning->add(get(startIndex));
startIndex += 1;
}
return returning;
}
/**
* Removes the first instance of the given Object in this array. If nothing
* is found, then no action will occur. The size reduces by 1 if the
* element is found.
* If the object to be removed is not a string, do nothing.
* @arg to_remove String to be removed from the array
**/
void remove(Object* to_remove) {
str_arr->remove(to_remove);
}
/**
* Removes all instances of the given Object in this array. If nothing
* is found, then no action will occur. The size reduces the number of found
* elements there are.
* If the object to remove is not a string, do nothing.
* @arg to_remove String that all instances in the array will be removed of
**/
void removeAll(Object* to_remove) {
str_arr->removeAll(to_remove);
}
/**
* Returns number of elements in the array.
**/
size_t getSize() {
return str_arr->getSize();
}
/**
* Overriding the String equals method.
* Returns if all the elements in this array and the given object are equal and
* in the same other.
* If the given object is NULL or not an array, then false will be returned.
* @arg other Object to check if this array is equal to
**/
bool equals(Object* other) {
StringArray* o = dynamic_cast<StringArray*> (other);
return o->str_arr->equals(this->str_arr);
}
/**
* Overriding the Object hash_me() method.
* Hashes the array based on user specifications. Default implementation is
* to hash all internal elements and sum them up.
**/
size_t hash_me_() {
return str_arr->hash() + 1;
}
};
class IntArray : public Object {
public:
Array* int_arr;
/**
* Default constructor which will set the initial max-capacity to the array to 10.
**/
IntArray() {
int_arr = new Array();
}
/**
* Initalized this array with the characteristics of the passed in array.
* @arg arr Array containing values to be used in initialization.
**/
IntArray(IntArray* arr) {
int_arr = arr->int_arr;
}
/**
* Destructor which will free the memory of the underlying array as well.
**/
~IntArray() {
delete int_arr;
}
/**
* Will return the int pointer at the provided index. if the index is invalid,
* then the method will return NULL.
* @arg index Location to get the value in the array at.
**/
int get(size_t index) {
Object* obj = int_arr->get(index);
if (obj) {
return static_cast <IntObj*> (obj)->getInt();
}
return NULL;
}
virtual void set(int to_add, size_t index) {
IntObj* obj = new IntObj(to_add);
return int_arr->set(obj, index);
}
/**
* Clears the array and reinitializes the underlying array to 10 spots with no elements.
* Reinitializes the size to 0.
**/
void clear() {
int_arr->clear();
}
/**
* Resizing the underlying array. And then copying over the elements to a new array with
* the updated size.
* Default is doubling the array size when the max capacity of the
* underlying array less the number of elements is 2.
**/
void resize() {
int_arr->resize();
}
/**
* Returns the first index of the of given Object pointer.
* If the object pointer is not found then -1 is returned.
* @arg to_find Object to find the index of.
**/
int indexOf(int to_find) {
IntObj* to_find_obj = new IntObj(to_find);
int returning = int_arr->indexOf(to_find_obj);
delete to_find_obj;
return returning;
}
/**
* Adds the element provided to the end of the list.
* The size is incremented by 1. If resizing the array is necessary,
* then that should be done.
* @arg to_add int to be added to the array.
**/
void add(int to_add) {
IntObj* int_obj = new IntObj(to_add);
int_arr->add(int_obj);
}
/**
* Adds the provided array to the end of the list, unless the given array is NULL,
* then it will not be added.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects that all need to be added to this array.
**/
void addAll(IntArray* to_add) {
int_arr->addAll(to_add->int_arr);
}
/**
* Adds the provided int at the given index. All elements previously at the index and
* to the right will be shifted accordingly.
* If the index is invalid, then nothing will be added/shifted.
* The size of this array is incremented by 1.
* If resizing the array is necessary, then that should be done.
* @arg to_add Object to be added to the array
* @arg index Location to add the Object at
**/
void add(int to_add, size_t index) {
IntObj* int_obj = new IntObj(to_add);
int_arr->add(int_obj, index);
}
/**
* Adds all the elements of the provided array at the given index,
* unless the given array is NULL, then it will not be added. Otherwise,
* all elements previously at the index and
* to the right will be shifted accordingly by the size of the procided array,
* If the index is invalid, then nothing will be added/shifted.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects to be added to the array
* @arg index Location to add the objects to the array at
**/
void addAll(IntArray* to_add, size_t index) {
int_arr->addAll(to_add->int_arr, index);
}
/**
* Returns the subarray starting from the provided index to the end of the array.
* If the index is invalid, then the method returns NULL
* @arg index Starting place for the subarray
**/
IntArray* subArray(size_t index) {
IntArray* returning = new IntArray();
if (index > getSize()) {
return NULL;
}
while(index < getSize()) {
returning->add(get(index));
index += 1;
}
return returning;
}
/**
* Returns the subarray starting from the provided index to the ending index
* The starting index must always be greater than the ending index. If either index is invalid,
* then NULL is returned. The set is [start, end)
* @arg startIndex starting place for the subarray
* @arg endIndex location of the last object to be put in the subarray
**/
IntArray* subArray(size_t startIndex, size_t endIndex) {
IntArray* returning = new IntArray();
if (endIndex > getSize() || startIndex > endIndex) {
return NULL;
}
while(startIndex < getSize()) {
returning->add(get(startIndex));
startIndex += 1;
}
return returning;
}
/**
* Removes the first instance of the given int in this array. If nothing
* is found, then no action will occur. The size reduces by 1 if the
* element is found.
* @arg to_remove int to be removed from the array
**/
void remove(int to_remove) {
IntObj* int_obj = new IntObj(to_remove);
int_arr->remove(int_obj);
delete int_obj;
}
/**
* Removes all instances of the given int in this array. If nothing
* is found, then no action will occur. The size reduces the number of found
* elements there are.
* @arg to_remove int that all instances in the array will be removed of
**/
void removeAll(int to_remove) {
IntObj* int_obj = new IntObj(to_remove);
int_arr->removeAll(int_obj);
delete int_obj;
}
/**
* Returns number of elements in the array.
**/
size_t getSize() {
return int_arr->getSize();
}
/**
* Overriding the Object equals method.
* Returns if all the elements in this array and the given object are equal and
* in the same other.
* If the given object is NULL or not an array, then false will be returned.
* @arg other Object to check if this array is equal to
**/
bool equals(Object* other) {
IntArray* o = dynamic_cast<IntArray*> (other);
if (o)
return o->int_arr->equals(this->int_arr);
else {
return false;
}
}
/**
* Overriding the Object hash_me() method.
* Hashes the array based on user specifications. Default implementation is
* to hash all internal elements and sum them up.
**/
size_t hash_me_() {
return int_arr->hash_me_() + 2;
}
};
class FloatArray : public Object {
public:
Array* float_arr;
/**
* Default constructor which will set the initial max-capacity to the array to 10.
**/
FloatArray() {
float_arr = new Array();
};
/**
* Initalized this array with the characteristics of the passed in array.
* @arg arr Array containing values to be used in initialization.
**/
FloatArray(FloatArray* arr) {
float_arr = arr->float_arr;
}
/**
* Destructor which will free the memory of the underlying array as well.
**/
~FloatArray() {
delete float_arr;
}
/**
* Will return the float pointer at the provided index. if the index is invalid,
* then the method will return -1
* @arg index Location to get the value in the array at.
**/
float get(size_t index) {
Object* obj = float_arr->get(index);
if (obj) {
return static_cast <FloatObj*> (obj)->getFloat();
}
return NULL;
}
/**
* Clears the array and reinitializes the underlying array to 10 spots with no elements.
* Reinitializes the size to 0.
**/
void clear() {
float_arr->clear();
}
/**
* Resizing the underlying array. And then copying over the elements to a new array with
* the updated size.
* Default is doubling the array size when the max capacity of the
* underlying array less the number of elements is 2.
**/
void resize() {
float_arr->resize();
}
/**
* Returns the first index of the of given float pointer.
* If the object pointer is not found then -1 is returned.
* @arg to_find Object to find the index of.
**/
int indexOf(float to_find) {
FloatObj* to_find_obj = new FloatObj(to_find);
int returning = float_arr->indexOf(to_find_obj);
delete to_find_obj;
return returning;
}
/**
* Adds the element provided to the end of the list.
* The size is incremented by 1. If resizing the array is necessary,
* then that should be done.
* @arg to_add int to be added to the array.
**/
void add(float to_add) {
FloatObj* float_obj = new FloatObj(to_add);
float_arr->add(float_obj);
}
virtual void set(float to_add, size_t index) {
FloatObj* obj = new FloatObj(to_add);
float_arr->set(obj, index);
}
/**
* Adds the provided array to the end of the list, unless the given array is NULL,
* then it will not be added.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects that all need to be added to this array.
**/
void addAll(FloatArray* to_add) {
float_arr->addAll(to_add->float_arr);
}
/**
* Adds the provided float at the given index. All elements previously at the index and
* to the right will be shifted accordingly.
* If the index is invalid, then nothing will be added/shifted.
* The size of this array is incremented by 1.
* If resizing the array is necessary, then that should be done.
* @arg to_add Object to be added to the array
* @arg index Location to add the Object at
**/
void add(float to_add, size_t index) {
FloatObj* float_obj = new FloatObj(to_add);
float_arr->add(float_obj, index);
}
/**
* Adds all the elements of the provided array at the given index,
* unless the given array is NULL, then it will not be added. Otherwise,
* all elements previously at the index and
* to the right will be shifted accordingly by the size of the procided array,
* If the index is invalid, then nothing will be added/shifted.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects to be added to the array
* @arg index Location to add the objects to the array at
**/
void addAll(FloatArray* to_add, size_t index) {
float_arr->addAll(to_add->float_arr, index);
}
/**
* Returns the subarray starting from the provided index to the end of the array.
* If the index is invalid, then the method returns NULL
* @arg index Starting place for the subarray
**/
FloatArray* subArray(size_t index) {
FloatArray* returning = new FloatArray();
if (index > getSize()) {
return NULL;
}
while(index < getSize()) {
returning->add(get(index));
index += 1;
}
return returning;
}
/**
* Returns the subarray starting from the provided index to the ending index
* The starting index must always be greater than the ending index. If either index is invalid,
* then NULL is returned. The set is [start, end)
* @arg startIndex starting place for the subarray
* @arg endIndex location of the last object to be put in the subarray
**/
FloatArray* subArray(size_t startIndex, size_t endIndex) {
FloatArray* returning = new FloatArray();
if (endIndex > getSize() || startIndex > endIndex) {
return NULL;
}
while(startIndex < getSize()) {
returning->add(get(startIndex));
startIndex += 1;
}
return returning;
}
/**
* Removes the first instance of the given float in this array. If nothing
* is found, then no action will occur. The size reduces by 1 if the
* element is found.
* @arg to_remove float to be removed from the array
**/
void remove(float to_remove) {
FloatObj* float_obj = new FloatObj(to_remove);
float_arr->remove(float_obj);
delete float_obj;
}
/**
* Removes all instances of the given float in this array. If nothing
* is found, then no action will occur. The size reduces the number of found
* elements there are.
* @arg to_remove int that all instances in the array will be removed of
**/
void removeAll(float to_remove) {
FloatObj* float_obj = new FloatObj(to_remove);
float_arr->removeAll(float_obj);
delete float_obj;
}
/**
* Returns number of elements in the array.
**/
size_t getSize() {
return float_arr->getSize();
}
/**
* Overriding the Object equals method.
* Returns if all the elements in this array and the given object are equal and
* in the same other.
* If the given object is NULL or not an array, then false will be returned.
* @arg other Object to check if this array is equal to
**/
bool equals(Object* other) {
FloatArray* o = dynamic_cast<FloatArray*> (other);
if (o)
return o->float_arr->equals(this->float_arr);
else {
return false;
}
}
/**
* Overriding the Object hash_me() method.
* Hashes the array based on user specifications. Default implementation is
* to hash all internal elements and sum them up.
**/
size_t hash_me_() {
return float_arr->hash_me_() + 3;
}
};
class BoolArray : public Object {
public:
Array* bool_arr;
/**
* Default constructor which will set the initial max-capacity to the array to 10.
**/
BoolArray() {
bool_arr = new Array();
}
/**
* Initalized this array with the characteristics of the passed in array.
* @arg arr Array containing values to be used in initialization.
**/
BoolArray(BoolArray* arr) {
bool_arr = arr->bool_arr;
}
/**
* Destructor which will free the memory of the underlying array as well.
**/
~BoolArray() {
delete bool_arr;
}
/**
* Will return the bool at the provided index. if the index is invalid,
* then the method will return -1
* @arg index Location to get the value in the array at.
**/
bool get(size_t index) {
Object* obj = bool_arr->get(index);
if (obj) {
return static_cast <BoolObj*> (obj)->getBool();
}
else {
return NULL;
}
}
/**
* Clears the array and reinitializes the underlying array to 10 spots with no elements.
* Reinitializes the size to 0.
**/
void clear() {
bool_arr->clear();
}
/**
* Resizing the underlying array. And then copying over the elements to a new array with
* the updated size.
* Default is doubling the array size when the max capacity of the
* underlying array less the number of elements is 2.
**/
void resize() {
bool_arr->resize();
}
/**
* Returns the first index of the of given bool.
* If the object pointer is not found then -1 is returned.
* @arg to_find Object to find the index of.
**/
int indexOf(bool to_find) {
BoolObj* to_find_obj = new BoolObj(to_find);
int returning = bool_arr->indexOf(to_find_obj);
delete to_find_obj;
return returning;
}
/**
* Adds the element provided to the end of the list.
* The size is incremented by 1. If resizing the array is necessary,
* then that should be done.
* @arg to_add int to be added to the array.
**/
void add(bool to_add) {
BoolObj* bool_obj = new BoolObj(to_add);
bool_arr->add(bool_obj);
}
/**
* Adds the provided array to the end of the list, unless the given array is NULL,
* then it will not be added.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects that all need to be added to this array.
**/
void addAll(BoolArray* to_add) {
bool_arr->addAll(to_add->bool_arr);
}
virtual void set(bool to_add, size_t index) {
BoolObj* obj = new BoolObj(to_add);
return bool_arr->set(obj, index);
}
/**
* Adds the provided bool at the given index. All elements previously at the index and
* to the right will be shifted accordingly.
* If the index is invalid, then nothing will be added/shifted.
* The size of this array is incremented by 1.
* If resizing the array is necessary, then that should be done.
* @arg to_add Object to be added to the array
* @arg index Location to add the Object at
**/
void add(bool to_add, size_t index) {
BoolObj* bool_obj = new BoolObj(to_add);
bool_arr->add(bool_obj, index);
}
/**
* Adds all the elements of the provided array at the given index,
* unless the given array is NULL, then it will not be added. Otherwise,
* all elements previously at the index and
* to the right will be shifted accordingly by the size of the procided array,
* If the index is invalid, then nothing will be added/shifted.
* Assuming a valid move, the size of this array is incremented by the size of the
* added array. If resizing the array is necessary, then that should be done.
* @arg to_add Array of Objects to be added to the array
* @arg index Location to add the objects to the array at
**/
void addAll(BoolArray* to_add, size_t index) {
bool_arr->addAll(to_add->bool_arr, index);
}
/**
* Returns the subarray starting from the provided index to the end of the array.
* If the index is invalid, then the method returns NULL
* @arg index Starting place for the subarray
**/
BoolArray* subArray(size_t index) {
BoolArray* returning = new BoolArray();
if (index > getSize()) {
return NULL;
}
while(index < getSize()) {
returning->add(get(index));
index += 1;
}
return returning;
}
/**
* Returns the subarray starting from the provided index to the ending index
* The starting index must always be greater than the ending index. If either index is invalid,
* then NULL is returned. The set is [start, end)
* @arg startIndex starting place for the subarray
* @arg endIndex location of the last object to be put in the subarray
**/
BoolArray* subArray(size_t startIndex, size_t endIndex) {
BoolArray* returning = new BoolArray();
if (endIndex > getSize() || startIndex > endIndex) {
return NULL;
}
while(endIndex < getSize()) {
returning->add(get(startIndex));
startIndex += 1;
}
return returning;
}
/**
* Removes the first instance of the given bool in this array. If nothing
* is found, then no action will occur. The size reduces by 1 if the
* element is found.
* @arg to_remove float to be removed from the array
**/
void remove(bool to_remove) {
BoolObj* bool_obj = new BoolObj(to_remove);
bool_arr->remove(bool_obj);
delete bool_obj;
}
/**
* Removes all instances of the given bool in this array. If nothing
* is found, then no action will occur. The size reduces the number of found
* elements there are.
* @arg to_remove int that all instances in the array will be removed of
**/
void removeAll(bool to_remove) {
BoolObj* bool_obj = new BoolObj(to_remove);
bool_arr->removeAll(bool_obj);
delete bool_obj;
}
/**
* Returns number of elements in the array.
**/
size_t getSize() {
return bool_arr->getSize();
}
/**
* Overriding the Object equals method.
* Returns if all the elements in this array and the given object are equal and
* in the same other.
* If the given object is NULL or not an array, then false will be returned.
* @arg other Object to check if this array is equal to
**/
bool equals(Object* other) {
BoolArray* o = dynamic_cast<BoolArray*> (other);
if (o)
return o->bool_arr->equals(this->bool_arr);
else {
return false;
}
}
/**
* Overriding the Object hash_me() method.
* Hashes the array based on user specifications. Default implementation is
* to hash all internal elements and sum them up.
**/
size_t hash_me_() {
return bool_arr->hash_me_() + 4;
}
}; | true |
d13fd99a298b222da5fdd68810ea51b1b84bb11f | C++ | osmanuss/Programming | /Practice/36/C++/36.cpp | UTF-8 | 2,708 | 3.65625 | 4 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
const double PI = 3.141592653589793;
const double precision = 1e-10;
enum type
{
Cartesian,
Polar
};
class Point
{
private:
double x, y;
public:
Point(double a1 = 0, double a2 = 0, type coord_system = Cartesian)
{
if (coord_system == Cartesian)
{
x = a1;
y = a2;
return;
}
else
{
x = a1 * cos(a2);
y = a1 * sin(a2);
}
}
bool operator ==(const Point& second) const
{
return abs(x - second.x) < precision && abs(y - second.y) < precision;
}
bool operator !=(const Point& second) const
{
return !(*this == second);
}
double get_x() const
{
return x;
}
double get_y() const
{
return y;
}
double get_r() const
{
return sqrt(x * x + y * y);
}
double get_phi() const
{
return atan(y / x) + (x < 0 ? PI : 0);
}
void set_x(double x)
{
this->x = x;
}
void set_y(double y)
{
this->y = y;
}
void set_r(double r)
{
double phi = get_phi();
this->x = cos(phi) * r;
this->y = sin(phi) * r;
}
void set_phi(double phi)
{
double r = get_r();
this->x = cos(phi) * r;
this->y = sin(phi) * r;
}
};
std::ostream& operator <<(std::ostream& out, const Point& point)
{
return out << '(' << point.get_x() << ',' << point.get_y() << ')';
}
std::istream& operator >>(std::istream& in, Point& point)
{
double num;
in.ignore(1);
in >> num;
point.set_x(num);
in.ignore(1);
in >> num;
point.set_y(num);
in.ignore(1);
return in;
}
int main() {
std::vector<Point> original;
std::ifstream fin("data.txt");
if (!fin.is_open()) {
std::cout << "Can't open file" << std::endl;
return 1;
}
else {
while (!fin.eof()) {
Point p;
fin >> p;
fin.ignore(2); // Точки разделены двумя символами ", "
original.push_back(p);
}
fin.close();
}
std::vector<Point> simulacrum(original);
for (auto& p : simulacrum) {
std::cout << p;
p.set_x(p.get_x() + 10);
p.set_phi(p.get_phi() + 180 * PI / 180);
p.set_y(-p.get_y());
p.set_x(-p.get_x() - 10);
std::cout << p << std::endl;
}
if (std::equal(original.begin(), original.end(), simulacrum.begin()))
std::cout << "\nIt works!\n";
else
std::cout << "\nIt not works!\n";
} | true |
e655b7c684556e63375b3257aab9d24475ff6340 | C++ | zoq/VC4C | /src/normalization/AddressCalculation.h | UTF-8 | 5,538 | 2.609375 | 3 | [
"MIT"
] | permissive | /*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#ifndef VC4C_NORMALIZATION_ADDRESS_CALCULATION_H
#define VC4C_NORMALIZATION_ADDRESS_CALCULATION_H
#include "../InstructionWalker.h"
#include "../Values.h"
#include "../analysis/ValueRange.h"
#include "../intermediate/IntermediateInstruction.h"
#include "../performance.h"
namespace vc4c
{
namespace periphery
{
enum class VPMUsage : unsigned char;
} // namespace periphery
namespace normalization
{
/**
* Enum for the different ways of how to access memory areas
*/
enum class MemoryAccessType
{
// lower the value into a register and replace all loads with moves
QPU_REGISTER_READONLY,
// lower the value into a register and replace all loads/stores with moves
QPU_REGISTER_READWRITE,
// store in VPM in extra space per QPU!!
VPM_PER_QPU,
// store in VPM, QPUs share access to common data
VPM_SHARED_ACCESS,
// keep in RAM/global data segment, read via TMU
RAM_LOAD_TMU,
// keep in RAM/global data segment, access via VPM
RAM_READ_WRITE_VPM
};
struct MemoryAccess
{
FastSet<InstructionWalker> accessInstructions;
MemoryAccessType preferred;
MemoryAccessType fallback;
};
MemoryAccessType toMemoryAccessType(periphery::VPMUsage usage);
/*
* Converts an address (e.g. an index chain) and the corresponding base pointer to the pointer difference
*
* NOTE: The result itself is still in "memory-address mode", meaning the offset is the number of bytes
*
* Returns (char*)address - (char*)baseAddress
*/
NODISCARD InstructionWalker insertAddressToOffset(InstructionWalker it, Method& method, Value& out,
const Local* baseAddress, const intermediate::MemoryInstruction* mem, const Value& ptrValue);
/*
* Converts an address (e.g. an index-chain) and a base-address to the offset of the vector denoting the element
* accessed by the index-chain. In addition to #insertAddressToOffset, this function also handles multiple
* stack-frames.
*
* NOTE: The result is still the offset in bytes, since VPM#insertReadVPM and VPM#insertWriteVPM take the offset
* in bytes!
*
* Returns ((char*)address - (char*)baseAddress) + (typeSizeInBytes * stackIndex), where stackIndex is always
* zero (and therefore the second part omitted) for shared memory
*/
NODISCARD InstructionWalker insertAddressToStackOffset(InstructionWalker it, Method& method, Value& out,
const Local* baseAddress, MemoryAccessType type, const intermediate::MemoryInstruction* mem,
const Value& ptrValue);
/*
* Converts an address (e.g. index-chain) and the corresponding base-address to the element offset for an
* element of the type used in the container
*
* Return ((char*)address - (char*)baseAddress) / sizeof(elementType)
*/
NODISCARD InstructionWalker insertAddressToElementOffset(InstructionWalker it, Method& method, Value& out,
const Local* baseAddress, const Value& container, const intermediate::MemoryInstruction* mem,
const Value& ptrValue);
// represents analysis data for the range of memory accessed per memory object
struct MemoryAccessRange
{
const Local* memoryObject;
// the memory instruction accessing the memory object
InstructionWalker memoryInstruction;
// the instruction adding the offset to the base pointer
InstructionWalker baseAddressAdd;
// the instruction converting the address offset from element offset to byte offset
Optional<InstructionWalker> typeSizeShift;
// the work-group uniform parts of which the address offset is calculated from
FastMap<Value, intermediate::InstructionDecorations> groupUniformAddressParts;
// the dynamic parts (specific to the work-item) of which the address offset is calculated from
FastMap<Value, intermediate::InstructionDecorations> dynamicAddressParts;
// the maximum range (in elements!) the memory is accessed in
analysis::IntegerRange offsetRange{0, 0};
std::string to_string() const;
};
/*
* Converts an address (e.g. index-chain) which contains work-group uniform and work-item specific parts (as
* specified in range) to the work-item specific part only.
* This can be seen as a specialization of #insertAddressToOffset
*
* NOTE: The result itself is still in "memory-address mode", meaning the offset is the number of bytes
*
* * E.g. get_global_id(0) (= get_group_id(0) + get_local_id(0)) will be converted to get_local_id(0)
*/
NODISCARD InstructionWalker insertAddressToWorkItemSpecificOffset(
InstructionWalker it, Method& method, Value& out, MemoryAccessRange& range);
struct LocalUsageOrdering
{
bool operator()(const Local* l1, const Local* l2) const;
};
} /* namespace normalization */
} /* namespace vc4c */
#endif /* VC4C_NORMALIZATION_ADDRESS_CALCULATION_H */ | true |
01282c621cbd82756cf354f859b8208788371f93 | C++ | JamesDYX/BUAA_Complier_Design | /FinalProject/编译课程设计/编译课程设计/globalFunction.cpp | UTF-8 | 60,680 | 2.625 | 3 | [] | no_license | /*
** @author:止水清潇menghuanlater
** @date:2017-12-10
** @location:BUAA
*/
//数据段起始地址:0x10010000
#include "globalFunction.h"
#include <fstream>
#include <cstring>
#include <map>
#include "error.h"
#define TEMP_REGISTER 6 //$t4~$t9
static int labelCount = 0;//全局标签计数器
int tmpVarCount = 0;//全局临时变量计数器
static string funcName = "GLOBAL";//临时变量的所属域,当域发生变化,整个计数器重新洗牌
static int globalStrCount = 0;//全局字符串计数器
static unsigned strMemSize = 0;//字符串占据的大小
unsigned int paramSpBegin;//临时参数栈空间指针
unsigned int currentParamSp;//当前参数栈指针的地址
const int tempStackMax = 100;//设置临时参数栈最大为100字节(最多有25个参数)
const unsigned int dataBaseAddr = 0x10010000;//数据段起始地址
unsigned int returnValueSpace;//函数返回值存放点
unsigned int funcBeginAddr;//整体函数栈的起始地址(即全局数据区域起始地址)
const string tmpCodeToFileName = "tmpCode.txt";//中间代码输出文件
const string mipsCodeToFileName = "mips.asm";//最终汇编代码输出文件
const string op_tmpCodeToFileName = "op_tmpCode.txt";//优化后的中间代码输出文件
const string op_mipsCodeToFileName = "op_mips.asm";//优化后的汇编代码
extern vector<SymbolTableItem> globalSymbolTable;
extern vector<FourYuanItem> optimizeTmpCodeArr;//优化后的中间代码
vector<FourYuanItem> globalTmpCodeArr;//中间代码生成集合
extern map<string, string> varToRegisterMap;
vector<string> constStringSet;//程序需要打印的常量字符串集合,放在.data域
map<string, string> stringWithLabel;//字符串与伪指令标签
map<string, unsigned> maxTempOrderMap;//每个函数最大的临时变量编号
map<string, unsigned> op_maxTempOrderMap;//基于优化问题产生的
string generateLabel() {
labelCount++;
char x[10] = { '\0' };
sprintf(x, "%d", labelCount);
return ("Label" + string(x));
}
string generateVar() {
tmpVarCount++;
char x[10] = {'\0'};
sprintf(x,"%d",tmpVarCount);
return ("T" + string(x));
}
string generateStrLabel() {
globalStrCount++;
char x[10] = {'\0'};
sprintf(x,"%d",globalStrCount);
return ("String" + string(x));
}
//取消字符串中的转义字符,所有的\都加上一个\即可
void cancelEscapeChar(string & target) {
vector< unsigned int> indexSets;
for (unsigned int i = 0; i < target.size(); i++) {
if(target.at(i) == '\\'){
indexSets.push_back(i);
}
}
for (unsigned int i = 0; i < indexSets.size(); i++) {
target.insert(indexSets.at(i)+i,"\\");
}
}
bool isStringDigit(string target) {
for (unsigned i = 0; i < target.size(); i++) {
if (target.at(i) > '9' || target.at(i) < '0') {
return false;
}
}
return true;
}
int stringToInt(string target) {
int outcome = 0;
bool isMinus = false;
for (unsigned i = 0; i < target.size(); i++) {
if (i == 0 && target.at(i) == '-') {
isMinus = true;
continue;
}
if (target.at(i) < '0' || target.at(i) > '9')
break;
outcome = outcome * 10 + target.at(i) - '0';
}
return isMinus?(-outcome):outcome;
}
void turnToPostfixExp(vector<PostfixItem>tar, vector<PostfixItem> & obj) {
vector<PostfixItem> tmp;
if (tar.size() == 1) {
obj.push_back(tar.at(0));
return;
}
if (tar.size() > 0) {
PostfixItem t = tar.at(0);
if (t.type == CharType && (t.number == '+' || t.number == '-') && t.isNotOperator == false) {
if (t.number == '-') {
t.type = IntType;
t.number = 0;
tar.insert(tar.begin(),t);
}
else {
tar.erase(tar.begin());
}
}
}
for (unsigned int i = 0; i < tar.size(); i++) {
PostfixItem item = tar.at(i);
if (item.type == CharType) {
switch (item.number) {
case '+':
case '-':
if (item.isNotOperator) {
obj.push_back(item);
break;
}
while (tmp.size() != 0) {
obj.push_back(tmp.at(tmp.size()-1));
tmp.pop_back();
}
tmp.push_back(item);
break;
case '*':
case '/':
if (item.isNotOperator) {
obj.push_back(item);
break;
}
while (tmp.size() != 0) {
if (tmp.at(tmp.size() - 1).number == '*' || tmp.at(tmp.size() - 1).number == '/') {
obj.push_back(tmp.at(tmp.size() - 1));
tmp.pop_back();
}
else {
break;
}
}
tmp.push_back(item);
break;
default:obj.push_back(item);
}
}
else {
obj.push_back(item);
}
}
while (tmp.size() != 0) {
obj.push_back(tmp.at(tmp.size()-1));
tmp.pop_back();
}
}
//生成计算代码
string calculateExp(vector<PostfixItem> & tar, bool & isSure,ValueType & t,int & ret,int line,bool isCache,vector<FourYuanItem> & cache,string funcName) {
PostfixItem item,item1;
FourYuanItem item2;
string tmpVar;
isSure = false;
vector<PostfixItem> tmp;
if (tar.size() == 1) {
item = tar.at(0);
if (item.type == IntType) {
t = IntType;
ret = item.number;
isSure = true;
return "";
}
else if (item.type == CharType) {
t = CharType;
ret = item.number;
isSure = true;
return "";
}
else {
if (!item.isNotCharVar) {//是字符型变量
t = CharType;
}
else
t = IntType;
return item.str;
}
}
else {
t = IntType;
for (unsigned int i = 0; i < tar.size(); i++) {
item = tar.at(i);
if (item.type == CharType) {
char x[15] = { '\0' };
item2.type = AssignState;
item2.isTargetArr = item2.isLeftArr = false;
switch (item.number) {
case '+':
case '-': {
if (item.isNotOperator) {
tmp.push_back(item);
break;
}
if (tmp.size() > 1) {
bool isAbleDirect = true;
int leftDigit, rightDigit;
if (tmp.at(tmp.size() - 1).type == StringType) {
item2.right = tmp.at(tmp.size() - 1).str;
tmp.pop_back();
isAbleDirect = false;
}
else {
sprintf(x, "%d", tmp.at(tmp.size() - 1).number);
item2.right = x;
rightDigit = tmp.at(tmp.size() - 1).number;
tmp.pop_back();
}
memset(x, 0, 15);
if (tmp.at(tmp.size() - 1).type == StringType) {
item2.left = tmp.at(tmp.size() - 1).str;
tmp.pop_back();
isAbleDirect = false;
}
else {
sprintf(x, "%d", tmp.at(tmp.size() - 1).number);
item2.left = x;
leftDigit = tmp.at(tmp.size() - 1).number;
tmp.pop_back();
}
if (isAbleDirect) {
item1.type = IntType;
item1.number = (item.number == '+') ? (leftDigit + rightDigit) : (leftDigit - rightDigit);
tmp.push_back(item1);
break;
}
tmpVar = generateVar();
item2.target = tmpVar;
item2.op = item.number;
if (isCache) {
cache.push_back(item2);
}
else {
globalTmpCodeArr.push_back(item2);
}
item1.type = StringType;
item1.str = tmpVar;
tmp.push_back(item1);
}
break;
}
case '*':
case '/': {
if (item.isNotOperator) {
tmp.push_back(item);
break;
}
if (tmp.size() > 1) {
bool isAbleDirect = true;
int leftDigit, rightDigit;
if (tmp.at(tmp.size() - 1).type == StringType) {
item2.right = tmp.at(tmp.size() - 1).str;
isAbleDirect = false;
tmp.pop_back();
}
else {
sprintf(x, "%d", tmp.at(tmp.size() - 1).number);
item2.right = x;
rightDigit = tmp.at(tmp.size() - 1).number;
tmp.pop_back();
}
memset(x, 0, 15);
if (tmp.at(tmp.size() - 1).type == StringType) {
item2.left = tmp.at(tmp.size() - 1).str;
isAbleDirect = false;
tmp.pop_back();
}
else {
sprintf(x, "%d", tmp.at(tmp.size() - 1).number);
item2.left = x;
leftDigit = tmp.at(tmp.size() - 1).number;
tmp.pop_back();
if (item.number == '/' && item2.right == "0") {
cout << "Error(at line " << line << " surround): exist div 0 situation." << endl;
break;
}
}
if (isAbleDirect) {
item1.type = IntType;
item1.number = (item.number == '*') ? (leftDigit*rightDigit) : (leftDigit / rightDigit);
tmp.push_back(item1);
break;
}
tmpVar = generateVar();
item2.target = tmpVar;
item2.op = item.number;
if (isCache) {
cache.push_back(item2);
}
else {
globalTmpCodeArr.push_back(item2);
}
item1.type = StringType;
item1.str = tmpVar;
tmp.push_back(item1);
}
break;
}
default:tmp.push_back(item);
}
}
else {
tmp.push_back(item);
}
}
if (tmp.size() >= 1) {
if (tmp.at(0).type == IntType) {
isSure = true;
t = IntType;
ret = tmp.at(0).number;
return "";
}
return tmp.at(0).str;
}
else {
return "";
}
}
}
void writeTmpCodeToFile() {
maxTempOrderMap.clear();
constStringSet.clear();
stringWithLabel.clear();
ofstream out(tmpCodeToFileName, ios::out);
string funcName = "GLOBAL";
for (unsigned int i = 0; i < globalTmpCodeArr.size(); i++) {
FourYuanItem item = globalTmpCodeArr.at(i);
switch (item.type) {
case ValueParamDeliver:
out << "Push " << item.target << endl;
break;
case FunctionCall:
out << "Call " << item.target << endl;
break;
case AssignState:
if (item.isTargetArr) {
out << item.target << "[" << item.index1 << "] = ";
if (item.isLeftArr) {
out << item.left << "[" << item.index2 << "]" << endl;
}
else {
out << item.left << " " << item.op << " " << item.right << endl;
}
}
else {
//查询是否为临时变量
if (item.target.size() > 0 && item.target.at(0) == 'T') {
map<string, unsigned>::iterator iter = maxTempOrderMap.find(funcName);
unsigned order = stringToInt(item.target.substr(1));
if (iter == maxTempOrderMap.end()) {
maxTempOrderMap.insert(map<string,unsigned>::value_type(funcName,order));
}
else {
if (iter->second < order)
iter->second = order;
}
}
out << item.target << " = ";
if (item.isLeftArr) {
out << item.left << "[" << item.index2 << "]" << endl;
}
else {
out << item.left << " " << item.op << " " << item.right << endl;
}
}
break;
case Label:
out << item.target << ":" << endl;
break;
case FunctionDef:
funcName = item.target;
if (item.funcType == VoidType) {
out << "void " + item.target << "()" << endl;
}
else if (item.funcType == ReturnIntType) {
out << "int " + item.target << "()" << endl;
}else{
out << "char " + item.target << "()" << endl;
}
break;
case ParamDef:
if (item.valueType == IntType) {
out << "Param int " << item.target << endl;
}
else {
out << "Param char " << item.target << endl;
}
break;
case Jump:
out << "Jump " << item.target << endl;
break;
case BEZ:
out << "BEZ " << item.left << " " << item.target << endl;
break;
case BNZ:
out << "BNZ " << item.left << " " << item.target << endl;
break;
case BLZ:
out << "BLZ " << item.left << " " << item.target << endl;
break;
case BLEZ:
out << "BLEZ " << item.left << " " << item.target << endl;
break;
case BGZ:
out << "BGZ " << item.left << " " << item.target << endl;
break;
case BGEZ:
out << "BGEZ " << item.left << " " << item.target << endl;
break;
case ReadChar:
out << "Read Char " << item.target << endl;
break;
case ReadInt:
out << "Read Int " << item.target << endl;
break;
case PrintStr:
out << "Print string " << '\"'<< item.target <<'\"'<< endl;
cancelEscapeChar(item.target);
constStringSet.push_back(item.target);
break;
case PrintChar:
if (item.target == "\n") {
out << "New Line." << endl;
}else
out << "Print char " << '\'' << item.target.at(0) << '\'' << endl;
break;
case PrintInt:
out << "Print int " << stringToInt(item.target) << endl;
break;
case PrintId:
out << "Print id " << item.target << endl;
break;
case ReturnInt:
out << "Ret int " << stringToInt(item.target) << endl;
break;
case ReturnChar:
out << "Ret char " << '\'' << item.target.at(0) << '\'' << endl;
break;
case ReturnId:
out << "Ret id " << item.target << endl;
break;
case ReturnEmpty:
out << "Ret" << endl;
break;
default:break;
}
}
out.close();
}
//最终汇编代码生成相关的函数
void generateMipsCode() {
ofstream out(mipsCodeToFileName, ios::out);
//首先遍历生成.data的宏汇编伪指令
out << ".data" << endl;
generateData(out);
//修约strMemSize成为4的倍数
strMemSize = strMemSize + 4 - (strMemSize % 4);
//临时参数栈基址设置为strMemSize+4
paramSpBegin = strMemSize+4+dataBaseAddr;
currentParamSp = paramSpBegin;
returnValueSpace = strMemSize+dataBaseAddr;
funcBeginAddr = paramSpBegin + tempStackMax;
//生成.globl main
out << ".globl main" << endl;
//下面着重生成.text
out << ".text" << endl;
generateText(out);
out << "#accomplish generate mips code." << endl;
out.close();
}
//生成汇编Data段指令,最终地址需要给出,用于知道整个函数运行栈的开始点在哪
void generateData(ofstream & out) {
strMemSize = 0;
for (unsigned int i = 0; i < constStringSet.size(); i++) {
string item = constStringSet.at(i);
//检查是否是重复的公共字符串
map<string,string>::iterator iter = stringWithLabel.find(item);
if(iter!=stringWithLabel.end())
continue;
strMemSize += item.size() + 1;//'\0'占一个字节
string label = generateStrLabel();
out << "\t" << label << ":.asciiz \"" << item << "\"" << endl;
stringWithLabel.insert(map<string, string>::value_type(item, label));
}
}
//全局的变量
void getAddrOfGlobal(string name,string targetReg,ofstream & out) {
int number = 0;
unsigned int i;
for (i = 0; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() != Constant)
break;
}
for (; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getId() == name)
break;
if (item.getArrSize() == 0)
number += 4;
else
number += item.getArrSize() * 4;
}
out << "li " << targetReg << " " << funcBeginAddr + number <<endl;
}
//局部的变量
void getAddrOfLocal(string funcName,string eleName,string targetReg,ofstream & out) {
int number = 0;
unsigned int i;
for (i = 0; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() == Function && item.getId() == funcName)
break;
}
for (i = i + 1; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() == Constant)
continue;
if (item.getId() == eleName) {
break;
}
if (item.getArrSize() == 0)
number += 4;
else
number += item.getArrSize() * 4;
}
out << "addiu " << targetReg << " $fp " << number + 8 << endl;
}
//获取临时变量的地址
void getAddrOfTemp(int order, string targetReg,ofstream & out) {
//@need:order > TEMP_REGISTER
out << "move " << targetReg << " $k0" << endl;
out << "addiu " << targetReg << " " << targetReg << " " << (order-1-TEMP_REGISTER) * 4 << endl;
}
string _intToStr(int number) {
char x[10] = { '\0' };
sprintf_s(x, "%d", number);
return string(x);
}
//生成Text段代码的辅助函数
//赋值语句处理(优化了右操作数为0的运算)
void helpAssignStatement(FourYuanItem item,ofstream & out) {
//使用$t0~$t7
if (item.isTargetArr) {//a[i] = temp1
//首先最终赋值元素的地址放在$t0寄存器中,运算结果放在$t1寄存器
//数组型变量是以G+order+id的形式出现
int order = stringToInt(item.target.substr(1));
SymbolTableItem arrayItem = globalSymbolTable.at(order);
//数组首地址放在$t0中
if (arrayItem.getFuncName() == "GLOBAL") {//是全局的
getAddrOfGlobal(arrayItem.getId(),"$t0",out);
}
else {
getAddrOfLocal(arrayItem.getFuncName(),arrayItem.getId(),"$t0",out);
}
//观察index1即数组下标
string index1 = item.index1;
if (index1.at(0) == 'G') {//在符号表
order = stringToInt(index1.substr(1));
SymbolTableItem index1Item = globalSymbolTable.at(order);
//地址放在$t1
if (index1Item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(index1Item.getId(),"$t1",out);
}
else {
getAddrOfLocal(index1Item.getFuncName(),index1Item.getId(),"$t1",out);
}
//放在$t1
out << "lw $t1 0($t1)" << endl;//下标值存入$t1
}
else if (index1.at(0) == 'T') {//在临时变量表
//放在$t1
int g = stringToInt(index1.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3)<<endl;
}
}
else {//纯数字
int number = stringToInt(index1);
out << "li $t1 " << number<<endl;
}
out << "li $t2 4" << endl;
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
out << "addu $t0 $t0 $t1" << endl;//最终赋值元素地址存入了$t0
//结构决定了下面是left + right结构 --->运算结果存在$t1 left值放在$t1 right值放在$t2
string left = item.left;
string right = item.right;
char op = item.op;
if (left.at(0) == 'G') {//符号表
order = stringToInt(left.substr(1));
SymbolTableItem leftItem = globalSymbolTable.at(order);
if (leftItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(leftItem.getId(),"$t1",out);
}
else {
getAddrOfLocal(leftItem.getFuncName(),leftItem.getId(),"$t1",out);
}
out << "lw $t1 0($t1)" << endl;
}
else if (left.at(0) == 'T') {//临时变量表
int g = stringToInt(left.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3)<<endl;
}
}
else if (left == "Ret") {//函数调用的返回值
out << "lw $t1 " << returnValueSpace << "($0)" << endl;
}
else {//数字
out << "li $t1 " << stringToInt(left) << endl;
}
//右操作数为"0",不需要生成代码
if (right != "0") {
if (right.at(0) == 'G') {//符号表
order = stringToInt(right.substr(1));
SymbolTableItem rightItem = globalSymbolTable.at(order);
if (rightItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(rightItem.getId(),"$t2",out);
}
else {
getAddrOfLocal(rightItem.getFuncName(),rightItem.getId(),"$t2",out);
}
out << "lw $t2 0($t2)" << endl;
}
else if (right.at(0) == 'T') {//临时变量表
int g = stringToInt(right.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t1)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3)<<endl;
}
}
else {//数字
out << "li $t2 " << stringToInt(right) << endl;
}
if (op == '+') {
out << "addu $t1 $t1 $t2" << endl;
}
else if (op == '-') {
out << "subu $t1 $t1 $t2" << endl;
}
else if (op == '*') {
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
else if (op == '/') {
out << "div $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
}
else {
if (item.op == '*')
out << "move $t1 $0" << endl;
}
}
else{
//$t0存放target地址
bool isTemp = false;
int g, g1;
if (item.target.at(0) == 'G') {//符号表内的变量
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(),"$t0",out);
}
else {
getAddrOfLocal(item.getFuncName(),item.getId(),"$t0",out);
}
}
else if (item.target.at(0) == 'T') {//临时变量
g1 = g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(stringToInt(item.target.substr(1)), "$t0", out);
}
else {
isTemp = true;
}
}
//分析left
if (item.isLeftArr) {
//单纯的数组取值
string left = item.left;
int order = stringToInt(left.substr(1));
SymbolTableItem x = globalSymbolTable.at(order);
//分析索引下标,将数组地址取出放在$t1
if (x.getFuncName() == "GLOBAL") {
getAddrOfGlobal(x.getId(),"$t1",out);
}
else {
getAddrOfLocal(x.getFuncName(),x.getId(),"$t1",out);
}
//下标地址取出放在$t2
string index2 = item.index2;
if (index2.at(0) == 'G') {//在符号表
order = stringToInt(index2.substr(1));
SymbolTableItem index2Item = globalSymbolTable.at(order);
if (index2Item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(index2Item.getId(),"$t2",out);
}
else {
getAddrOfLocal(index2Item.getFuncName(),index2Item.getId(),"$t2",out);
}
out << "lw $t2 0($t2)" << endl;
}
else if (index2.at(0) == 'T') {//在临时变量表
g = stringToInt(index2.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t2)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3)<<endl;
}
}
else {//纯数字
out << "li $t2 " << stringToInt(index2) << endl;
}
out << "li $t3 4" << endl;
out << "mult $t2 $t3" << endl;
out << "mflo $t2" << endl;
out << "addu $t1 $t1 $t2" << endl;
//取出数据,放在$t1
out << "lw $t1 0($t1)" << endl;
}
else {
//左右操作数
int order;
string left = item.left;
string right = item.right;
char op = item.op;
if (left.at(0) == 'G') {//符号表
order = stringToInt(left.substr(1));
SymbolTableItem leftItem = globalSymbolTable.at(order);
if (leftItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(leftItem.getId(),"$t1",out);
}
else {
getAddrOfLocal(leftItem.getFuncName(),leftItem.getId(),"$t1",out);
}
out << "lw $t1 0($t1)" << endl;
}
else if (left.at(0) == 'T') {//临时变量表
g = stringToInt(left.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3)<<endl;
}
}
else if (left == "Ret") {//函数调用的返回值
out << "lw $t1 " << returnValueSpace << "($0)" << endl;
}
else {//数字
out << "li $t1 " << stringToInt(left) << endl;
}
if (right != "0") {
if (right.at(0) == 'G') {//符号表
order = stringToInt(right.substr(1));
SymbolTableItem rightItem = globalSymbolTable.at(order);
if (rightItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(rightItem.getId(), "$t2", out);
}
else {
getAddrOfLocal(rightItem.getFuncName(), rightItem.getId(), "$t2", out);
}
out << "lw $t2 0($t2)" << endl;
}
else if (right.at(0) == 'T') {//临时变量表
g = stringToInt(right.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t2)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3)<<endl;
}
}
else {//数字
out << "li $t2 " << stringToInt(right) << endl;
}
if (op == '+') {
out << "addu $t1 $t1 $t2" << endl;
}
else if (op == '-') {
out << "subu $t1 $t1 $t2" << endl;
}
else if (op == '*') {
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
else if (op == '/') {
out << "div $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
}
else {
if (item.op == '*')
out << "move $t1 $0" << endl;
}
}
if (isTemp) {
out << "move $t" << (g1 + 3) << " $t1" << endl;
return;
}
}
//从$t1将值存入内存
out << "sw $t1 0($t0)" << endl;
}
//函数定义处理(空间分配,数据保存等一系列操作)
int getGlobalVarSumSpace() {
int number = 0;
for (unsigned int i = 0; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() == Function)
break;
if (item.getItemType() == Constant)
continue;
if (item.getArrSize() == 0)
number += 4;
else
number += item.getArrSize() * 4;
}
return number;
}
void initializeStack(string funcName,ofstream & out) {
//参数计数器
int paramC = 0;
int number = 0;//变量不进行初始化
for (unsigned int i = 0; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() == Function && item.getId() == funcName) {
for (unsigned int j = i + 1; j < globalSymbolTable.size(); j++) {
item = globalSymbolTable.at(j);
if (item.getFuncName() != funcName)
break;
if (item.getItemType() == Constant)
continue;
if (item.getItemType() == Parament) {//是参数
//借用$v1寄存器作为中转
out << "lw $v1 " << paramSpBegin + paramC * 4 << "($0)" << endl;
string lala = "G" + _intToStr(item.getOrder()) + item.getId();
map<string, string>::iterator itr = varToRegisterMap.find(lala);
if (itr != varToRegisterMap.end()) {
out << "move " << itr->second << " $v1" << endl;
}
else {
out << "sw $v1 0($sp)" << endl;
}
paramC++;
out << "addiu $sp $sp 4" << endl;
}
else if (item.getItemType() == Variable) {
if (item.getArrSize() == 0) {
number += 4;
}
else {
number += 4 * item.getArrSize();
}
}
}
break;
}
}
out << "addiu $sp $sp " << number << endl;
//临时变量区入口地址确定,存放入$k0
out << "move $k0 $sp" << endl;
out << "move $k1 $0 " << endl;
//分配所需最大的临时空间
map<string, unsigned>::iterator iter = maxTempOrderMap.find(funcName);
if (iter != maxTempOrderMap.end()) {
if(iter->second>TEMP_REGISTER)
out << "addiu $sp $sp " << (iter->second - TEMP_REGISTER) * 4<< endl;
out << "addiu $k1 $0 " << iter->second << endl;
}
}
void helpFunctionDef(string funcName, ofstream & out) {
if (funcName == "main") {
//main函数只需要做全局变量的数据分配
int size = getGlobalVarSumSpace();
out << "li $fp " << funcBeginAddr + size << endl;
out << "addiu $sp $fp 8" << endl;
initializeStack(funcName,out);
}
else {
//将$k0,$k1寄存器的值保存入栈
out << "sw $k0 0($sp)" << endl;
out << "sw $k1 4($sp)" << endl;
out << "sw $t4 8($sp)" << endl;
out << "sw $t5 12($sp)" << endl;
out << "sw $t6 16($sp)" << endl;
out << "sw $t7 20($sp)" << endl;
out << "sw $t8 24($sp)" << endl;
out << "sw $t9 28($sp)" << endl;
out << "addiu $sp $sp 32" << endl;
//设置上一级函数的基地址
out << "sw $fp 4($sp)" << endl;
//设置fp
out << "move $fp $sp" << endl;
//设置返回地址
out << "sw $ra 0($fp)" << endl;
//初始化栈空间
out << "addiu $sp $fp 8" << endl;
initializeStack(funcName,out);
}
}
//跳转语句B类统一处理,避免代码过度杂糅重复
void helpBJump(FourYuanItem item,ofstream & out) {
//把判断的变量值存入$a1寄存器中,再调用转移函数
string obj = item.left;
if (obj.at(0) == 'G') {
int order = stringToInt(obj.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(),"$a1",out);
}
else {
getAddrOfLocal(item.getFuncName(),item.getId(), "$a1", out);
}
out << "lw $a1 0($a1)" << endl;
}
else if (obj.at(0) == 'T') {
int g = stringToInt(obj.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a1", out);
out << "lw $a1 0($a1)" << endl;
}
else {
out << "move $a1 " << "$t" << (g + 3) << endl;
}
}
switch (item.type)
{
case BEZ:
out << "beq $a1 $0 " << item.target << endl;
break;
case BNZ:
out << "bne $a1 $0 " << item.target << endl;
break;
case BLZ:
out << "bltz $a1 " << item.target << endl;
break;
case BLEZ:
out << "blez $a1 " << item.target << endl;
break;
case BGZ:
out << "bgtz $a1 " << item.target << endl;
break;
case BGEZ:
out << "bgez $a1 " << item.target << endl;
break;
default:
break;
}
}
//函数返回处理
void helpReturn(ofstream & out) {
//栈指针恢复到$fp
out << "move $sp $fp" << endl;
//$k0 $k1寄存器值恢复
out << "lw $t9 -4($sp)" << endl;
out << "lw $t8 -8($sp)" << endl;
out << "lw $t7 -12($sp)" << endl;
out << "lw $t6 -16($sp)" << endl;
out << "lw $t5 -20($sp)" << endl;
out << "lw $t4 -24($sp)" << endl;
out << "lw $k1 -28($sp)" << endl;
out << "lw $k0 -32($sp)" << endl;
out << "addiu $sp $sp -32" << endl;
//返回地址存入$ra
out << "lw $ra 0($fp)" << endl;
//函数栈区起始地址恢复--->上一级函数基地址$fp恢复
out << "lw $fp 4($fp)" << endl;
//执行jr
out << "jr $ra" << endl;
}
//生成最终的Text段代码
void generateText(ofstream & out) {
for (unsigned int i = 0; i < globalTmpCodeArr.size(); i++) {
FourYuanItem item = globalTmpCodeArr.at(i);
switch (item.type) {
case ValueParamDeliver:
//push对应的全部都是变量,取地址
//首先看push的符号表里面的还是临时生成的变量
if (item.target.at(0) == 'G') {//符号表内
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(),"$a2",out);
}
else {
getAddrOfLocal(item.getFuncName(),item.getId(), "$a2", out);
}
out << "lw $a2 0($a2)" << endl;
}
else {//临时变量
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a2", out);
out << "lw $a2 0($a2)" << endl;
}
else {
out << "move $a2 " << "$t" << (g + 3) << endl;
}
}
out << "sw $a2 " << currentParamSp << "($0)" << endl;
currentParamSp += 4;
break;
case FunctionCall:
currentParamSp = paramSpBegin;//回到起点
//函数调用,跳转,生成所跳转的目标函数运行栈空间的首地址
out << "jal " << item.target<<endl;//此时mars运行会将返回地址写入到$ra寄存器(函数执行时需要保存它)
break;
case AssignState:
helpAssignStatement(item,out);
break;
case Label:
out << item.target << ":" << endl;
break;
case FunctionDef:
//函数定义要处理的大问题
out << item.target << ":" << endl;//生成跳转标签
helpFunctionDef(item.target,out);
break;
case ParamDef:
//忽略处理,因为已经通过符号表在函数定义处处理了变量、参数的空间分配与地址分配
break;
case Jump:
out << "j " << item.target << endl;
break;
case BEZ:
case BNZ:
case BLZ:
case BLEZ:
case BGZ:
case BGEZ:
helpBJump(item,out);
break;
case ReadChar:
case ReadInt:{
if(item.type == ReadChar)
out << "li $v0 12" << endl;
else
out << "li $v0 5" << endl;
out << "syscall" << endl;
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$a3", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$a3", out);
}
out << "sw $v0 0($a3)" << endl;
break;
}
case PrintStr: {
cancelEscapeChar(item.target);
map<string, string>::iterator iter = stringWithLabel.find(item.target);
if (iter != stringWithLabel.end()) {
out << "la $a0 " << iter->second << endl;
}
out << "li $v0 4" << endl;
out << "syscall" << endl;
break;
}
case PrintChar:
out << "li $a0 " << (int)item.target.at(0) << endl;
out << "li $v0 11" << endl;
out << "syscall" << endl;
break;
case PrintInt:
out << "li $a0 " << stringToInt(item.target) << endl;
out << "li $v0 1" << endl;
out << "syscall" << endl;
break;
case PrintId: {
//判断是打印int还是char
if (item.target.at(0) == 'G') {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(),"$a0",out);
}
else {
getAddrOfLocal(item.getFuncName(),item.getId(), "$a0", out);
}
out << "lw $a0 0($a0)" << endl;
}
else if (item.target.at(0) == 'T') {
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a0", out);
out << "lw $a0 0($a0)" << endl;
}
else {
out << "move $a0 " << "$t" << (g + 3) << endl;
}
}
if (!item.isNotPrintCharId)
out << "li $v0 11" << endl;
else
out << "li $v0 1" << endl;
out << "syscall" << endl;
break;
}
case ReturnInt:
case ReturnChar:
out << "li $v0 " << stringToInt(item.target) << endl;
out << "sw $v0 " << returnValueSpace << "($0)" << endl;
//返回地址
helpReturn(out);
break;
case ReturnId: {
if (item.target.at(0) == 'G') {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$v0", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$v0", out);
}
out << "lw $v0 0($v0)" << endl;
}
else if (item.target.at(0) == 'T') {
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$v0", out);
out << "lw $v0 0($v0)" << endl;
}
else {
out << "move $v0 " << "$t" << (g + 3) << endl;
}
}
out << "sw $v0 " << returnValueSpace << "($0)" << endl;
//返回地址
helpReturn(out);
break;
}
case ReturnEmpty:
//返回地址
helpReturn(out);
break;
case OverProcedure:
out << "li $v0 10" << endl;
out << "syscall" << endl;
default:break;
}
}
}
//优化部分的生成代码
void op_writeTmpCodeToFile() {
op_maxTempOrderMap.clear();
constStringSet.clear();
stringWithLabel.clear();
ofstream out(op_tmpCodeToFileName, ios::out);
string funcName = "GLOBAL";
for (unsigned int i = 0; i < optimizeTmpCodeArr.size(); i++) {
FourYuanItem item = optimizeTmpCodeArr.at(i);
switch (item.type) {
case ValueParamDeliver:
out << "Push " << item.target << endl;
break;
case FunctionCall:
out << "Call " << item.target << endl;
break;
case AssignState:
if (item.isTargetArr) {
out << item.target << "[" << item.index1 << "] = ";
if (item.isLeftArr) {
out << item.left << "[" << item.index2 << "]" << endl;
}
else {
out << item.left << " " << item.op << " " << item.right << endl;
}
}
else {
//查询是否为临时变量
if (item.target.size() > 0 && item.target.at(0) == 'T') {
map<string, unsigned>::iterator iter = op_maxTempOrderMap.find(funcName);
unsigned order = stringToInt(item.target.substr(1));
if (iter == op_maxTempOrderMap.end()) {
op_maxTempOrderMap.insert(map<string, unsigned>::value_type(funcName, order));
}
else {
if (iter->second < order)
iter->second = order;
}
}
out << item.target << " = ";
if (item.isLeftArr) {
out << item.left << "[" << item.index2 << "]" << endl;
}
else {
out << item.left << " " << item.op << " " << item.right << endl;
}
}
break;
case Label:
out << item.target << ":" << endl;
break;
case FunctionDef:
funcName = item.target;
if (item.funcType == VoidType) {
out << "void " + item.target << "()" << endl;
}
else if (item.funcType == ReturnIntType) {
out << "int " + item.target << "()" << endl;
}
else {
out << "char " + item.target << "()" << endl;
}
break;
case ParamDef:
if (item.valueType == IntType) {
out << "Param int " << item.target << endl;
}
else {
out << "Param char " << item.target << endl;
}
break;
case Jump:
out << "Jump " << item.target << endl;
break;
case BEZ:
out << "BEZ " << item.left << " " << item.target << endl;
break;
case BNZ:
out << "BNZ " << item.left << " " << item.target << endl;
break;
case BLZ:
out << "BLZ " << item.left << " " << item.target << endl;
break;
case BLEZ:
out << "BLEZ " << item.left << " " << item.target << endl;
break;
case BGZ:
out << "BGZ " << item.left << " " << item.target << endl;
break;
case BGEZ:
out << "BGEZ " << item.left << " " << item.target << endl;
break;
case ReadChar:
out << "Read Char " << item.target << endl;
break;
case ReadInt:
out << "Read Int " << item.target << endl;
break;
case PrintStr:
out << "Print string " << '\"' << item.target << '\"' << endl;
cancelEscapeChar(item.target);
constStringSet.push_back(item.target);
break;
case PrintChar:
if (item.target == "\n") {
out << "New Line." << endl;
}
else
out << "Print char " << '\'' << item.target.at(0) << '\'' << endl;
break;
case PrintInt:
out << "Print int " << stringToInt(item.target) << endl;
break;
case PrintId:
out << "Print id " << item.target << endl;
break;
case ReturnInt:
out << "Ret int " << stringToInt(item.target) << endl;
break;
case ReturnChar:
out << "Ret char " << '\'' << item.target.at(0) << '\'' << endl;
break;
case ReturnId:
out << "Ret id " << item.target << endl;
break;
case ReturnEmpty:
out << "Ret" << endl;
break;
default:break;
}
}
out.close();
}
void op_initializeStack(string funcName, ofstream & out) {
//参数计数器
int paramC = 0;
int number = 0;//变量不进行初始化
for (unsigned int i = 0; i < globalSymbolTable.size(); i++) {
SymbolTableItem item = globalSymbolTable.at(i);
if (item.getItemType() == Function && item.getId() == funcName) {
for (unsigned int j = i + 1; j < globalSymbolTable.size(); j++) {
item = globalSymbolTable.at(j);
if (item.getFuncName() != funcName)
break;
if (item.getItemType() == Constant)
continue;
if (item.getItemType() == Parament) {//是参数
//借用$v1寄存器作为中转
out << "lw $v1 " << paramSpBegin + paramC * 4 << "($0)" << endl;
out << "sw $v1 0($sp)" << endl;
paramC++;
out << "addiu $sp $sp 4" << endl;
}
else if (item.getItemType() == Variable) {
if (item.getArrSize() == 0) {
number += 4;
}
else {
number += 4 * item.getArrSize();
}
}
}
break;
}
}
out << "addiu $sp $sp " << number << endl;
//临时变量区入口地址确定,存放入$k0
out << "move $k0 $sp" << endl;
out << "move $k1 $0 " << endl;
//分配所需最大的临时空间
map<string, unsigned>::iterator iter = op_maxTempOrderMap.find(funcName);
if (iter != op_maxTempOrderMap.end()) {
if (iter->second>TEMP_REGISTER)
out << "addiu $sp $sp " << (iter->second - TEMP_REGISTER) * 4 << endl;
out << "addiu $k1 $0 " << iter->second << endl;
}
}
void op_helpAssignStatement(FourYuanItem item, ofstream & out) {
//使用$t0~$t7
if (item.isTargetArr) {//a[i] = temp1
//首先最终赋值元素的地址放在$t0寄存器中,运算结果放在$t1寄存器
//数组型变量是以G+order+id的形式出现
int order = stringToInt(item.target.substr(1));
SymbolTableItem arrayItem = globalSymbolTable.at(order);
//数组首地址放在$t0中
if (arrayItem.getFuncName() == "GLOBAL") {//是全局的
getAddrOfGlobal(arrayItem.getId(), "$t0", out);
}
else {
getAddrOfLocal(arrayItem.getFuncName(), arrayItem.getId(), "$t0", out);
}
//观察index1即数组下标
string index1 = item.index1;
if (index1.at(0) == 'G') {//在符号表
map<string, string>::iterator myItr = varToRegisterMap.find(index1);
if (myItr != varToRegisterMap.end()) {
out << "move $t1 " << myItr->second << endl;
}
else {
order = stringToInt(index1.substr(1));
SymbolTableItem index1Item = globalSymbolTable.at(order);
//地址放在$t1
if (index1Item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(index1Item.getId(), "$t1", out);
}
else {
getAddrOfLocal(index1Item.getFuncName(), index1Item.getId(), "$t1", out);
}
//放在$t1
out << "lw $t1 0($t1)" << endl;//下标值存入$t1
}
}
else if (index1.at(0) == 'T') {//在临时变量表
//放在$t1
int g = stringToInt(index1.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3) << endl;
}
}
else {//纯数字
int number = stringToInt(index1);
out << "li $t1 " << number << endl;
}
out << "li $t2 4" << endl;
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
out << "addu $t0 $t0 $t1" << endl;//最终赋值元素地址存入了$t0
//结构决定了下面是left + right结构 --->运算结果存在$t1 left值放在$t1 right值放在$t2
string left = item.left;
string right = item.right;
char op = item.op;
if (left.at(0) == 'G') {//符号表
map<string, string>::iterator myItr = varToRegisterMap.find(left);
if (myItr != varToRegisterMap.end()) {
out << "move $t1 " << myItr->second << endl;
}
else {
order = stringToInt(left.substr(1));
SymbolTableItem leftItem = globalSymbolTable.at(order);
if (leftItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(leftItem.getId(), "$t1", out);
}
else {
getAddrOfLocal(leftItem.getFuncName(), leftItem.getId(), "$t1", out);
}
out << "lw $t1 0($t1)" << endl;
}
}
else if (left.at(0) == 'T') {//临时变量表
int g = stringToInt(left.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3) << endl;
}
}
else if (left == "Ret") {//函数调用的返回值
out << "lw $t1 " << returnValueSpace << "($0)" << endl;
}
else {//数字
out << "li $t1 " << stringToInt(left) << endl;
}
//右操作数为"0",不需要生成代码
if (right != "0") {
if (right.at(0) == 'G') {//符号表
map<string, string>::iterator myItr = varToRegisterMap.find(right);
if (myItr != varToRegisterMap.end()) {
out << "move $t2 " << myItr->second << endl;
}
else {
order = stringToInt(right.substr(1));
SymbolTableItem rightItem = globalSymbolTable.at(order);
if (rightItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(rightItem.getId(), "$t2", out);
}
else {
getAddrOfLocal(rightItem.getFuncName(), rightItem.getId(), "$t2", out);
}
out << "lw $t2 0($t2)" << endl;
}
}
else if (right.at(0) == 'T') {//临时变量表
int g = stringToInt(right.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t1)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3) << endl;
}
}
else {//数字
out << "li $t2 " << stringToInt(right) << endl;
}
if (op == '+') {
out << "addu $t1 $t1 $t2" << endl;
}
else if (op == '-') {
out << "subu $t1 $t1 $t2" << endl;
}
else if (op == '*') {
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
else if (op == '/') {
out << "div $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
}
else {
if (item.op == '*')
out << "move $t1 $0" << endl;
}
}
else {
//$t0存放target地址
bool isTemp = false;
bool isReg = false;
int g, g1;
string targetReg;
if (item.target.at(0) == 'G') {//符号表内的变量
map<string, string>::iterator myItr = varToRegisterMap.find(item.target);
if (myItr != varToRegisterMap.end()) {
targetReg = myItr->second;
isReg = true;
}
else {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$t0", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$t0", out);
}
}
}
else if (item.target.at(0) == 'T') {//临时变量
g1 = g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(stringToInt(item.target.substr(1)), "$t0", out);
}
else {
isTemp = true;
}
}
//分析left
if (item.isLeftArr) {
//单纯的数组取值
string left = item.left;
int order = stringToInt(left.substr(1));
SymbolTableItem x = globalSymbolTable.at(order);
//分析索引下标,将数组地址取出放在$t1
if (x.getFuncName() == "GLOBAL") {
getAddrOfGlobal(x.getId(), "$t1", out);
}
else {
getAddrOfLocal(x.getFuncName(), x.getId(), "$t1", out);
}
//下标地址取出放在$t2
string index2 = item.index2;
if (index2.at(0) == 'G') {//在符号表
map<string, string>::iterator myItr = varToRegisterMap.find(index2);
if (myItr != varToRegisterMap.end()) {
out << "move $t2 " << myItr->second << endl;
}
else {
order = stringToInt(index2.substr(1));
SymbolTableItem index2Item = globalSymbolTable.at(order);
if (index2Item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(index2Item.getId(), "$t2", out);
}
else {
getAddrOfLocal(index2Item.getFuncName(), index2Item.getId(), "$t2", out);
}
out << "lw $t2 0($t2)" << endl;
}
}
else if (index2.at(0) == 'T') {//在临时变量表
g = stringToInt(index2.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t2)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3) << endl;
}
}
else {//纯数字
out << "li $t2 " << stringToInt(index2) << endl;
}
out << "li $t3 4" << endl;
out << "mult $t2 $t3" << endl;
out << "mflo $t2" << endl;
out << "addu $t1 $t1 $t2" << endl;
//取出数据,放在$t1
out << "lw $t1 0($t1)" << endl;
}
else {
//左右操作数
int order;
string left = item.left;
string right = item.right;
char op = item.op;
if (left.at(0) == 'G') {//符号表
map<string, string>::iterator myItr = varToRegisterMap.find(left);
if (myItr != varToRegisterMap.end()) {
out << "move $t1 " << myItr->second << endl;
}
else {
order = stringToInt(left.substr(1));
SymbolTableItem leftItem = globalSymbolTable.at(order);
if (leftItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(leftItem.getId(), "$t1", out);
}
else {
getAddrOfLocal(leftItem.getFuncName(), leftItem.getId(), "$t1", out);
}
out << "lw $t1 0($t1)" << endl;
}
}
else if (left.at(0) == 'T') {//临时变量表
g = stringToInt(left.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t1", out);
out << "lw $t1 0($t1)" << endl;
}
else {
out << "move $t1 " << "$t" << (g + 3) << endl;
}
}
else if (left == "Ret") {//函数调用的返回值
out << "lw $t1 " << returnValueSpace << "($0)" << endl;
}
else {//数字
out << "li $t1 " << stringToInt(left) << endl;
}
if (right != "0") {
if (right.at(0) == 'G') {//符号表
map<string, string>::iterator myItr = varToRegisterMap.find(right);
if (myItr != varToRegisterMap.end()) {
out << "move $t2 " << myItr->second << endl;
}
else {
order = stringToInt(right.substr(1));
SymbolTableItem rightItem = globalSymbolTable.at(order);
if (rightItem.getFuncName() == "GLOBAL") {
getAddrOfGlobal(rightItem.getId(), "$t2", out);
}
else {
getAddrOfLocal(rightItem.getFuncName(), rightItem.getId(), "$t2", out);
}
out << "lw $t2 0($t2)" << endl;
}
}
else if (right.at(0) == 'T') {//临时变量表
g = stringToInt(right.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$t2", out);
out << "lw $t2 0($t2)" << endl;
}
else {
out << "move $t2 " << "$t" << (g + 3) << endl;
}
}
else {//数字
out << "li $t2 " << stringToInt(right) << endl;
}
if (op == '+') {
out << "addu $t1 $t1 $t2" << endl;
}
else if (op == '-') {
out << "subu $t1 $t1 $t2" << endl;
}
else if (op == '*') {
out << "mult $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
else if (op == '/') {
out << "div $t1 $t2" << endl;
out << "mflo $t1" << endl;
}
}
else {
if (item.op == '*')
out << "move $t1 $0" << endl;
}
}
if (isTemp) {
out << "move $t" << (g1 + 3) << " $t1" << endl;
return;
}
if (isReg) {
out << "move " << targetReg << " $t1" << endl;
return;
}
}
//从$t1将值存入内存
out << "sw $t1 0($t0)" << endl;
}
void op_helpFunctionDef(string funcName, ofstream & out) {
if (funcName == "main") {
//main函数只需要做全局变量的数据分配
int size = getGlobalVarSumSpace();
out << "li $fp " << funcBeginAddr + size << endl;
out << "addiu $sp $fp 8" << endl;
op_initializeStack(funcName, out);
}
else {
//将$k0,$k1寄存器的值保存入栈
out << "sw $k0 0($sp)" << endl;
out << "sw $k1 4($sp)" << endl;
out << "sw $t4 8($sp)" << endl;
out << "sw $t5 12($sp)" << endl;
out << "sw $t6 16($sp)" << endl;
out << "sw $t7 20($sp)" << endl;
out << "sw $t8 24($sp)" << endl;
out << "sw $t9 28($sp)" << endl;
out << "sw $s0 32($sp)" << endl;
out << "sw $s1 36($sp)" << endl;
out << "sw $s2 40($sp)" << endl;
out << "sw $s3 44($sp)" << endl;
out << "sw $s4 48($sp)" << endl;
out << "sw $s5 52($sp)" << endl;
out << "sw $s6 56($sp)" << endl;
out << "sw $s7 60($sp)" << endl;
out << "addiu $sp $sp 64" << endl;
//设置上一级函数的基地址
out << "sw $fp 4($sp)" << endl;
//设置fp
out << "move $fp $sp" << endl;
//设置返回地址
out << "sw $ra 0($fp)" << endl;
//初始化栈空间
out << "addiu $sp $fp 8" << endl;
initializeStack(funcName, out);
}
}
void op_helpBJump(FourYuanItem item, ofstream & out) {
//把判断的变量值存入$a1寄存器中,再调用转移函数
string obj = item.left;
map<string, string>::iterator myItr = varToRegisterMap.find(obj);
if (myItr != varToRegisterMap.end()) {
out << "addu $a1 " << myItr->second << " $0" << endl;
}
else {
if (obj.at(0) == 'G') {
int order = stringToInt(obj.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$a1", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$a1", out);
}
out << "lw $a1 0($a1)" << endl;
}
else if (obj.at(0) == 'T') {
int g = stringToInt(obj.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a1", out);
out << "lw $a1 0($a1)" << endl;
}
else {
out << "move $a1 " << "$t" << (g + 3) << endl;
}
}
}
switch (item.type)
{
case BEZ:
out << "beq $a1 $0 " << item.target << endl;
break;
case BNZ:
out << "bne $a1 $0 " << item.target << endl;
break;
case BLZ:
out << "bltz $a1 " << item.target << endl;
break;
case BLEZ:
out << "blez $a1 " << item.target << endl;
break;
case BGZ:
out << "bgtz $a1 " << item.target << endl;
break;
case BGEZ:
out << "bgez $a1 " << item.target << endl;
break;
default:
break;
}
}
void op_helpReturn(ofstream & out,string funcName) {
//栈指针恢复到$fp
out << "move $sp $fp" << endl;
//$k0 $k1 t4~t9 s0~s7寄存器值恢复,根据函数情况而定
//顶层放s0~s7
out << "lw $s7 -4($sp)" << endl;
out << "lw $s6 -8($sp)" << endl;
out << "lw $s5 -12($sp)" << endl;
out << "lw $s4 -16($sp)" << endl;
out << "lw $s3 -20($sp)" << endl;
out << "lw $s2 -24($sp)" << endl;
out << "lw $s1 -28($sp)" << endl;
out << "lw $s0 -32($sp)" << endl;
out << "lw $t9 -36($sp)" << endl;
out << "lw $t8 -40($sp)" << endl;
out << "lw $t7 -44($sp)" << endl;
out << "lw $t6 -48($sp)" << endl;
out << "lw $t5 -52($sp)" << endl;
out << "lw $t4 -56($sp)" << endl;
out << "lw $k1 -60($sp)" << endl;
out << "lw $k0 -64($sp)" << endl;
out << "addiu $sp $sp -64"<< endl;
//返回地址存入$ra
out << "lw $ra 0($fp)" << endl;
//函数栈区起始地址恢复--->上一级函数基地址$fp恢复
out << "lw $fp 4($fp)" << endl;
//执行jr
out << "jr $ra" << endl;
}
void op_generateMipsCode() {
ofstream out(op_mipsCodeToFileName, ios::out);
//首先遍历生成.data的宏汇编伪指令
out << ".data" << endl;
generateData(out);
//修约strMemSize成为4的倍数
strMemSize = strMemSize + 4 - (strMemSize % 4);
//临时参数栈基址设置为strMemSize+4
paramSpBegin = strMemSize + 4 + dataBaseAddr;
currentParamSp = paramSpBegin;
returnValueSpace = strMemSize + dataBaseAddr;
funcBeginAddr = paramSpBegin + tempStackMax;
//生成.globl main
out << ".globl main" << endl;
//下面着重生成.text
out << ".text" << endl;
op_generateText(out);
out << "#accomplish generate mips code." << endl;
out.close();
}
void op_generateText(ofstream & out) {
string funcName = "GLOBAL";
for (unsigned int i = 0; i < optimizeTmpCodeArr.size(); i++) {
FourYuanItem item = optimizeTmpCodeArr.at(i);
map<string, string>::iterator myItr;
switch (item.type) {
case ValueParamDeliver:
//push,检擦是否在全局寄存器
myItr = varToRegisterMap.find(item.target);
if (myItr != varToRegisterMap.end()) {
out << "sw " << myItr->second << " " << currentParamSp << "($0)" << endl;
currentParamSp += 4;
break;
}
if (item.target.at(0) == 'G') {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$a2", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$a2", out);
}
out << "lw $a2 0($a2)" << endl;
}
else {//临时变量
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a2", out);
out << "lw $a2 0($a2)" << endl;
}
else {
out << "move $a2 " << "$t" << (g + 3) << endl;
}
}
out << "sw $a2 " << currentParamSp << "($0)" << endl;
currentParamSp += 4;
break;
case FunctionCall:
currentParamSp = paramSpBegin;//回到起点
//函数调用,跳转,生成所跳转的目标函数运行栈空间的首地址
out << "jal " << item.target << endl;//此时mars运行会将返回地址写入到$ra寄存器(函数执行时需要保存它)
break;
case AssignState:
op_helpAssignStatement(item, out);
break;
case Label:
out << item.target << ":" << endl;
break;
case FunctionDef:
//函数定义要处理的大问题
out << item.target << ":" << endl;//生成跳转标签
funcName = item.target;
op_helpFunctionDef(item.target, out);
break;
case ParamDef:
//忽略处理,因为已经通过符号表在函数定义处处理了变量、参数的空间分配与地址分配
break;
case Jump:
out << "j " << item.target << endl;
break;
case BEZ:
case BNZ:
case BLZ:
case BLEZ:
case BGZ:
case BGEZ:
op_helpBJump(item, out);
break;
case ReadChar:
case ReadInt: {
if (item.type == ReadChar)
out << "li $v0 12" << endl;
else
out << "li $v0 5" << endl;
out << "syscall" << endl;
myItr = varToRegisterMap.find(item.target);
if (myItr != varToRegisterMap.end()) {
out << "addu " << myItr->second << " $v0 $0" << endl;
break;
}
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$a3", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$a3", out);
}
out << "sw $v0 0($a3)" << endl;
break;
}
case PrintStr: {
cancelEscapeChar(item.target);
map<string, string>::iterator iter = stringWithLabel.find(item.target);
if (iter != stringWithLabel.end()) {
out << "la $a0 " << iter->second << endl;
}
out << "li $v0 4" << endl;
out << "syscall" << endl;
break;
}
case PrintChar:
out << "li $a0 " << (int)item.target.at(0) << endl;
out << "li $v0 11" << endl;
out << "syscall" << endl;
break;
case PrintInt:
out << "li $a0 " << stringToInt(item.target) << endl;
out << "li $v0 1" << endl;
out << "syscall" << endl;
break;
case PrintId: {
//判断是打印int还是char
myItr = varToRegisterMap.find(item.target);
if (myItr != varToRegisterMap.end()) {
out << "addu $a0 " << myItr->second << " $0" << endl;
if (!item.isNotPrintCharId)
out << "li $v0 11" << endl;
else
out << "li $v0 1" << endl;
out << "syscall" << endl;
break;
}
if (item.target.at(0) == 'G') {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$a0", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$a0", out);
}
out << "lw $a0 0($a0)" << endl;
}
else if (item.target.at(0) == 'T') {
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$a0", out);
out << "lw $a0 0($a0)" << endl;
}
else {
out << "move $a0 " << "$t" << (g + 3) << endl;
}
}
if (!item.isNotPrintCharId)
out << "li $v0 11" << endl;
else
out << "li $v0 1" << endl;
out << "syscall" << endl;
break;
}
case ReturnInt:
case ReturnChar:
out << "li $v0 " << stringToInt(item.target) << endl;
out << "sw $v0 " << returnValueSpace << "($0)" << endl;
//返回地址
op_helpReturn(out,funcName);
break;
case ReturnId: {
myItr = varToRegisterMap.find(item.target);
if (myItr != varToRegisterMap.end()) {
out << "sw " << myItr->second << " " << returnValueSpace << "($0)" << endl;
op_helpReturn(out,funcName);
break;
}
if (item.target.at(0) == 'G') {
int order = stringToInt(item.target.substr(1));
SymbolTableItem item = globalSymbolTable.at(order);
if (item.getFuncName() == "GLOBAL") {
getAddrOfGlobal(item.getId(), "$v0", out);
}
else {
getAddrOfLocal(item.getFuncName(), item.getId(), "$v0", out);
}
out << "lw $v0 0($v0)" << endl;
}
else if (item.target.at(0) == 'T') {
int g = stringToInt(item.target.substr(1));
if (g > TEMP_REGISTER) {
getAddrOfTemp(g, "$v0", out);
out << "lw $v0 0($v0)" << endl;
}
else {
out << "move $v0 " << "$t" << (g + 3) << endl;
}
}
out << "sw $v0 " << returnValueSpace << "($0)" << endl;
//返回地址
op_helpReturn(out,funcName);
break;
}
case ReturnEmpty:
//返回地址
op_helpReturn(out,funcName);
break;
case OverProcedure:
out << "li $v0 10" << endl;
out << "syscall" << endl;
default:break;
}
}
} | true |
fe92a165132566b1caff26f36bd22d77aa33cdc9 | C++ | amonszpart/RAPter | /RAPter/external/schnabel07/GfxTL/BBoxDistanceKdTreeStrategy.h | UTF-8 | 3,139 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | #ifndef GfxTL__BBOXDISTANCEKDTREESTRATEGY_HEADER__
#define GfxTL__BBOXDISTANCEKDTREESTRATEGY_HEADER__
namespace GfxTL
{
template< class InheritedStrategyT >
struct BBoxDistanceKdTreeStrategy
{
typedef typename InheritedStrategyT::value_type value_type;
class CellData
: public InheritedStrategyT::CellData
{
public:
typedef typename InheritedStrategyT::CellData BaseType;
typedef typename BaseType::value_type value_type;
typedef typename ScalarTypeDeferer< value_type >::ScalarType
ScalarType;
CellData()
{
m_bbox[0] = m_bbox[1] = NULL;
}
~CellData()
{
delete[] m_bbox[0];
delete[] m_bbox[1];
}
ScalarType **BBox()
{
return m_bbox;
}
const ScalarType * const *BBox() const
{
return m_bbox;
}
private:
ScalarType *m_bbox[2];
};
template< class BaseT >
class StrategyBase
: public InheritedStrategyT::template StrategyBase< BaseT >
{
public:
typedef typename InheritedStrategyT::template StrategyBase< BaseT >
BaseType;
typedef typename BaseType::CellType CellType;
typedef typename ScalarTypeDeferer< value_type >::ScalarType
ScalarType;
typedef typename BaseType::DereferencedType DereferencedType;
typedef typename ScalarTypeConversion< ScalarType,
ScalarType >::DifferenceType DiffScalarType;
StrategyBase()
{}
~StrategyBase()
{}
protected:
template< class BuildInformationT >
void InitRoot(const BuildInformationT &bi, CellType *cell)
{
BaseType::InitRoot(bi, cell);
cell->BBox()[0] = new ScalarType[BaseType::m_dim];
cell->BBox()[1] = new ScalarType[BaseType::m_dim];
BaseType::AssignVector(bi.BBox()[0], &cell->BBox()[0]);
BaseType::AssignVector(bi.BBox()[1], &cell->BBox()[1]);
}
template< class BuildInformationT >
void InitCell(const CellType &parent,
const BuildInformationT &parentInfo, unsigned int childIdx,
const BuildInformationT &bi, CellType *cell)
{
BaseType::InitCell(parent, parentInfo, childIdx, bi, cell);
cell->BBox()[0] = new ScalarType[BaseType::m_dim];
cell->BBox()[1] = new ScalarType[BaseType::m_dim];
BaseType::AssignVector(bi.BBox()[0], &cell->BBox()[0]);
BaseType::AssignVector(bi.BBox()[1], &cell->BBox()[1]);
}
template< class TraversalInformationT >
void UpdateCellWithBack(const TraversalInformationT &ti,
CellType *cell)
{
BaseType::UpdateCellWithBack(ti, cell);
BaseType::IncludeInAABox(BaseType::back(), cell->BBox());
}
template< class TraversalInformationT >
typename BaseType::template DistanceType
<
ScalarType,
typename ScalarTypeDeferer<
typename TraversalInformationT::GlobalType::PointType
>::ScalarType
>::Type
CellSqrDistance(const CellType &cell, const TraversalInformationT &ti) const
{
return BaseType::BoxSqrDistance(ti.Global().Point(), cell.BBox()[0],
cell.BBox()[1]);
}
};
};
};
#endif
| true |
d23f52b7445aea057e5ce587b8e9c446644eef6f | C++ | Nisthar/Shopify-Node-Addons | /cppsrc/httptest.cpp | UTF-8 | 3,147 | 2.921875 | 3 | [] | no_license | #include "httptest.h"
std::string apifunctions::createLicense(){
auto r = cpr::Post(cpr::Url{/*LICENSE API ENDPOINT HERE*/}, cpr::Header{{"Content-Type", "application/x-www-form-urlencoded"}},cpr::Payload{{}});
return r.text;
}
std::string apifunctions::authLicense(std::string key, std::string hwid){
auto r = cpr::Post(cpr::Url{/*AUTH API ENDPOINT HERE*/},
cpr::Header{{"Content-Type", "application/x-www-form-urlencoded"}},
cpr::Payload{ {"license", key },
{"hwid", hwid } });
std::cout << r.url << std::endl;
std::cout << r.status_code << std::endl;
return r.text;
}
std::string apifunctions::createTask(std::string website, std::string keywords, std::string size, int numTasks, int numCheckouts ){
// Clean url here
// Parse keywords here
auto r = cpr::Post(cpr::Url{/*TASK CREATION API ENDPOINT HERE*/},
cpr::Header{{"Content-Type", "application/x-www-form-urlencoded"}},
cpr::Payload{ {"website", website },
{"keywords", keywords },
{"size", size },
{"numTasks", static_cast<char>(numTasks) },
{"numCheckouts", static_cast<char>(numCheckouts) }});
return r.text;
}
// ===== Function Wrappers =====
// PostWrapper(const Napi::CallbackInfo &info) => createLicense(url)
// AuthWrapper(const Napi::CallbackInfo &info) => authLicense(key, hwid)
// Init(Napi::Env env, Napi::Object exports) => createTask(website,keywords,size,numTasks,numCheckouts)
// = TODO =
// Add in type checking and missing argument calls
Napi::String apifunctions::PostWrapper(const Napi::CallbackInfo &info){
Napi::Env env = info.Env();
std::string s = apifunctions::createLicense();
return Napi::String::New(env,s);
}
Napi::String apifunctions::AuthWrapper(const Napi::CallbackInfo &info){
Napi::Env env = info.Env();
if(info.Length() < 2 || !info[0].IsString() || !info[1].IsString()){
throw Napi::Error::New(env, "Invalid Arguments!");
}
std::string k = info[0].ToString();
std::string h = info[1].ToString();
std::string cl = apifunctions::authLicense(k,h);
return Napi::String::New(env,cl);
}
Napi::String apifunctions::NewTaskWrapper(const Napi::CallbackInfo &info){
Napi::Env env = info.Env();
if(info.Length() < 5 || !info[0].IsString() || !info[1].IsString() || !info[2].IsString() || !info[3].IsNumber() || !info[4].IsNumber()){
throw Napi::Error::New(env, "Invalid Arguments!");
}
std::string w = info[0].ToString();
std::string kw = info[1].ToString();
std::string sz = info[2].ToString();
int nt = info[3].ToNumber();
int nc = info[4].ToNumber();
std::string response = createTask(w , kw, sz, nt, nc);
return Napi::String::New(env, response);
}
Napi::Object apifunctions::Init(Napi::Env env, Napi::Object exports){
exports.Set("createLicense", Napi::Function::New(env, apifunctions::PostWrapper));
exports.Set("authLicense", Napi::Function::New(env, apifunctions::AuthWrapper));
return exports;
}
| true |
9ddc7a53492ac3cd173cde012766ab76d80ff607 | C++ | bobroider/test | /myrect.cpp | UTF-8 | 2,476 | 2.515625 | 3 | [] | no_license |
#include <QDebug>
#include <QGraphicsScene>
#include <QGraphicsView>
#include "myrect.h"
#include "mybullet.h"
#include "myenemy.h"
#include "game.h"
MyRect::MyRect(QGraphicsItem *parent): QGraphicsPixmapItem(parent), direction(Direction_Unknown)
{
_piu_sound = new QMediaPlayer;
_piu_sound->setMedia(QUrl("qrc:/music/piu.wav"));
_timer = new QTimer(this);
_timer->setInterval(5);
connect( _timer, SIGNAL(timeout()), this, SLOT(move()));
setPixmap(QPixmap(":/image/fly.png"));
setZValue(Game::PriorityDeepPlayer);
}
void MyRect::keyPressEvent(QKeyEvent *event)
{
if(event->isAutoRepeat()) { event->ignore(); return; }
switch (event->key()) {
case Qt::Key_Left:
isPressedLeft = true;
if(!isPressedRight) direction = Direction_Left;
break;
case Qt::Key_Right:
isPressedRight = true;
if(!isPressedLeft) direction = Direction_Right;
break;
case Qt::Key_Space:
event->accept();
scene()->addItem(new MyBullet);
if (_piu_sound->state() == QMediaPlayer::PlayingState) {
_piu_sound->setPosition(0);
}
else if(_piu_sound->state() == QMediaPlayer::StoppedState) {
_piu_sound->play();
}
return;
break;
default:
event->ignore();
return;
}
event->accept();
_timer->start();
}
void MyRect::keyReleaseEvent(QKeyEvent *event)
{
if(event->isAutoRepeat()) { event->ignore(); return; }
switch (event->key()) {
case Qt::Key_Left:
isPressedLeft = false;
if(isPressedRight) direction = Direction_Right;
else _timer->stop();
break;
case Qt::Key_Right:
isPressedRight = false;
if(isPressedLeft) direction = Direction_Left;
else _timer->stop();
break;
default:
event->ignore();
return;
}
}
void MyRect::spawn()
{
scene()->addItem(new MyEnemy);
}
void MyRect::move()
{
if(!hasFocus()) { _timer->stop(); return; }
if(direction == Direction_Left) {
if(pos().x() > 0)
moveBy(-1, 0);
else {
//_timer->stop();
direction = Direction_Unknown;
}
} else if(direction == Direction_Right){
if (pos().x() + boundingRect().width() < scene()->sceneRect().right())
moveBy(1, 0);
else {
//_timer->stop();
direction = Direction_Unknown;
}
}
}
| true |
85f06c770c8c58c85e0bcdadf753e47db7c3ee84 | C++ | HuangJingGitHub/PracMakePert_C-Cpp | /leetcode/two_sum/leetcode_two_sum.cpp | UTF-8 | 1,497 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <unordered_map>
#include <vector>
#include <typeinfo>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
std::unordered_multimap<int, int> umap;
for (int i = 0; i < nums.size() ; i++)
{
umap.insert(std::make_pair(nums[i], i));
}
for (int i = 0, subTarget; i < nums.size() - 1; i++)
{
subTarget = target - nums[i];
auto range = umap.equal_range(subTarget);
if (range.first != umap.end() )
{
cout << "subTarget = " << subTarget << endl;
if (range.first != umap.find(nums[i]))
{
vector<int> index{i, range.first->second};
return index;
}
else if (range.first == umap.find(nums[i]) && next(range.first, 1) != umap.end())
{
for (auto itr = range.first; itr != range.second; itr++)
cout << itr->first << " " << itr->second << endl;
vector<int> index{i, range.first->second};
return index;
}
}
}
vector<int> noAnswer;
return noAnswer;
}
};
int main()
{
vector<int> testVec{3,2,4,4,5,3,8,3}, ans;
int testTarget = 6;
Solution sol;
ans = sol.twoSum(testVec, testTarget);
for (int x : ans)
cout << x << " ";
}
| true |
7767b321e5d17ab71e48fc32da49b42cbc9a7fc0 | C++ | sing840722/ZomZom | /OpenGLTemplate/LightHouse.cpp | UTF-8 | 1,449 | 2.625 | 3 | [] | no_license | #include "LightHouse.h"
#include "Light.h"
#include "Common.h"
ALightHouse::ALightHouse() {
m_position = glm::vec3(-137.676, 0, -124.156);
m_pLight = new ALight;
m_pLight->SetLa(glm::vec3(0));
m_pLight->SetLd(glm::vec3(0.6,0,0));
m_pLight->SetLs(glm::vec3(0.85,0,0));
glm::vec3 lightSrcPosition = m_position;
lightSrcPosition.y += 65;
m_pLight->SetPosition(lightSrcPosition);
m_pLight->SetCutoff(50);
m_pLight->SetExponent(250);
m_pLight->SetAttenuation(glm::vec3(1, 0, 0));
}
ALightHouse::~ALightHouse() {
delete m_pLight;
}
void ALightHouse::Initialise() {
glm::vec3 lightSrcPosition = m_position;
lightSrcPosition.y += 65;
m_pLight->SetPosition(lightSrcPosition);
}
ALight* ALightHouse::GetLight() {
return m_pLight;
}
void ALightHouse::SetLightDirection(glm::mat3 vNormalMat, glm::vec3 targetLocation) {
static float t;
t = t + 0.05;
glm::vec3 lp = glm::vec3(m_pLight->Position());
glm::vec3 ttt;
ttt.x = m_position.x * sin(t);
ttt.y = 0;
ttt.z = m_position.x * cos(t/10);
m_pLight->SetDirection(glm::normalize(vNormalMat * (ttt - glm::vec3(m_pLight->Position()))));
}
void ALightHouse::SetLightDirection(glm::mat3 vNormalMat) {
static float t;
t = t + 0.025;
glm::vec3 lp = glm::vec3(m_pLight->Position());
glm::vec3 ttt;
ttt.x = m_position.x * sin(t);
ttt.y = 0;
ttt.z = m_position.x * cos(t / 10);
m_pLight->SetDirection(glm::normalize(vNormalMat * (ttt - glm::vec3(m_pLight->Position()))));
} | true |
9fe63c36308da096b026d6eaceccf31abd6f02a5 | C++ | PohanYang/OOP | /lab12/ex12-2.cpp | UTF-8 | 2,687 | 3.5 | 4 | [] | no_license | #include <iostream>
#include <stdlib.h>
using namespace std;
template <class T>
class Vector
{
private:
int len;
T* vec;
public:
Vector(int n, int m): len(n){
vec = new T[n];
for(int i; i<n; i++){
vec[i] = m;
}
}
Vector(int n, double *b): len(n), vec(b){}
void display();
int getVlen()const{return len;}
int getVvec(int i)const{return vec[i];}
void operator += (Vector b){
for(int i=0; i<b.len; i++){
vec[i] = vec[i]+b.vec[i];
}
}
void rand1D(T vec, int n);
// add any member if necessary
template<class S>
friend S dot (const Vector<S> &, const Vector<S> &);
};
template<class T>
void Vector<T>::display()
{
for(int i=0; i<getVlen(); i++){
cout << getVvec(i) << " ";
}
cout << endl;
}
/*
/////////////////////////////////////////////////
Point2D
////////////////////////////////////////////////
*/
class Point2D{
public:
int x;
int y;
};
template<>
class Vector<Point2D>
{
public:
int len;
Point2D *vec;
Vector(int n, int m):len(n){
vec = new Point2D[n];
for(int i=0; i<len; i++){
vec[i].x = m;
vec[i].y = m;
}
}
Vector(int n, Point2D *v):len(n){
vec = new Point2D[n];
for(int i=0; i<len; i++){
vec[i].x = v->x;
vec[i].y = v->y;
}
}
void display();
void operator += (Vector<Point2D> b){
for(int i=0; i<b.len; i++){
vec[i].x = vec[i].x + b.vec[i].x;
vec[i].y = vec[i].y + b.vec[i].y;
}
}
friend Point2D dot(const Vector<Point2D> &, const Vector<Point2D>){}
};
template<class S>
void Vector<Point2D>::display(){
for(int i=0; i<len; i++){
cout << "(" << vec[i].x << "," << vec[i].y << ") ";
}
cout << endl;
}
template<class S>
S dot(const Vector<S> &a, const Vector<S> &b)
{
S c = 0;
for(int i=0; i<a.getVlen(); i++){
c += a.getVvec(i)*b.getVvec(i);
}
return c;
}
template<class T>
void rand1D(T *vec, int n)
{
for(int i=0; i<n; i++){
vec[i].x = (rand()%10);
vec[i].y = (rand()%10);
}
}
int main()
{
int n;
cout << "Enter n: ";
cin >> n;
Vector<double> dvec(n,1);
double *b = new double[n];
for (int i = 0; i < n; i++)
b[i] = i;
Vector<double> dvec2(n,b);
cout << "dvec = ";
dvec.display();
cout << "dvec2 = ";
dvec2.display();
dvec2 += dvec;
cout << "new dvec2 = ";
dvec2.display();
double c = dot(dvec, dvec2);
cout << "dot(dvec, dvec2) = " << c << endl << endl;
srand(1);
Point2D *v = new Point2D[n];
rand1D<Point2D>(v, n); //0~9
Vector<Point2D> vp1(n,1);
Vector<Point2D> vp2(n,v);
cout << "vp1 = ";
vp1.display();
cout << "vp2 = ";
vp2.display();
vp2 += vp1;
cout << "new vp2 = ";
vp2.display();
//Point2D d = dot(vp1, vp2);
//cout << "dot(vp1, vp2) = " << d << endl;
return 0;
}
| true |
5e69c42a01e3e1336a8e15180723cfa4acc044f8 | C++ | theirishduck/OpenGL_3D-Interactive | /GlutPlayground/TCPReceiver.cpp | UTF-8 | 1,865 | 2.703125 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <WinSock2.h>
#include "TCPReceiver.h"
TCPReceiver::TCPReceiver(): hasClosed(false)
{
}
TCPReceiver::TCPReceiver(int port): hasClosed(false)
{
WSADATA WsaDat;
if (WSAStartup(MAKEWORD(2, 2), &WsaDat) != 0)
{
fprintf(stderr, "TCPReceiver(): wsa startup failed\n");
WSACleanup();
throw TCPReceiver_Exception::WSAINITERROR;
}
m_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (m_socket == INVALID_SOCKET)
{
fprintf(stderr, "TCPReceiver(): socket create failed\n");
WSACleanup();
throw TCPReceiver_Exception::SOCKETINITERROR;
}
m_servaddr.sin_family = AF_INET;
m_servaddr.sin_addr.s_addr = INADDR_ANY;
m_servaddr.sin_port = htons(port);
if (bind(m_socket, (SOCKADDR*)(&m_servaddr), sizeof(m_servaddr)) == SOCKET_ERROR)
{
fprintf(stderr, "TCPReceiver(): socket binding failed\n");
WSACleanup();
throw TCPReceiver_Exception::SOCKETBINDERROR;
}
}
TCPReceiver::~TCPReceiver()
{
}
void TCPReceiver::Listen(int backlog)
{
listen(m_socket, backlog);
}
bool TCPReceiver::Accept()
{
m_senderSocket = accept(m_socket, NULL, NULL);
return !(m_senderSocket == SOCKET_ERROR);
}
void TCPReceiver::SetNonBlocking()
{
u_long iMode = 1;
ioctlsocket(m_senderSocket, FIONBIO, &iMode);
}
void TCPReceiver::Receive(char *buff, size_t size)
{
int bytesRecv = recv(m_senderSocket, buff, size, 0);
int wsaError;
if (bytesRecv > 0)
return;
if (bytesRecv == SOCKET_ERROR && (wsaError = WSAGetLastError()) == WSAEWOULDBLOCK)
{
throw TCPReceiver_Exception(TCPReceiver_Exception::NONBLOCKING);
}
else
{
throw TCPReceiver_Exception(TCPReceiver_Exception::DISCONNECT);
}
}
int TCPReceiver::Close()
{
hasClosed = true;
return closesocket(m_socket);
}
int TCPReceiver::CloseSender()
{
return closesocket(m_senderSocket);
}
bool TCPReceiver::isClosed()
{
return hasClosed;
} | true |
476f5d2c3a574c811095560fee5745cb56331382 | C++ | NIICKK/Distributed-Service-using-GRPC- | /Thread.h | UTF-8 | 511 | 2.703125 | 3 | [] | no_license | #ifndef _Thread_H_
#define _Thread_H_
#include <queue>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <unistd.h>
#include "Thread.h"
class Thread{
private:
std::thread _thread;
bool _isfree;
std::function<void()> _task;
std::mutex _locker;
public:
//Constructor
Thread();
//if free
bool isfree();
//add task
void addTask(std::function<void()> task);
//If there is a task then execute it, otherwise spin
void run();
};
#endif
| true |
8e9682d134516eaab52761fee59743f6dc3cbc2d | C++ | s-s-9/UVA-Codes | /11192_groupreverse.cpp | UTF-8 | 956 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int noofgroups, groupchars, i;
string temp, s;
vector<string> tempshomahar;
while(scanf("%d", &noofgroups)==1){
if(noofgroups==0){
break;
}
cin>>s;
groupchars = (s.size())/noofgroups;
temp = "";
tempshomahar.clear();
for(i = 0; i<s.size(); i++){
if(i%groupchars==0){
if(temp!=""){
//cout<<temp<<endl;
tempshomahar.push_back(temp);
temp = "";
}
}
temp.push_back(s[i]);
}
//cout<<temp<<endl;
if(temp!=""){
tempshomahar.push_back(temp);
}
for(i = 0; i<tempshomahar.size(); i++){
reverse(tempshomahar[i].begin(), tempshomahar[i].end());
cout<<tempshomahar[i];
}
cout<<endl;
}
return 0;
}
| true |
c96d4bd2ccfd62e189f1aab766d2e7c4f8154836 | C++ | Cryolited/Comb | /CombQT/CombQT/generator.cpp | UTF-8 | 2,585 | 2.546875 | 3 | [] | no_license |
#include "analysisbank.h"
class Generator {
public:
struct params
{
uint16_t WIN_H_RADIX = 18;
uint16_t FB_OVERLAP_RATIO = 2; // перекрытие
uint16_t NFFT = 128; // колво фильтров
uint16_t WIN_OVERLAP_RATIO = 8; // длина фильтров
};
class signal {
public:
vector<float> t;
vector<int16_t> i;
vector<int16_t> q;
vector<int16_t> si;
vector<int16_t> sq;
void resize(uint16_t length) // без нулей
{
t.resize(length);
i.resize(length);
q.resize(length);
}
void resizeS(uint16_t length) // с нулями
{
si.resize(length);
sq.resize(length);
}
};
void genSignal(float LFM) // генерирование сигнала
{
params p;
first_period_part = p.NFFT ;
second_period_part = p.NFFT * p.WIN_OVERLAP_RATIO;
uint16_t DATA_AMPL = 30000;
uint16_t THRESHOLD = DATA_AMPL/2;
double time_sec = t_us;
uint16_t f0 = 0;
uint16_t len = Fs*time_sec ;
uint16_t len2 = ((len+ first_period_part + second_period_part)/p.NFFT)*p.NFFT ;
sig.resize(len);
sig.resizeS(len2);
float F0 = -LFM/2;
uint32_t l =0;
float b = LFM/time_sec;
for (int n = 0; n < len ; ++n) {
sig.t[n] = (float)n/Fs;
if ( LFM == 0)
{
sig.q[n] = round(DATA_AMPL*sin(2.0*M_PI*1e6*sig.t[n])) +rand()*1000 ;
sig.i[n] = round(DATA_AMPL*cos(2.0*M_PI*1e6*sig.t[n])) +rand()*1000;
}else {
sig.q[n] = round(DATA_AMPL*sin(2.0*M_PI*(F0*sig.t[n]+b/2.0*sig.t[n]*sig.t[n]))) ;
sig.i[n] = round(DATA_AMPL*cos(2.0*M_PI*(F0*sig.t[n]+b/2.0*sig.t[n]*sig.t[n]))) ;
}
}
for (int n = 0; n < len2; ++n) {
if (n < first_period_part)
{
sig.sq[n] = 0;
sig.si[n] = 0;
}
else
if (n < len + first_period_part )
{
sig.sq[n] = sig.q[l] ;
sig.si[n] = sig.i[l] ;
l++;
}
else
{
sig.sq[n] = 0;
sig.si[n] = 0;
}
}
}
signal sig;
double t_us = 0.2 * 1e-6;
uint16_t first_period_part;
uint16_t second_period_part;
uint32_t Fs = 512e6;
};
| true |
14276d071e0ccc65b6dedc669857f2968bbec9b5 | C++ | grasmanek94/HoverboardController | /controller.ino | UTF-8 | 1,480 | 2.71875 | 3 | [] | no_license | #include "SoftwareSerial9.h"
#define TX_L 11
#define RX_L 10
#define TX_R 6
#define RX_R 5
#define LEDPIN 13
SoftwareSerial9 serial_left(RX_L,TX_L);
SoftwareSerial9 serial_right(RX_R,TX_R);
void setup() {
serial_left.begin(26315);
serial_right.begin(26315);
Serial.begin(115200);
}
char c = ' ';
signed int sp_l=0;
signed int sp_r=0;
void loop() {
Serial.println(c);
if(c == ' ') {
sp_l=0;
sp_r=0;
} else if(c == 'q') {
sp_l -= 10;
} else if(c == 'w') {
sp_l += 10;
} else if(c == '2') {
sp_l += 100;
} else if(c == '1') {
sp_l -= 100;
} else if(c == 'o') {
sp_r -= 10;
} else if(c == 'p') {
sp_r += 10;
} else if(c == '0') {
sp_r += 100;
} else if(c == '9') {
sp_r -= 100;
}
Serial.print("speeds: ");
Serial.print(sp_l);
Serial.print(" / ");
Serial.println(sp_r);
do {
serial_left.write9(256);
serial_left.write9(sp_l & 0xFF);
serial_left.write9((sp_l >> 8) & 0xFF);
serial_left.write9(sp_l & 0xFF);
serial_left.write9((sp_l >> 8) & 0xFF);
serial_left.write9(85);
serial_right.write9(256);
serial_right.write9(sp_r & 0xFF);
serial_right.write9((sp_r >> 8) & 0xFF);
serial_right.write9(sp_r & 0xFF);
serial_right.write9((sp_r >> 8) & 0xFF);
serial_right.write9(85);
delayMicroseconds(300);
} while(!Serial.available());
c=Serial.read();
}
| true |
8f10b8eaa21df6f7afbbbaac0f6aca2b80880072 | C++ | boaz001/drone-tracking | /color-tracking-demo/color-tracking-demo.cpp | UTF-8 | 4,901 | 2.75 | 3 | [] | no_license | // color-tracking-demo.cpp
#include <iostream>
#include <cstdlib>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
// clicked point class
class CClickedPoint
{
public:
CClickedPoint();
virtual ~CClickedPoint();
cv::Point point_;
bool bUpdated_;
};
CClickedPoint::CClickedPoint()
: point_(0, 0)
, bUpdated_(false)
{}
CClickedPoint::~CClickedPoint()
{}
// callback for mouse events on a window
void
mouseCallback(int event, int x, int y, int flags, void* pData)
{
CClickedPoint* pClickedPoint = static_cast<CClickedPoint*>(pData);
if (pClickedPoint != NULL)
{
if (event == cv::EVENT_LBUTTONDOWN)
{
pClickedPoint->point_.x = x;
pClickedPoint->point_.y = y;
pClickedPoint->bUpdated_ = true;
}
}
}
// init
bool
initVideoCapture(cv::VideoCapture& videoCapture)
{
// set video capture properties for MacBook' iSight camera
videoCapture.set(CV_CAP_PROP_FRAME_WIDTH, 500);
videoCapture.set(CV_CAP_PROP_FRAME_HEIGHT, 600);
// try to open the video source
videoCapture.open(0);
if (!videoCapture.isOpened())
{
std::cerr << "Could not open video capture device" << std::endl;
return false;
}
return true;
}
bool
createWindow(const std::string& sWindowName, const CClickedPoint* pCallbackData)
{
// create window
cv::namedWindow(sWindowName, CV_WINDOW_AUTOSIZE);
// bind mouse callback function
cv::setMouseCallback(sWindowName, mouseCallback, (void*)pCallbackData);
// should always succeed
return true;
}
bool
addTrackbar(
const std::string& sWindowName,
const std::string& sTrackbarName,
int* value,
const int count = 255)
{
cv::createTrackbar(sTrackbarName, sWindowName, value, count);
return true;
}
// main entry point
int
main(int argc, char** argv)
{
int iDebug = 0;
if (argc == 2)
{
iDebug = std::atoi(argv[1]);
}
// create video capture object
cv::VideoCapture videoCapture;
const bool bVideoCaptureInitialized = initVideoCapture(videoCapture);
// create windows
// Input
const std::string sInputWindow("Input");
CClickedPoint InputWindowClickedPoint;
createWindow(sInputWindow, &InputWindowClickedPoint);
// HSV Result
const std::string sResultWindow("Result");
createWindow(sResultWindow, NULL);
// Controls
const std::string sControlsWindow("Controls");
createWindow(sControlsWindow, NULL);
const std::string sControlRangeH("Range H");
const std::string sControlRangeS("Range S");
const std::string sControlRangeV("Range V");
int rangeH = 10;
int rangeS = 10;
int rangeV = 10;
const int maxRangeH = 50;
const int maxRangeS = 50;
const int maxRangeV = 50;
addTrackbar(sControlsWindow, sControlRangeH, &rangeH, maxRangeH);
addTrackbar(sControlsWindow, sControlRangeS, &rangeS, maxRangeS);
addTrackbar(sControlsWindow, sControlRangeV, &rangeV, maxRangeV);
if (bVideoCaptureInitialized)
{
// HSV threshold values
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
for(;;)
{
cv::Mat frame;
// grab frame
videoCapture >> frame;
// flip to make it mirror-like
// cv::flip(frame, frame, 1);
// show it
cv::imshow(sInputWindow, frame);
// HSV try-out
// convert to HSV
cv::Mat imgHSV;
cv::cvtColor(frame, imgHSV, cv::COLOR_BGR2HSV);
// get clicked point color
if (InputWindowClickedPoint.bUpdated_ == true)
{
const int x = InputWindowClickedPoint.point_.x;
const int y = InputWindowClickedPoint.point_.y;
InputWindowClickedPoint.bUpdated_ = false;
const cv::Vec3b hsv = imgHSV.at<cv::Vec3b>(y, x);
if (iDebug > 3)
{
std::cout << "h=" << static_cast<int>(hsv[0])
<< " s=" << static_cast<int>(hsv[1])
<< " v=" << static_cast<int>(hsv[2]) << std::endl;
}
// update range thresholds
iLowH = hsv[0] - rangeH;
iHighH = hsv[0] + rangeH;
iLowS = hsv[1] - rangeS;
iHighS = hsv[1] + rangeS;
iLowV = hsv[2] - rangeV;
iHighV = hsv[2] + rangeV;
}
// threshold image
cv::Mat imgThresholded;
cv::inRange(
imgHSV,
cv::Scalar(iLowH, iLowS, iLowV),
cv::Scalar(iHighH, iHighS, iHighV),
imgThresholded);
// combine thresholded on original image
cv::Mat imgCombined;
frame.copyTo(imgCombined, imgThresholded);
// show result
cv::imshow(sResultWindow, imgCombined);
// give imshow some time to show the result
// so have a 1 ms delay
// stop when a key is pressed
if (cv::waitKey(1) > -1)
{
break;
}
}
}
else
{
std::cerr << "Failed to initialize video capture device" << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| true |
e5a6e015924cd578c5aadb39806d8d36febb59c7 | C++ | ABHISHEK-G0YAL/Competitive-Programming | /practice/LeetCode/Diameter_of_Binary_Tree.cpp | UTF-8 | 882 | 3.5625 | 4 | [] | no_license | // https://leetcode.com/problems/diameter-of-binary-tree/
/*
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
int diameter = 0;
int heightOfBinaryTree(TreeNode* root) {
if(!root)
return 0;
int leftHeight = heightOfBinaryTree(root->left);
int rightHeight = heightOfBinaryTree(root->right);
diameter = max(diameter, leftHeight + rightHeight);
return 1 + max(leftHeight, rightHeight);
}
public:
int diameterOfBinaryTree(TreeNode* root) {
heightOfBinaryTree(root);
return diameter;
}
}; | true |
589a02ca1feeb4369215cc74fe98e8083eb30a8e | C++ | nazhor/chartwork | /src/chartwork/LinePlot.cpp | UTF-8 | 2,784 | 2.8125 | 3 | [
"MIT"
] | permissive | #include <chartwork/LinePlot.h>
#include <QtGui>
#include <chartwork/Design.h>
#include <chartwork/elements/Symbol.h>
namespace chartwork
{
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// LinePlot
//
////////////////////////////////////////////////////////////////////////////////////////////////////
LinePlot::LinePlot(QWidget *parent)
: XYPlot(parent),
m_lineWidth(2.0)
{
resize(400, 300);
setMinimumSize(200, 150);
m_title.setText("Line Plot");
generateRandomValues();
update();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void LinePlot::generateRandomValues()
{
resetValues();
std::srand(0);
const size_t numberOfSamples = 50;
auto randomFunction = [](int function, double value)
{
switch (function)
{
default:
case 0:
return value * value;
case 1:
return std::sqrt(value);
case 2:
return value;
case 3:
return std::cos(value * M_PI_2);
}
};
for (EntryMultiSet &dataSeries : m_values)
{
const int function = rand() % 4;
const double yMax = m_yMin + (std::rand() / (double)RAND_MAX) * (m_yMax - m_yMin);
for (size_t i = 0; i < numberOfSamples; i++)
{
const double x = m_xMin + (m_xMax - m_xMin) * (double)i / (numberOfSamples - 1);
const double y = m_yMin + randomFunction(function, (double)i / (numberOfSamples - 1)) * (yMax - m_yMin);
dataSeries.insert(Entry(x, y));
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void LinePlot::paint(QPainter &painter)
{
XYPlot::paint(painter);
painter.setRenderHint(QPainter::Antialiasing);
for (size_t dataSeriesIndex = 0; dataSeriesIndex < m_values.size(); dataSeriesIndex++)
{
const EntryMultiSet &dataSeries = m_values[dataSeriesIndex];
if (dataSeries.size() < 2)
continue;
const QColor &color = (*m_colors)[dataSeriesIndex % m_colors->size()];
painter.setPen(QPen(color, m_lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
QPolygonF path;
for (const Entry &entry : dataSeries)
{
const QPointF position = positionForValue(entry);
path << position;
}
painter.drawPolyline(path);
}
painter.setRenderHint(QPainter::Antialiasing, false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
double LinePlot::lineWidth() const
{
return m_lineWidth;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
void LinePlot::setLineWidth(double lineWidth)
{
m_lineWidth = std::max(0.5, std::min(10.0, lineWidth));
update();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
}
| true |
1166232caf1f3fdd6f805d5ce11f74850fe20a71 | C++ | 993950972/LeetCode | /C++/443. String Compression.cpp | UTF-8 | 2,923 | 3.921875 | 4 | [] | no_license | /*
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input:
["a","a","b","b","c","c","c"]
Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
Example 2:
Input:
["a"]
Output:
Return 1, and the first 1 characters of the input array should be: ["a"]
Explanation:
Nothing is replaced.
Example 3:
Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]
Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.
*/
/*
算法思想:刚开始理解错了题意,没仔细看题忽略了in-place。重写了下。思想:循环遍历vector,统计字符个数,如果字符个数大于1,则将该字符和其个数(转换成字符)放入vector(ans)中。如果等于1,则只需要将该字符放入ans中即可。遍历完毕,判断最后cnt值是否大于1,大于则将其转换成字符串并放入ans中 。
*/
class Solution {
public:
string numToStr(int num)
{
string str;
while(num)
{
str += (num % 10) + '0';
num/=10;
}
return str;
}
int compress(vector<char>& chars) {
int sz = chars.size();
if(sz < 2)
return chars.size();
char temp = chars[0];
int cnt = 1;
vector<char> ans;
ans.push_back(temp);
for(int i = 1;i < sz;i++)
{
if(chars[i] == temp)
{
cnt++; //统计连续相同字符的个数
}
else //如果相邻字符不等
{
if(cnt > 1) //且cnt>1,则将数字转换成字符填入ans中
{
string str = numToStr(cnt);
for(int j = str.size() - 1;j >= 0;j--)
{
ans.push_back(str[j]);
}
} //更新为temp为当前字符,更新计数器。
temp = chars[i];
cnt = 1;
ans.push_back(temp);
}
}
if(cnt > 1)
{
string str = numToStr(cnt);
for(int j = str.size() - 1;j >= 0;j--)
{
ans.push_back(str[j]);
}
}
chars = ans;
return ans.size();
}
}; | true |
ccfcb53b06bd9bc772a5a0e22de2a38751bcf521 | C++ | agabor/DicomReader | /cv/Image.cpp | UTF-8 | 3,001 | 2.703125 | 3 | [] | no_license | #include "Image.h"
#include "DicomReader.h"
#include <iostream>
using namespace cv;
using namespace std;
Image::Image(const char *file_name) {
DicomReader r;
original = r.read(file_name, CV_8U);
resize();
}
void Image::applyContrast(const MatchSettings &settings) {
mat = Mat(original.rows, original.cols, mat.type());
original.convertTo(mat, -1, settings.contrast);
}
void Image::resize() {
double m = sqrt(double(400000) / double(original.rows * original.cols));
cv::Mat dest(static_cast<int>(original.rows * m), static_cast<int>(original.cols * m), CV_8U);
cv::resize(original, dest, dest.size());
original = dest;
}
void addKeyPoint(const KeyPoint &k, map<int, vector<KeyPoint>> &kpmap) {
if (kpmap.find(k.octave) == kpmap.end())
kpmap[k.octave] = vector<KeyPoint>();
kpmap[k.octave].push_back(k);
}
float getScale(int octave, const MatchSettings &settings) {
switch (octave) {
case 0: return settings.scale0;
case 1: return settings.scale1;
case 2: return settings.scale2;
case 3: return settings.scale3;
default: return settings.scale3;
}
}
void Image::scan(const MatchSettings &settings) {
if (settings.mirrorY) {
mirrored = std::make_shared<Image>();
mirrored->file_name = file_name;
flip(original, mirrored->original, 1);
mirrored->scanSelf(settings);
}
scanSelf(settings);
}
void Image::scanSelf(const MatchSettings &settings) {
applyContrast(settings);
clear();
detectKeyPoints(settings);
extractDescriptors();
}
void Image::clear() {
keypoints.clear();
descriptors.clear();
scaled_keypoints.clear();
scaled_descriptors.clear();
}
KeyPoint getScaledKeyPoint(const MatchSettings &settings, const KeyPoint &k) {
KeyPoint scaled;
scaled.size = k.size * getScale(k.octave, settings);
scaled.octave = k.octave;
scaled.response = k.response;
scaled.angle = k.angle;
scaled.class_id = k.class_id;
scaled.pt = k.pt;
return scaled;
}
void Image::detectKeyPoints(const MatchSettings &settings) {
SurfFeatureDetector detector{settings.minHessian, OCTAVES, 1};
vector<KeyPoint> points;
detector.detect(mat, points );
sort(points.begin(), points.end(),
[](const KeyPoint &a, const KeyPoint &b) -> bool
{
return a.response > b.response;
});
for(auto &k : points) {
addKeyPoint(k, keypoints);
KeyPoint scaled = getScaledKeyPoint(settings, k);
addKeyPoint(scaled, scaled_keypoints);
}
}
void Image::extractDescriptors() {
SurfDescriptorExtractor extractor;
for (auto item : keypoints) {
Mat desc;
extractor.compute(mat, item.second, desc);
descriptors[item.first] = desc;
}
for (auto item : scaled_keypoints) {
Mat desc;
extractor.compute(mat, item.second, desc);
scaled_descriptors[item.first] = desc;
}
}
| true |
ea3aed06e8efae3377f3f36fda03b0f315ab3212 | C++ | SajibTalukder2k16/Codeforces | /661 Div 3/1399A.cpp | UTF-8 | 636 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int test_case;
cin>>test_case;
while(test_case--)
{
int n;
cin>>n;
int ara;
vector<int>vec;
for(int i=0;i<n;i++)
{
cin>>ara;
vec.push_back(ara);
}
sort(vec.begin(),vec.end());
bool check = true;
for(int i=1;i<n;i++)
{
if(vec[i]-vec[i-1]>1)
{
check = false;
break;
}
}
if(check==false)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
} | true |
5650bcc5174351ff36d0ce50d062177d317881d0 | C++ | smsesteves/ComputerGraphics | /LAIG3_T3_G10/source/include/torus.h | UTF-8 | 261 | 2.640625 | 3 | [] | no_license | #ifndef TORUS_H
#define TORUS_H
#include "primitive.h"
using namespace std;
class Torus : public Primitive
{
private:
float inner;
float outer;
int slices;
int loops;
public:
Torus(float inner,float outer,int slices,int loops);
void draw();
};
#endif | true |
05c2e1a454db57314b15724594a9325fc601ded4 | C++ | josephwinston/hana | /test/integral_constant/orderable.cpp | UTF-8 | 1,521 | 2.640625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | /*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/tuple.hpp>
#include <laws/base.hpp>
#include <laws/comparable.hpp>
#include <laws/orderable.hpp>
using namespace boost::hana;
int main() {
//////////////////////////////////////////////////////////////////////////
// Setup for the laws below
//////////////////////////////////////////////////////////////////////////
auto int_constants = tuple_c<int, -10, -2, 0, 1, 3, 4>;
//////////////////////////////////////////////////////////////////////////
// Comparable and Orderable
//////////////////////////////////////////////////////////////////////////
{
// operators
static_assert(has_operator<IntegralConstant<int>, decltype(equal)>{}, "");
static_assert(has_operator<IntegralConstant<int>, decltype(not_equal)>{}, "");
static_assert(has_operator<IntegralConstant<int>, decltype(less)>{}, "");
static_assert(has_operator<IntegralConstant<int>, decltype(less_equal)>{}, "");
static_assert(has_operator<IntegralConstant<int>, decltype(greater)>{}, "");
static_assert(has_operator<IntegralConstant<int>, decltype(greater_equal)>{}, "");
// laws
test::TestComparable<IntegralConstant<int>>{int_constants};
test::TestOrderable<IntegralConstant<int>>{int_constants};
}
}
| true |
1fb1eab3d540f5261dc85bb421130f301ba0c2d1 | C++ | dentiny/Ghost-Interpreter | /Ghost Interpreter v0.1/BuiltinFunctor.hpp | UTF-8 | 6,230 | 3.078125 | 3 | [] | no_license | #ifndef BUILT_IN_FUNC_HPP__
#define BUILT_IN_FUNC_HPP__
#include "DataManager.hpp"
#include "Ghost_intObj.hpp"
#include "Ghost_floatObj.hpp"
#include "Ghost_stringObj.hpp"
#include "Ghost_listObj.hpp"
#include <string>
#include <functional>
#include <unordered_set>
#include <unordered_map>
struct BuiltinFunctor : virtual public DataManager
{
public:
// unordered_set to store built-in function
// (1) cannot be used as function name or variable name
// (2) examined before parsing on vector number
const std::unordered_set<std::string> built_in_func
{
"val", // get the value of variable
"type", // get the type of variable
"query", // get the type and value of variable
"show_local", // display local variables
"show_global", // display glocal variables
"show_var" // display all variables
};
// helper function for parse()
// helper function for category 6: built-in function type()
// helper function for category 7: built-in function
std::string getType(const std::string & var_name,
std::unordered_map<std::string, varType> & varTbl,
std::unordered_map<std::string, Ghost_intObj> & intTbl,
std::unordered_map<std::string, Ghost_floatObj> & floatTbl,
std::unordered_map<std::string, Ghost_stringObj> & stringTbl,
std::unordered_map<std::string, Ghost_listObj> & listTbl)
{
// variable not declared
if(varTbl.find(var_name) == varTbl.end())
{
return "Invalid Type";
}
varType curType = varTbl[var_name];
if(curType == varType::INT_VAR)
{
return intTbl[var_name].getType();
}
else if(curType == varType::FLOAT_VAR)
{
return floatTbl[var_name].getType();
}
else if(curType == varType::STRING_VAR)
{
return stringTbl[var_name].getType();
}
else if(curType == varType::LIST_VAR)
{
return listTbl[var_name].getType();
}
return "Invalid Type";
}
// helper function for parse()
// helper function for category 6: built-in function val()
// helper function for category 7: built-in function
std::string getVal(const std::string & var_name,
std::unordered_map<std::string, varType> & varTbl,
std::unordered_map<std::string, Ghost_intObj> & intTbl,
std::unordered_map<std::string, Ghost_floatObj> & floatTbl,
std::unordered_map<std::string, Ghost_stringObj> & stringTbl,
std::unordered_map<std::string, Ghost_listObj> & listTbl)
{
// variable not declared
if(varTbl.find(var_name) == varTbl.end())
{
return "Invalid Value";
}
varType curType = varTbl[var_name];
if(curType == varType::INT_VAR)
{
return intTbl[var_name].getVal_s();
}
else if(curType == varType::FLOAT_VAR)
{
return floatTbl[var_name].getVal_s();
}
else if(curType == varType::STRING_VAR)
{
return stringTbl[var_name].getVal_s();
}
else if(curType == varType::LIST_VAR)
{
return listTbl[var_name].getVal_s();
}
return "Invalid Value";
}
// helper function for parse()
// helper function for category 7: built-in function
std::string query(const std::string & var_name,
std::unordered_map<std::string, varType> & varTbl,
std::unordered_map<std::string, Ghost_intObj> & intTbl,
std::unordered_map<std::string, Ghost_floatObj> & floatTbl,
std::unordered_map<std::string, Ghost_stringObj> & stringTbl,
std::unordered_map<std::string, Ghost_listObj> & listTbl)
{
std::string type = getType(var_name, varTbl, intTbl, floatTbl, stringTbl, listTbl);
std::string val = getVal(var_name, varTbl, intTbl, floatTbl, stringTbl, listTbl);
if(type == "Invalid Type" || val == "Invalid Value")
{
return "Invalid";
}
std::string ret = var_name + " " + type + " " + val;
return ret;
}
// helper function for parse()
// helper function for category 7: built-in function show_local()
void showLocal()
{
// corner case: there is no local variable
if(localVarTbl.empty())
{
std::cout << "No local Variable" << std::endl;
return;
}
std::cout << "Local Variables:" << std::endl;
for(auto it = localVarTbl.begin(); it != localVarTbl.end(); ++it)
{
std::string var_name = it->first;
std::string var_type = getType(var_name, localVarTbl, localIntTbl, localFloatTbl, localStringTbl, localListTbl);
std::string var_val = getVal(var_name, localVarTbl, localIntTbl, localFloatTbl, localStringTbl, localListTbl);
std::cout << var_name << " " << var_type << " " << var_val << std::endl;
}
}
// helper function for parse()
// helper function for category 7: built-in function show_global()
void showGlobal()
{
// corner case: there is no local variable
if(varTbl.empty())
{
std::cout << "No global Variable" << std::endl;
return;
}
std::cout << "Global Variables:" << std::endl;
for(auto it = varTbl.begin(); it != localVarTbl.end(); ++it)
{
std::string var_name = it->first;
std::string var_type = getType(var_name, varTbl, intTbl, floatTbl, stringTbl, listTbl);
std::string var_val = getVal(var_name, varTbl, intTbl, floatTbl, stringTbl, listTbl);
std::cout << var_name << " " << var_type << " " << var_val << std::endl;
}
}
// helper function for parse()
// helper function for category 7: built-in function show_global()
void showVar()
{
showLocal();
showGlobal();
}
};
#endif | true |
09a4e5f7ed526bd72734199d1066feda8626d727 | C++ | urisabate/Perosnal_Research_Audio-Music_Manager | /code/Game/Source/Enemy.h | UTF-8 | 2,190 | 2.625 | 3 | [
"MIT"
] | permissive | #ifndef __ENEMY_H__
#define __ENEMY_H__
#include "Entity.h"
#include "Animation.h"
#include "Render.h"
#include "DynArray.h"
#include "Point.h"
#include "SDL/include/SDL.h"
#define SPRITE_TILE_WIDTH 154
#define SPRITE_TILE_HEIGHT 141
struct SDL_Rect;
struct Animation;
enum EnemyClass
{
SMALL_WOLF,
BIG_WOLF,
MANTIS,
BIRD
};
struct MantisBullet
{
MantisBullet()
{
bulletRect = { 413, 1004, 10, 4 };
bulletSpritesheet = nullptr;
}
SDL_Rect bulletRect;
SDL_Texture* bulletSpritesheet;
bool active = false;
void BulletReset()
{
bulletRect = { 413, 1004, 10, 4 };
active = false;
}
void Update()
{
if (active) bulletRect.x -= 3;
}
void Draw()
{
if (active) app->render->DrawRectangle(bulletRect, { 55, 111, 53, 255 });
}
};
class Enemy : public Entity
{
public:
Enemy();
virtual ~Enemy();
void SetUp(EnemyClass xenemyClass, SDL_Rect collider, int xlvl, int xexp, int xhealth, int xstrength, int xdefense, int xvelocity);
void Jump();
void HighJump();
void SmallWolfAttack(unsigned short int typeOfAttack);
void BirdAttack(unsigned short int typeOfAttack);
void MantisAttack(unsigned short int typeOfAttack);
void MantisAttack1Logic(unsigned short int timer);
void MantisBulletShoot();
private: // Attack Time
short int attack = 0;
short int jumpTime = 0;
short int smallWolfTimeAttack1 = 0;
short int smallWolfTimeAttack2 = 0;
short int birdTimeAttack1 = 0;
short int birdTimeAttack2 = 0;
short int birdTimeAttack3 = 0;
short int mantisTimeAttack1 = 0;
short int mantisTimeAttack2 = 0;
short int mantisTimeAttack3 = 0;
public:
SDL_Rect colliderCombat;
bool jumping = false;
public:
friend class Combat;
int health;
int maxHealth;
int defense;
int strength;
int velocity;
int lvl;
int exp;
private:
DynArray<iPoint>* path;
EnemyClass enemyClass;
MantisBullet bullet[5];
public:
Animation cLittleWolfAwakeAnim;
Animation cLittleWolfIdleAnim;
Animation cLittleWolfRunAnim;
};
#endif // __ENEMY_H__
| true |
40eba4e85ef5ab5628dae92162654d1a055daaa2 | C++ | Shaheryar-Ali/FAST-NUCES-code | /Semester 3/Data Structures/Question 1 pof fucking assignment/Question 1/linked list.cpp | UTF-8 | 1,610 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include "linked list.h"
using namespace std;
list::list()
{
head = nullptr;
};
node* list::begin()
{
return head;
};
node* list::end()
{
node* temp = head;
while (temp->next != nullptr)
temp = temp->next;
return temp;
};
bool list::isEmpty()
{
if (head == nullptr)
return true;
else
return false;
};
void list::insert(char c, char d)
{
node* temp = new node;
if (isEmpty())
{
temp->data = d;
temp->next = nullptr;
head = temp;
}
else
{
temp = head;
while (temp != nullptr && temp->data != c)
temp = temp->next;
if (temp != nullptr)
{
node * temp2 = new node;
temp2->data = d;
temp2->next = temp->next;
temp->next = temp2->next;
}
}
};
void list::remove(char c)
{
node* temp = new node;
if (isEmpty())
{
cout << "List is empty\n";
}
else if (head->next == nullptr)
{
temp = head;
delete temp;
}
else
{
temp = head;
while (temp->next != nullptr && temp->data != c) //Lo
temp = temp->next;
if (temp->next != nullptr)
{
node* temp2 = new node;
temp2 = temp->next;
temp->next = temp->next->next;
delete temp2; //Delete node next to the key one
}
}
}
void list::insertatstart(char d)
{
node* temp = new node;
temp->data = d;
if (isEmpty())
{
temp->next = nullptr;
head = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void list::removeFromStart()
{
node* temp = new node;
if (isEmpty())
{
cout << "list is already empty";
}
else if (head->next == nullptr)
{
temp = head;
delete temp;
}
else
{
temp = head;
head = head->next;
delete temp;
}
}; | true |
7f3b96c0d0965915734d3ff6d15cadcff13b7dc4 | C++ | gruffieux/cpp-modules | /Sources/ctileengine.cpp | ISO-8859-1 | 11,481 | 2.515625 | 3 | [] | no_license | #include <ctileengine.h>
#include <canimation.h>
TileEngine::TileEngine()
{
int i;
TileData = Visual();
*TileData.getDimension() = Axe(TILE_SIZE, TILE_SIZE);
for (i = 0; i < MAX_LAYERS; i++)
Tiles[i] = NULL;
MapFile = DataFileList("", DataFileList::NO_INDEX);
}
TileEngine::TileEngine(int width, int height, double Camera_angle, double Camera_acc, double Camera_dec)
{
int i;
ScreenData.dimension.x = width;
ScreenData.dimension.y = height;
ScreenData.Camera = Mover(Camera_angle, Camera_acc, Camera_dec);
TileData = Visual();
*TileData.getDimension() = Axe(TILE_SIZE, TILE_SIZE);
for (i = 0; i < MAX_LAYERS; i++)
Tiles[i] = NULL;
MapFile = DataFileList("", DataFileList::NO_INDEX);
}
TileEngine::TileEngine(TileEngine &model)
{
int i;
ScreenData = *model.GetScreenData();
MapData = *model.GetMapData();
TileData = *model.GetTileData();
for (i = 0; i < MAX_LAYERS; i++)
Tiles[i] = NULL;
MapFile = *model.GetMapFile();
}
void TileEngine::InitTiles(int layer, void (CALLBACK *CallBackProc)())
{
int x, y;
if (!Tiles[layer])
{
Tiles[layer] = new Tile**[MapData.TileCount.x];
for (x = 0; x < MapData.TileCount.x; x++)
{
Tiles[layer][x] = new Tile*[MapData.TileCount.y];
for (y = 0; y < MapData.TileCount.y; y++)
{
Tiles[layer][x][y] = new Tile(MapData.TileID[y][x][layer]);
if (CallBackProc) CallBackProc();
}
}
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
if (x)
Tiles[layer][x][y]->SetLeft(Tiles[layer][x-1][y]);
if (x < MapData.TileCount.x - 1)
Tiles[layer][x][y]->SetRight(Tiles[layer][x+1][y]);
if (y)
Tiles[layer][x][y]->SetUp(Tiles[layer][x][y-1]);
if (y < MapData.TileCount.y - 1)
Tiles[layer][x][y]->SetDown(Tiles[layer][x][y+1]);
if (CallBackProc) CallBackProc();
}
}
}
void TileEngine::UpdateTiles(int layer, bool in, void (CALLBACK *CallBackProc)())
{
int x, y;
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
if (in)
Tiles[layer][x][y]->SetTileID(MapData.TileID[y][x][layer]);
else
MapData.TileID[y][x][layer] = Tiles[layer][x][y]->GetTileID();
if (CallBackProc) CallBackProc();
}
}
void TileEngine::DestroyTiles(int layer, void (CALLBACK *CallBackProc)())
{
int x, y;
if (Tiles[layer])
{
for (x = 0; x < MapData.TileCount.x; x++)
{
for (y = 0; y < MapData.TileCount.y; y++)
{
MapData.TileID[y][x][layer] = 0;
delete Tiles[layer][x][y];
Tiles[layer][x][y] = NULL;
if (CallBackProc) CallBackProc();
}
delete [] Tiles[layer][x];
Tiles[layer][x] = NULL;
}
delete [] Tiles[layer];
Tiles[layer] = NULL;
}
}
void TileEngine::InitMap(int TilesX, int TilesY, int TileIDCount, int layer, void (CALLBACK *CallBackProc)())
{
int x, y;
MapData.TileCount.x = TilesX;
MapData.TileCount.y = TilesY;
MapData.TileIDCount[layer] = TileIDCount;
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
MapData.TileID[y][x][layer] = 0;
InitTilesZone(x, y);
if (CallBackProc) CallBackProc();
}
UpdateMapAni(layer, "");
InitScreenData();
}
void TileEngine::InitScreenData()
{
ScreenData.VisibleTileCount.x = ScreenData.dimension.x / TileData.getDimension()->x;
ScreenData.VisibleTileCount.y = ScreenData.dimension.y / TileData.getDimension()->y;
ScreenData.MaxCamera.east = (MapData.TileCount.x - ScreenData.VisibleTileCount.x) * TileData.getDimension()->x;
ScreenData.MaxCamera.south = (MapData.TileCount.y - ScreenData.VisibleTileCount.y) * TileData.getDimension()->y;
}
void TileEngine::InitTilesZone(int x, int y)
{
MapData.TileZone[x].west = x * TileData.getDimension()->x;
MapData.TileZone[x].east = x * TileData.getDimension()->x + TileData.getDimension()->x;
MapData.TileZone[y].north = y * TileData.getDimension()->y;
MapData.TileZone[y].south = y * TileData.getDimension()->y + TileData.getDimension()->y;
}
void TileEngine::UpdateMapAni(int layer, Str BmpFileName)
{
if (BmpFileName.GetLength())
{
if (TileData.getAnimations()->ElementExist(layer))
delete Animation::getAnimationElement(layer, TileData.getAnimations());
TileData.addAni(layer, "", BmpFileName, 0, 0, 0, RGB(255, 255, 255), 0);
}
if (TileData.getAnimations()->ElementExist(layer))
{
MapData.TileIDCount[layer] = Animation::getAnimationElement(layer, TileData.getAnimations())->GetSprite()->GetHeight() / TILE_SIZE;
Animation::getAnimationElement(layer, TileData.getAnimations())->SetFrame(MapData.TileIDCount[layer], TileData.getDimension()->x, TileData.getDimension()->y);
}
}
void TileEngine::EmptyClipBoard(int layer)
{
int x, y;
for (x = 0; x < MAX_TILES_X; x++)
for (y = 0; y < MAX_TILES_Y; y++)
TilesCopy[y][x][layer] = 0;
}
void TileEngine::CopyToClipBoard(int layer)
{
int x, y;
EmptyClipBoard(layer);
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
TilesCopy[y][x][layer] = MapData.TileID[y][x][layer];
}
void TileEngine::CopyToClipBoard(int **data, int layer)
{
int x, y;
EmptyClipBoard(layer);
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
TilesCopy[y][x][layer] = data[x][y];
}
void TileEngine::PasteClipBoard(int LayerSrc, int LayerDest)
{
int x, y;
InitTiles(LayerDest);
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
MapData.TileID[y][x][LayerDest] = TilesCopy[y][x][LayerSrc];
Tiles[LayerDest][x][y]->SetTileID(TilesCopy[y][x][LayerSrc]);
}
}
bool TileEngine::LoadMap(int layer, void (CALLBACK *CallBackProc)())
{
int x, y;
if (!MapFile.Open(true, false, false))
return false;
// Les donnes de la map sont rcupres dans un fichier .dat
MapData.TileCount.x = MapFile.Read(); // On rcupre la dimension x
MapData.TileCount.y = MapFile.Read(); // On rcupre la dimension y
MapData.TileIDCount[layer] = MapFile.Read(); // On rcupre le nombre d'id
// On rcupre l'id et la zone des tiles
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
MapData.TileID[y][x][layer] = MapFile.Read();
InitTilesZone(x, y);
if (CallBackProc) CallBackProc();
}
MapFile.Close();
UpdateMapAni(layer, "");
InitScreenData();
return true;
}
bool TileEngine::SaveMap(int layer, void (CALLBACK *CallBackProc)())
{
int x, y;
if (!MapFile.Open(false, true, true))
return false;
MapFile.Write(MapData.TileCount.x);
MapFile.Write(MapData.TileCount.y);
MapFile.Write(MapData.TileIDCount[layer]);
for (x = 0; x < MapData.TileCount.x; x++)
for (y = 0; y < MapData.TileCount.y; y++)
{
MapFile.Write(MapData.TileID[y][x][layer]);
if (CallBackProc) CallBackProc();
}
MapFile.Close();
return true;
}
void TileEngine::RenderMap(int layer)
{
int i, x, y;
Axe Start, End;
TileData.getVisibleZone()->left = TileData.getVisibleZone()->top = 0;
TileData.getVisibleZone()->right = TileData.getDimension()->x;
TileData.getVisibleZone()->bottom = TileData.getDimension()->y;
Start.x = ScreenData.Camera.getPosition()->x >> 5;
Start.y = ScreenData.Camera.getPosition()->y >> 5;
End.x = Start.x + ScreenData.VisibleTileCount.x;
End.y = Start.y + ScreenData.VisibleTileCount.y;
x = ScreenData.Camera.getPosition()->x & 0x0000001F;
y = ScreenData.Camera.getPosition()->y & 0x0000001F;
//Si la coordonne x de la camra est divisible par 32
if (!x)
End.x--;
//Sinon dplace rcDest gauche pour placer la premire colonne de briques
else
{
TileData.getVisibleZone()->left -= x;
TileData.getVisibleZone()->right -= x;
}
//Si la coordonne y de la camra est divisible par 32
if (!y)
End.y--;
//Sinon dplace rcDest en haut pour placer la premire ligne de briques
else
{
TileData.getVisibleZone()->top -= y;
TileData.getVisibleZone()->bottom -= y;
}
//Vrifie qu'on excde pas la limite
if (End.x > MapData.TileCount.x)
End.x = MapData.TileCount.x;
if (End.y > MapData.TileCount.y)
End.y = MapData.TileCount.y;
for (x = Start.x; x <= End.x; x++)
{
for (y = Start.y; y <= End.y; y++)
{
i = MapData.TileID[y][x][layer];
//Affiche uniquement une brique ayant l'id suprieur 0
if (i > 0)
TileData.runAni(layer, i);
//Avance rcDest
TileData.getVisibleZone()->top += TileData.getDimension()->y;
TileData.getVisibleZone()->bottom += TileData.getDimension()->y;
}
//Rinitialise rcDest en haut de la prochaine colonne
TileData.getVisibleZone()->left += TileData.getDimension()->x;
TileData.getVisibleZone()->right += TileData.getDimension()->x;
TileData.getVisibleZone()->top -= ((End.y - Start.y + 1) << 5);
TileData.getVisibleZone()->bottom -= ((End.y - Start.y + 1) << 5);
}
}
void TileEngine::Scroll(Mover *pMover, CardinalPoint *MaxDistance, bool stop, bool rebound)
{
if (pMover)
{
pMover->GenerateDirection();
ScreenData.Camera.SetAngle(pMover->GetAngle());
ScreenData.Camera.SetAcceleration(pMover->GetAcceleration());
ScreenData.Camera.SetDeceleration(pMover->GetDeceleration());
ScreenData.Camera.SetMagnitude(pMover->GetMagnitude());
*ScreenData.Camera.GetDirection() = CardinalPoint(pMover->GetDirection()->west, pMover->GetDirection()->east, pMover->GetDirection()->north, pMover->GetDirection()->south);
*ScreenData.Camera.GetBlockedDirection() = CardinalPoint(pMover->GetBlockedDirection()->west, pMover->GetBlockedDirection()->east, pMover->GetBlockedDirection()->north, pMover->GetBlockedDirection()->south);
if (((pMover->GetDirection()->west == 1) && (pMover->GetBlockedDirection()->west == 0) && ((ScreenData.Camera.getPosition()->x == ScreenData.MaxCamera.west) | (pMover->getPosition()->x > ScreenData.dimension.x / 2))) |
((pMover->GetDirection()->east == 1) && (pMover->GetBlockedDirection()->east == 0) && ((ScreenData.Camera.getPosition()->x == ScreenData.MaxCamera.east) | (pMover->getPosition()->x + pMover->getDimension()->x < ScreenData.dimension.x / 2))) |
((pMover->GetDirection()->north == 1) && (pMover->GetBlockedDirection()->north == 0) && ((ScreenData.Camera.getPosition()->y == ScreenData.MaxCamera.north) | (pMover->getPosition()->y > ScreenData.dimension.y / 2))) |
((pMover->GetDirection()->south == 1) && (pMover->GetBlockedDirection()->south == 0) && ((ScreenData.Camera.getPosition()->y == ScreenData.MaxCamera.south) | (pMover->getPosition()->y + pMover->getDimension()->y < ScreenData.dimension.y / 2))))
{
if (MaxDistance)
{
if ((pMover->getPosition()->x <= MaxDistance->west) && (ScreenData.Camera.getPosition()->x == ScreenData.MaxCamera.west))
stop = rebound = false;
if ((pMover->getPosition()->x + pMover->getDimension()->x >= MaxDistance->east) && (ScreenData.Camera.getPosition()->x == ScreenData.MaxCamera.east))
stop = rebound = false;
if ((pMover->getPosition()->y <= MaxDistance->north) && (ScreenData.Camera.getPosition()->y == ScreenData.MaxCamera.north))
stop = rebound = false;
if ((pMover->getPosition()->y + pMover->getDimension()->y >= MaxDistance->south) && (ScreenData.Camera.getPosition()->y == ScreenData.MaxCamera.south))
stop = rebound = false;
}
pMover->Move(MaxDistance, stop, rebound);
}
else
{
*pMover->GetCurrentObstacle() = CardinalPoint();
*pMover->GetBlockedDirection() = CardinalPoint();
ScreenData.Camera.Move(&ScreenData.MaxCamera, stop, rebound);
}
}
else
ScreenData.Camera.Move(&ScreenData.MaxCamera, stop, rebound);
}
| true |
f9010aafc49e5b6e7070dc447c558899e09aa7b7 | C++ | AmazingCaddy/leetcode | /Unique_Binary_Search_Trees_II.cpp | UTF-8 | 1,673 | 2.90625 | 3 | [] | no_license | #define DEBUG
#ifdef DEBUG
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_set>
#include <stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
#endif
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int maxn = 10004;
TreeNode* idx[maxn];
class Solution {
private:
void print(const vector<int>& v) {
for (int i = 0; i < v.size(); i ++) {
if (i) {
cout << " ";
}
cout << v[i];
}
}
vector<TreeNode *> dfs(int left, int right) {
if (left > right) {
return vector<TreeNode *>(1, NULL);
}
vector<TreeNode *> res;
for (int k = left; k <= right; k ++) {
vector<TreeNode *> lt = this->dfs(left, k - 1);
vector<TreeNode *> rt = this->dfs(k + 1, right);
for (int i = 0; i < lt.size(); i ++) {
for (int j = 0; j < rt.size(); j ++) {
TreeNode *root = new TreeNode(k);
root->left = lt[i];
root->right = rt[j];
res.push_back(root);
}
}
}
return res;
}
public:
void test() {
vector<TreeNode *> ans = this->generateTrees(3);
cout << ans.size() << "\n";
}
vector<TreeNode *> generateTrees(int n) {
vector<TreeNode *> ans = this->dfs(1, n);
return ans;
}
};
#ifdef DEBUG
int main(int argc, char const *argv[]) {
Solution *sol = new Solution();
sol -> test();
delete sol;
return 0;
}
#endif
| true |
2bf6f038c2a5db8d5a4dfcb2fb2ab86946978e1b | C++ | NishaMcNealis/practice-projects | /passwordChecker.cpp | UTF-8 | 1,262 | 3.421875 | 3 | [] | no_license | #include <string>
#include <iostream>
using namespace std;
bool passwordChecker(string password) {
if (password.size() < 8 || password.size() > 15) return false;
bool hasDigit = false;
bool hasLower = false;
bool hasUpper = false;
bool hasSpecial = false;
for (int i = 0; i < password.size(); i++) {
if (password[i] == ' ') {
return false;
}
else if (password[i] >= '0' && password[i] <= '9') {
hasDigit = true;
}
else if (password[i] >= 'a' && password[i] <= 'z') {
hasLower = true;
}
else if (password[i] >= 'A' && password[i] <= 'Z') {
hasUpper = true;
}
else if ((password[i] >= '!' && password[i] <= '/') || (password[i] >= ':' && password[i] <= '@')) {
hasSpecial = true;
}
}
return (hasDigit && hasLower && hasSpecial && hasUpper);
}
int main(int argc, char *argv[])
{
cout << passwordChecker("GeeksForGeeks") << endl;
cout << passwordChecker("Geek$ForGeeks7") << endl;
cout << passwordChecker("$9nM$") << endl;
cout << passwordChecker("has space") << endl;
cout << passwordChecker("hasnoDig!T") << endl;
cout << passwordChecker("NOL0W#R") << endl;
cout << passwordChecker("noupper8*") << endl;
cout << passwordChecker("noSPECIAL3") << endl;
}
| true |
a2ff6c0eb6eb4d0d73b18ce920bf2f1d5a828537 | C++ | KertAles/Osvajalec-Game | /pathfinding/distance.cpp | UTF-8 | 473 | 2.859375 | 3 | [] | no_license | #include "distance.h"
Distance::Distance() { }
double Distance::pointDistance(GridSquare *pos1, GridSquare *pos2) {
double distance = 0;
if(abs(pos1->getX()/SQUARESIZE - pos2->getX()/SQUARESIZE) >
abs(pos1->getY()/SQUARESIZE - pos2->getY()/SQUARESIZE)) {
distance = abs(pos1->getX()/SQUARESIZE - pos2->getX()/SQUARESIZE);
}
else {
distance = abs(pos1->getY()/SQUARESIZE - pos2->getY()/SQUARESIZE);
}
return distance;
}
| true |
867e7a7889225678afaae14c396af0045b659175 | C++ | Gabo250/Halado_Algoritmusok_Beadando | /AdvAlg-Stud/Optimization/Main.cpp | UTF-8 | 1,024 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include <string>
#include "SmallestBoundaryPolygonSolver.h"
#include "SmallestBoundaryPolygon.h"
#include "SmallestBoundaryPolygonSolver_Simulated.h"
#include "TravellingSalesman.h"
#include "TravellingSalesmanSolver.h"
void SmallestBoundaryPolygon_HillClimbingStochastic()
{
SmallestBoundarySolver problem(10, "Log\\SmallestBoundaryPolygon_HillClimbingStochastic.txt");
problem.loadPointsFromFile("Input\\Points.txt");
problem.GenerateRandomPointsOnaCircle();
problem.Optimalize(1500, 10.0f);
}
void SmallestBoundaryPolygon_Simulated()
{
SmallestBoundarySolver_Simulated problem("Log\\SmallestBoundaryPolygon_Simulated.txt", 10);
problem.Optimalize(1500, 10.0f);
}
void TravellingSalesmanSolv()
{
TravellingSalesmanSolver problem("Log\\TravellingSalesman.txt");
problem.loadTownsFromFile("Input\\Towns.txt");
problem.GeneticAlgorithm(2000);
}
int main()
{
//SmallestBoundaryPolygon_HillClimbingStochastic();
//TravellingSalesmanSolv();
SmallestBoundaryPolygon_Simulated();
return 0;
} | true |
ee15d3bf5489fa11ac07bcddad97cfb008da343c | C++ | filbetka/small_projects | /C++/network_client/network_client/network_client.cpp | UTF-8 | 4,174 | 3.390625 | 3 | [] | no_license | #include "network_client.h"
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <unistd.h>
#include <cerrno>
/**
* @class Network_Client
* @details The class management network access
* by client with TCP/IP protocol. The client
* is service for all address family (IPv4, IPv6).
*/
/**
* @brief Network_Client::Network_Client
* @param address - IP address to connect
* @param port - port number to connect
*/
Network_Client::Network_Client(string address, int port):
client_socket(move(address), port)
{
read_timeout_ms = 100;
}
Network_Client::~Network_Client()
{
if (client_socket.Is_Connected())
this->Connection_Close();
}
/**
* @brief Network_Client::Connection_Open
* @return if connection has been opened
*/
bool Network_Client::Connection_Open()
{
return client_socket.Connection_Open();
}
/**
* @brief Network_Client::Connection_Close
* @details Close connection and socket
*/
void Network_Client::Connection_Close()
{
client_socket.Connection_Close();
}
/**
* @brief Network_Client::Is_Connected
* @return connection is active with server.
*/
bool Network_Client::Is_Connected() const
{
return client_socket.Is_Connected();
}
/**
* @brief Network_Client::Write
* @param data - data to write
* @details Write data to server
*/
void Network_Client::Write(const string& data)
{
int status = 0;
// send text
status = send(
client_socket.Connection(),
data.c_str(),
data.length(),
MSG_NOSIGNAL);
// write error
if (status < 0)
{
cerr << "Network_Client::Write: "
"Connection error\n";
this->Connection_Close();
}
}
/**
* @brief Network_Client::Read
* @details Read data from server
* @return red bytes as string
*/
#include <array>
string Network_Client::Read()
{
int socket_fd = client_socket.Connection();
int status = 0;
int timeout_sec = read_timeout_ms / 1000;
int timeout_ms = read_timeout_ms - timeout_sec * 1000;
fd_set read_set;
timeval timeout = {};
timeout.tv_sec = timeout_sec;
timeout.tv_usec = timeout_ms;
FD_ZERO(&read_set);
FD_SET(socket_fd, &read_set);
status = select(
FD_SETSIZE,
&read_set,
nullptr,
nullptr,
&timeout);
if (status < 0)
{
cerr << "Network_Client::Read: select error\n";
cerr << strerror(errno) << endl;
return "";
}
if (status == 0) // timeout
usleep(10000); // 10 ms
if (not FD_ISSET(socket_fd, &read_set))
return "";
// read data
char buffer[4096] = {0};
status = read(socket_fd, buffer, 4096);
// check if error
if (status < 0)
{
cerr << "Network_Client::Read: read string\n";
cerr << strerror(errno) << endl;
return "";
}
// return read data
return string(buffer, status);
}
/**
* @brief Network_Client::Write
* @param data - data to write
* @param size - data size to write
* @details Write data to server
*/
void Network_Client::Write(char* data, size_t size)
{
int status = 0;
// send text
status = send(
client_socket.Connection(),
data, size,
MSG_NOSIGNAL);
// write error
if (status < 0)
{
cerr << "Network_Client::Write: "
"Connection error\n";
this->Connection_Close();
}
}
/**
* @brief Network_Client::Read
* @param buffer - data container
* @param size - data size to read
* @details Read data from server
*/
void Network_Client::Read(char* buffer, size_t size)
{
int status = 0;
// read data
status = read(
client_socket.Connection(),
buffer,
size);
// check if error
if (status < 0)
{
cerr << "Wifi_Client::Read: "
"Connection error\n";
this->Connection_Close();
}
}
/**
* @brief Network_Client::Set_Read_Timeout
* @param timeout_ms - read timeout in ms
* @details Read methods use this to break waiting.
*/
void Network_Client::Set_Read_Timeout(int timeout_ms)
{
read_timeout_ms = timeout_ms;
}
| true |
9ff873f49a3bb559b2bd174e1d3e50eca05dcc62 | C++ | facku24/DesignPatters | /Gamming/main1.cpp | UTF-8 | 311 | 2.671875 | 3 | [] | no_license | #include "inputHandler1.h"
#include <iostream>
/*
COMPILE: g++ main1.cpp command1.cpp inputHandler1.cpp
*/
int main(int argc, char* argv[])
{
InputHandler ih;
char c;
do
{
std::cin >> c;
ih.handleInput(c);
} while (c != 'q');
std::cout << "Exit" << std::endl;
return 0;
} | true |
38177dbd31dc32631ecaccb5db39b11a7033f0b7 | C++ | csjuribe/cpp_programming | /ch2/7g.cpp | UTF-8 | 555 | 3.640625 | 4 | [] | no_license | //include statements
#include <iostream>
#include <string>
//using namespace statement
using namespace std;
int main()
{
const int SECRET = 11;
const double RATE = 12.50;
int num1, num2, newNum;
string name;
double hoursWorked, wages;
cout<<"Please enter two integers."<<endl;
cin>>num1>>num2;
cout<<"The value of num 1 is "<<num1<<" and value of num2 is "<<num2<<endl;
newNum = 2*num1+num2;
cout<<"The value of newNum = "<<newNum<<endl;
newNum += SECRET;
cout<<"The updated value of newNum is " <<newNum<<endl;
return 0;
}
| true |
63ef2a46ace0b3706e38928b3192609d7138fc09 | C++ | y761823/ACM-code | /POJ/p2455.cpp | UTF-8 | 2,456 | 2.5625 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 210;
const int MAXE = 40010 * 2;
const int INF = 0x7f7f7f7f;
struct Dinic {
int n, m, st, ed, ecnt, maxlen;
int head[MAXN];
int cur[MAXN], d[MAXN];
int to[MAXE], next[MAXE], flow[MAXE], cap[MAXE], len[MAXE];
void init(int ss, int tt) {
st = ss; ed = tt;
ecnt = 2;
memset(head, 0, sizeof(head));
}
void add_edge(int u, int v, int c, int l) {
len[ecnt] = l; to[ecnt] = v; cap[ecnt] = c; flow[ecnt] = 0; next[ecnt] = head[u]; head[u] = ecnt++;
len[ecnt] = l; to[ecnt] = u; cap[ecnt] = c; flow[ecnt] = 0; next[ecnt] = head[v]; head[v] = ecnt++;
}
bool bfs() {
memset(d, 0, sizeof(d));
queue<int> que; que.push(st);
d[st] = 1;
while(!que.empty()) {
int u = que.front(); que.pop();
for(int p = head[u]; p; p = next[p]) {
if(len[p] > maxlen) continue;
int v = to[p];
if(!d[v] && cap[p] > flow[p]) {
d[v] = d[u] + 1;
que.push(v);
if(v == ed) return true;
}
}
}
return d[ed];
}
int dfs(int u, int a) {
if(u == ed || a == 0) return a;
int outflow = 0, f;
for(int &p = cur[u]; p; p = next[p]) {
if(len[p] > maxlen) continue;
int v = to[p];
if(d[u] + 1 == d[v] && (f = dfs(v, min(a, cap[p] - flow[p]))) > 0) {
flow[p] += f;
flow[p ^ 1] -= f;
outflow += f;
a -= f;
if(a == 0) break;
}
}
return outflow;
}
int Maxflow(int mlen) {
int ans = 0; maxlen = mlen;
while(bfs()) {
for(int i = 0; i <= ed; ++i) cur[i] = head[i];
ans += dfs(st, INF);
}
return ans;
}
} G;
int main() {
int n, m, T, left = 0, right = 0;
scanf("%d%d%d", &n, &m, &T);
G.init(1, n);
for(int i = 0; i < m; ++i) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
G.add_edge(a, b, 1, c);
if(right < c) right = c;
}
while(left < right) {
memset(G.flow, 0, sizeof(G.flow));
int mid = (left + right) >> 1;
if(G.Maxflow(mid) < T) left = mid + 1;
else right = mid;
}
printf("%d\n", right);
}
| true |
63e30222eccd023db0b27fab1b2e721819bb06c6 | C++ | mismayil/cs488 | /A5/GeometryNode.cpp | UTF-8 | 1,686 | 2.65625 | 3 | [] | no_license | #include "GeometryNode.hpp"
#include "TextureMaterial.hpp"
//---------------------------------------------------------------------------------------
GeometryNode::GeometryNode(
const std::string & name, Primitive *prim, Material *mat )
: SceneNode( name )
, m_material( mat )
, m_primitive( prim )
{
m_nodeType = NodeType::GeometryNode;
}
GeometryNode::~GeometryNode() {
}
void GeometryNode::setMaterial( Material *mat )
{
// Obviously, there's a potential memory leak here. A good solution
// would be to use some kind of reference counting, as in the
// C++ shared_ptr. But I'm going to punt on that problem here.
// Why? Two reasons:
// (a) In practice we expect the scene to be constructed exactly
// once. There's no reason to believe that materials will be
// repeatedly overwritten in a GeometryNode.
// (b) A ray tracer is a program in which you compute once, and
// throw away all your data. A memory leak won't build up and
// crash the program.
m_material = mat;
}
TAO* GeometryNode::intersect(Ray ray) {
ray.o = glm::vec3(get_inverse() * glm::vec4(ray.o, 1));
ray.d = glm::vec3(get_inverse() * glm::vec4(ray.d, 0));
TAO *tao = m_primitive->intersect(ray);
if (!tao) return NULL;
glm::vec3 point = ray.o + (float) tao->taomin * ray.d;
TextureMaterial *tmaterial = dynamic_cast<TextureMaterial *>(m_material);
if (tmaterial) tmaterial->setuv(m_primitive->mapuv(point, tao->nmin, tmaterial->getTexture()));
tao->materialmin = m_material;
tao->materialmax = m_material;
tao->nmin = glm::transpose(glm::mat3(get_inverse())) * tao->nmin;
tao->nmax = glm::transpose(glm::mat3(get_inverse())) * tao->nmax;
return tao;
}
| true |
0875178fc0442fa22a07545999c7b98a2bc370e9 | C++ | chow97/project2 | /project2.cpp | UTF-8 | 6,774 | 3.375 | 3 | [] | no_license | // Name : Chow
// I couldn't get everything in the criteria but I tried my best
//Raymond Aguilera!
//Hey there
#include <iostream>
#include <cstring>
#include <iomanip>
#include <cctype>
#include <fstream>
using namespace std;
// named constants
const int MAX_CHAR = 101;
const int MUSIC_LIBRARY_CAP = 100;
const int TITLE = 20;
const int ARTIST = 20;
const int ALBUM = 20;
const int DURATION = 20;
// define a new data type
struct SongEntry
{
char title[MAX_CHAR];
char artist[MAX_CHAR];
char duration[MAX_CHAR];
char album[MAX_CHAR];
};
// USER INTERFACE RELATED FUNCTIONS
void displayMenu();
char readInCommand();
void processCommand(char command, SongEntry list[], int& listSize);
void readInEntry(SongEntry& anEntry);
void readInArtist(char artist[]);
void readInAlbum(char album[]);
// DATABASE RELATED FUNCTIONS
void displayAll(const SongEntry list[], int listSize);
void addEntry(const SongEntry& anEntry, SongEntry list[], int& listSize);
bool searchEntry(const char artist[], SongEntry& match, const SongEntry list[], int listSize);
// use external file
void loadMusicLibrary(const char fileName[], SongEntry list[], int& listSize);
void saveMusicLibrary(const char fileName[], const SongEntry list[], int listSize);
// Standard input tools
void readString(const char prompt[], char inputStr[], int maxChar);
int main()
{
char command;
SongEntry list[MUSIC_LIBRARY_CAP];
int listSize = 0;
char fileName[] = "songs.txt";
loadMusicLibrary(fileName, list, listSize);
displayMenu();
command = readInCommand();
while (command != 'q')
{
processCommand(command, list, listSize);
displayMenu();
command = readInCommand();
}
cout << endl << "Thank you" << endl << endl;
saveMusicLibrary(fileName, list, listSize);
return 0;
}
// this function reads a c-string from standard input
void readString(const char prompt[], char inputStr[], int maxChar)
{
cout << endl << prompt;
//read until it reach maxChar limit or encounters a '\n'
cin.get(inputStr, maxChar, '\n');
while(!cin)
{
cin.clear();
cin.ignore(100, '\n');
cout << endl << prompt;
cin.get(inputStr, maxChar, '\n');
}
//throw away the '\n'
cin.ignore(100, '\n');
}
// This function displays the main menu.
void displayMenu()
{
cout << endl << "Welcome to your music library!" << endl << endl;
cout << "Choose from the following options: " << endl;
cout << "\t1. Add an entry" << endl;
cout << "\t2. List all entries" << endl;
cout << "\t3. Search Songs by Artist name" << endl;
cout << "\t4. Search Songs by Album name" << endl;
cout << "\tq. Exit this program" << endl << endl;
}
char readInCommand()
{
char cmd;
cout << endl << "Please enter command(1, 2, 3, 4 or q): ";
cin >> cmd;
cin.ignore(100, '\n');
return tolower(cmd);
}
void processCommand(char command, SongEntry list[], int& listSize)
{
SongEntry entry;
char title[MAX_CHAR];
char artist[MAX_CHAR];
char album[MAX_CHAR];
switch(command)
{
case '1':
readInEntry(entry);
addEntry(entry, list, listSize);
break;
case '2':
displayAll(list, listSize);
break;
case '3':
readInArtist(artist);
if(searchEntry(artist, entry, list, listSize))
cout << endl << "The song of " << artist << ": " << entry.title << endl;
else
cout << endl << "Invalid" << endl;
break;
case '4':
readInAlbum(album);
break;
default:
cout << endl << "Wrong Input!" << endl;
break;
}
}
//this function reads in a song entry
void readInEntry(SongEntry& anEntry)
{
char title[MAX_CHAR];
char artist[MAX_CHAR];
char duration[MAX_CHAR];
char album[MAX_CHAR];
//read input title, artist, duration, album
readString("Please enter the Title of the song: ", title, MAX_CHAR);
readString("Please enter the Artist's name: ", artist, MAX_CHAR);
readString("Please enter the Duration of the song: ", duration, MAX_CHAR);
readString("Please enter the Album of the song: ", album, MAX_CHAR);
//populate the pased in object
strcpy(anEntry.title, title);
strcpy(anEntry.artist, artist);
strcpy(anEntry.duration, duration);
strcpy(anEntry.album, album);
}
void readInArtist(char artist[])
{
readString("Plese enter the Name of the Artist: ", artist, MAX_CHAR);
}
void readInAlbum(char album[])
{
readString("Please enter the Name of the Album: ", album, MAX_CHAR);
}
//this function display all songs in file
void displayAll(const SongEntry list[], int listSize)
{
int index;
cout << setw(TITLE) << "Title" << setw(ARTIST) << "Artist" << setw(DURATION) << "Duration" << setw(ALBUM) << "Album" << endl;
for(index = 0; index < listSize; index++)
{
cout << setw(TITLE) << list[index].title << setw(ARTIST) << list[index].artist << setw(DURATION) << list[index].duration << setw(ALBUM) << list[index].album << endl;
}
}
// this function add entry to the end of the file
void addEntry(const SongEntry& anEntry, SongEntry list[], int& listSize)
{
strcpy(list[listSize].title, anEntry.title);
strcpy(list[listSize].artist, anEntry.artist);
strcpy(list[listSize].duration, anEntry.duration);
strcpy(list[listSize].album, anEntry.album);
listSize++;
}
// this function searches entries
bool searchEntry(const char artist[], SongEntry& match, const SongEntry list[], int listSize)
{
int index;
for(index = 0; index < listSize; index++)
{
if(strcmp(artist, list[index].artist) == 0)
{
strcpy(match.title, list[index].title);
strcpy(match.artist, list[index].artist);
break;
}
}
if(index == listSize)
return false;
else
return true;
}
//this function load everthing in data file
void loadMusicLibrary(const char fileName[], SongEntry list[], int& listSize)
{
ifstream in;
char title[MAX_CHAR];
char artist[MAX_CHAR];
char duration[MAX_CHAR];
char album[MAX_CHAR];
SongEntry anEntry;
in.open(fileName);
if(!in)
{
in.clear();
cerr << endl << "Fail to open " << fileName << " for input!" << endl << endl;
exit(1);
}
in.get(title, MAX_CHAR, ';');
while(!in.eof())
{
in.get();
in.get(artist, MAX_CHAR, ';');
in.get();
in.get(duration, MAX_CHAR, ';');
in.get();
in.get(album, MAX_CHAR, '\n');
in.ignore(100, '\n');
strcpy(anEntry.artist, artist);
strcpy(anEntry.title, title);
strcpy(anEntry.duration, duration);
strcpy(anEntry.album, album);
addEntry(anEntry, list, listSize);
in.get(title, MAX_CHAR, ';');
}
in.close();
}
void saveMusicLibrary(const char fileName[], const SongEntry list[], int listSize)
{
ofstream out;
int index;
out.open(fileName);
if(!out)
{
out.clear();
cerr << endl << "Fail to open " << fileName << " for output!" << endl << endl;
exit(1);
}
for (index = 0; index < listSize; index++)
{
out << list[index].title << ';' << list[index].artist << ';' << list[index].duration << ';' << list[index].album << endl;
}
out.close();
}
| true |
e109c82e449c51ae8e5a80dfd877d090d4eb9112 | C++ | sakshi-chauhan/CodechefCppCodes | /JAN15/RECMSG.cpp | UTF-8 | 855 | 2.78125 | 3 | [] | no_license | #include<iostream>
#include<stdio.h>
#define gc getchar_unlocked
#define pc putchar_unlocked
int scan(){
int n=0;
char ch;
ch=gc();
while(ch<'0' || ch >'9')
ch=gc();
while(ch>='0' && ch<='9'){
n=n*10+ch-'0';
ch=gc();
}
return n;
}
int print(int n){
int i=0;
char ch[6]={-1};
while(n>0){
ch[i++]='0'+n%10;
n=n/10;
}
while(i-->0){
pc(ch[i]);
}
pc('\n');
}
int main(){
int T;
long long int sum;
int over[26];
std::string str;
for( int i = 0 ; i < 26 ; i++ )
over[i]=i+1;
//std::cin>>T;
T = scan();
while( T-- ){
std::cin>>str;
sum = 0;
for( int j = 0 ; j < str.length(); j++ )
sum += over[str[j]-'a'];
//std::cout<<sum<<"\n";
print(sum);
}
return 0;
}
| true |
0c7647b59d06e8141c06fa3813d7dea48f8418d9 | C++ | jaypatel73/NYUTandonBridge | /hw5/gr2180_hw5_q5.cpp | UTF-8 | 2,138 | 3.890625 | 4 | [] | no_license | //File Name: gr2180_hw5_q5.cpp
//Author: Gowtham Rajeshshekaran
//Email Address: gr2180@nyu.edu
//Assignment Number: Hw5 Q5
//Description: Program to print all the perfect and amicable numbers within the given range
//Last Changed: Aug 14, 2020
#include <iostream>
#include <cmath>
using namespace std;
const int ZERO = 0;
const int ONE = 1;
const int TWO = 2;
void analyzeDividors(int num, int& outCountDivs, int& outSumDivs);
//Takes a number "num" and updates two output
//parameters with the number of num's proper divisors and their sum.
bool isPerfect(int num);
//Checks if the given number is a perfect number
Organism main() {
int inputNum;
cout << "Please enter a positive integer >= 2: ";
cin >> inputNum;
if (inputNum < TWO) {
cout << "The number should be greater than 2\n";
return ONE;
}
cout << "Perfect numbers between 2 and " << inputNum << endl;
for (int num = 2; num <= inputNum; num++) {
if (isPerfect(num)){
cout << num << endl;
}
}
cout << endl << "Pairs of amicable numbers between 2 and " << inputNum << endl;
for (int num = 2; num <= inputNum; num++) {
int countDivsN = 0, sumDivsN = 0;
int m, countDivsM = 0, sumDivsM = 0;
analyzeDividors(num, countDivsN, sumDivsN);
m = sumDivsN;
analyzeDividors(m, countDivsM, sumDivsM);
if ((sumDivsM == num) && (num != m) && (m <= inputNum)) {
cout << "(" << num << "," << m << ")\n";
}
}
return ZERO;
}
void analyzeDividors(int num, int& outCountDivs, int& outSumDivs) {
for(int n = 1; n < sqrt(num); n++ ) {
if(num % n == ZERO){
outCountDivs++;
outSumDivs += n;
}
}
for(int n = sqrt(num); n > ONE; n--) {
if(num % n == ZERO) {
if((num / n) != num) {
outCountDivs++;
outSumDivs += num / n;
}
}
}
}
bool isPerfect(int num) {
int countDivs = 0, sumDivs = 0;
analyzeDividors(num, countDivs, sumDivs);
if (sumDivs == num) {
return true;
}
else
return false;
}
| true |
963600f03903932cd9a99dc26542942323f20a77 | C++ | henne90gen/RacingToHell | /src/Renderer.h | UTF-8 | 2,197 | 2.546875 | 3 | [] | no_license | #pragma once
#include <glad/glad.h>
#include <glm/vec2.hpp>
#include <glm/vec4.hpp>
#include "MyMath.h"
#include "Platform.h"
// forward declarations
struct GameState;
struct Input;
enum AtomPlane {
BACKGROUND = 0,
AI = 1,
AI_BULLETS = 2,
PLAYER = 3,
PLAYER_BULLETS = 4,
GAME_UI = 5,
MENU = 6,
};
namespace Render {
const char firstCharacter = ' ';
const char lastCharacter = '~';
enum FontSize { Small, Medium, Large };
struct Texture {
uint32_t width, height;
uint8_t bytesPerPixel;
GLuint id;
int xDivision = 1;
int yDivision = 1;
};
struct Character {
char value;
bool hasKerning;
glm::vec2 size, bearing;
float advance;
float kerning[lastCharacter - firstCharacter];
Render::Texture texture;
};
struct Rectangle {
Math::Rectangle dimensions;
glm::vec4 color;
};
struct Triangle {
glm::vec2 p1, p2, p3;
glm::vec4 color;
};
struct TextureRectangle {
Texture texture;
Math::Rectangle dimensions;
glm::vec2 direction;
int tileIndex;
};
struct Circle {
glm::vec2 position;
float radius;
glm::vec4 color;
};
struct Text {
glm::vec2 position;
char characters[50];
FontSize fontSize;
glm::vec4 color;
};
void clearScreen(uint32_t color);
void flushBuffer(Platform &platform);
void pushText(GameState *gameState, std::string text, glm::vec2 position, FontSize fontSize, glm::vec4 color,
AtomPlane plane);
void pushTriangle(GameState *gameState, glm::vec2 point1, glm::vec2 point2, glm::vec2 point3, glm::vec4 color,
float plane);
void pushRectangle(GameState *gameState, Math::Rectangle dimensions, glm::vec4 color, float plane);
void pushCircle(GameState *gameState, glm::vec2 position, float radius, glm::vec4 color, AtomPlane plane);
void pushTexture(GameState *gameState, Texture *texture, glm::vec2 position, glm::vec2 size, glm::vec2 direction,
int tileIndex = 0, AtomPlane plane = AtomPlane::BACKGROUND);
void pushAnimation(GameState *gameState, Texture *texture, glm::vec2 position, glm::vec2 size, unsigned *tileIndex,
AtomPlane plane, int timing = 1);
} // namespace Render
| true |
63e3fc6651af42b16dceb4052069ba364971dc10 | C++ | Jenny-Smolensky/HnJ_2ndRoad | /server_side/MyParallelServer.cpp | UTF-8 | 3,107 | 2.859375 | 3 | [] | no_license | //
// Created by jenny on 1/15/19.
//
#include "MySerialServer.h"
using namespace server_side;
#include "MyParallelServer.h"
/**
* listen thread
* @param arg
* @return
*/
void* threadListen(void* arg) {
auto * params = (MyParallelServer*)arg;
try {
params->parallellListen();
} catch (invalid_argument& e) {
cout << "server disconnected" << endl;
} catch (const char* ex) {
cout << ex;
}
}
/**
* listen to client thread funciton
* @param arg
* @return
*/
void* threadFuncClientListen(void* arg) {
auto * params = (CLIENT_LISTEN_PARAMS*)arg;
params->clientHandler->handleClient(params->socketId);
delete params;
}
/**
* open socket on give port
* @param port
* @param clientHandler
*/
void MyParallelServer::open(int port, ClientHandler* clientHandler) {
this->clientHandler = clientHandler;
createSocket(port, DEFAULT_TIME_PER_SEC);
//create thread opening socket
// pthread_create(&threadRunningId, nullptr, threadListen, this);
parallellListen();
//wait for the thread
// pthread_join(threadRunningId, nullptr);
}
/**
* listen to client on given socket
* @param socketId
*/
void MyParallelServer::listenToClient(int socketId) {
CLIENT_LISTEN_PARAMS * params =
new CLIENT_LISTEN_PARAMS{this->clientHandler, socketId, this};
pthread_t threadId;
pthread_create(&threadId, nullptr, threadFuncClientListen, params);
this->threadIdVector.push_back(threadId);
}
/**
* listen parallel to clients
*/
void MyParallelServer::parallellListen() {
int clientSocket;
bool flag = true;
timeval timeout;
//time out only for clients after the first
timeout.tv_sec = TIMEOUT;
timeout.tv_usec = 0;
timeval timeOutMessage;
timeOutMessage.tv_sec = MESSAGE_TIMEOUT;
timeOutMessage.tv_usec = 0;
//while to closed
while (flag) {
//wait for client
clientSocket = waitForConnection();
//if time out or wrong input
if (clientSocket == -1) {
flag = false;
stop();
continue;
}
//setting timeout
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout)) == -1) {
perror("ERROR on setting timeout");
}
listenToClient(clientSocket);
}
cout << "time out caused server stop listening" << endl;
}
/**
* function thread to stop server
* @param arg
* @return
*/
void* threadFuncStop(void* arg) {
AServer* aServer = (AServer*)arg;
aServer->closeServer();
}
/**
* stop server by request
*/
void MyParallelServer::stop() {
pthread_t pthreadIdClose;
// pthread_create(&pthreadIdClose, nullptr, threadFuncStop, this);
// pthread_join(pthreadIdClose, nullptr);
for(auto thread :this->threadIdVector) {
pthread_join(thread, nullptr);
}
threadIdVector.clear();
//close socket
close(sockfd);
}
/**
* free alocated space
*/
MyParallelServer::MyParallelServer() {
this->clientHandler = nullptr;
this->countClientsRunning = 0;
}
| true |
5b33423391ac50745727c0b5b4f14d7564c17ded | C++ | rslater003/RileySlater-CSCI20-SPR2017 | /lab11/lab11.cpp | UTF-8 | 1,057 | 3.421875 | 3 | [] | no_license | /* 1. Computer picks a random number between 1 and 10. Set an integer to points equal to 10.
2. User makes a random guess and based on that guess the computer either
A. Tells the user the number is higher
B. Tells the user the number is lower
C. Tells the user the number is correct
3. If the computer has chosen option A, then the computer will deduct 1 point from int points and output: "The number picked is higher."
Check if int points has hit 0, if it has, then reset program after showing output: "You lost."
If int points is above 0 then repeat step 2.
If the computer has chosen option B, then the computer will deduct 1 point from int points and output: "The number picked is lower."
Check if int points has hit 0, if it has, then reset program after showing output: "You lost."
If int points is above 0 then repeat step 2.
If the computer has chosen option C, then the computer will output: "You have guessed my number!" Show congratulations pop-up.
*/ | true |
0ad9b2a5430ba63b1c77f6b1322dcced4a1725f2 | C++ | simran1802/Data-Structures-and-Algorithms-using-C- | /insert_doubly_linked_list.cpp | UTF-8 | 1,751 | 3.671875 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Node{
public:
Node *prev;
int data;
Node *next;
}*first=NULL;
void create(int a[],int n){
Node *t,*last;
int i;
first = new Node();
first->data=a[0];
first->prev=first->next=NULL;
last=first;
for(i=1;i<n;i++){
t=new Node();
t->data=a[i];
t->next=NULL;
t->prev=last;
last->next=t;
last=t;
}
}
void display(Node *p){
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<"\n";
}
int Length(Node *p){
int l=0;
while(p){
l++;
p=p->next;
}
return l;
}
void insert(Node *p,int index,int x){
Node *t;
int i;
if(index<0 || index>Length(p))
return;
if(index==0){
t=new Node();
t->data=x;
t->next=first;
t->prev=NULL;
first->prev=t;
first=t;
}
else{
for(i=1;i<index-1;i++)
p=p->next;
t=new Node();
t->data=x;
t->next=p->next;
t->prev=p;
if(p->next)p->next->prev=t;
p->next=t;
}
}
int Delete(Node *p,int index){
Node *q;
int x=-1,i;
if(index<1 || index>Length(p))
return -1;
if(index==1){
first=first->next;
if(first)first->prev=NULL;
x=p->data;
delete p;
}
else{
for(i=0;i<index-1;i++)
p=p->next;
p->prev->next=p->next;
if(p->next)
p->next->prev=p->prev;
x=p->data;
delete p;
}
return x;
}
void reverse(Node *p){
Node *temp;
while(p!=NULL){
temp=p->next;
p->next=p->prev;
p->prev=temp;
p=p->prev;
if(p!=NULL && p->next==NULL)
first=p;
}
}
int main(){
int a[]={2,4,8,18,28};
create(a,5);
insert(first,4,21);
Delete(first,4);
Delete(first,1);
reverse(first);
display(first);
cout<<"Length:"<<Length(first);
return 0;
}
| true |
54899be2fa4424975219497be18d03bbeb04bafe | C++ | jeremybboy/mai18 | /question4.cpp | UTF-8 | 929 | 2.609375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include <fstream>
#include<string>
#include "DenseMatrix.hpp"
#include "SparseMatrix.hpp"
#include "FredholmMatrix.hpp"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
#include <stdio.h>
#include <gsl/gsl_sf_bessel.h>
#include <gsl/gsl_linalg.h>
#include <fstream>
using namespace std;
int main(){
int N=5;
FredholmMatrix A(N);
vector<double> u={1,1,1,1,1};
vector<double> v={1,2,3,4,5};
int sigma=1;
A.Insert(sigma,u,v);
cout<<endl;
A.Insert(sigma,u,v);
A.Insert(sigma,v,v);
A.Insert(3,v,u);
cout<<"Ma matrice A"<<endl;
cout<<A<<endl;
cout<<"Sa norme de Frobenius"<<endl;
cout<<FrobeniusNorm(A)<<endl;
cout<<endl;
cout<<"Ma matrice B"<<endl;
DenseMatrix B(N,N);
B.Load("matrice.txt");
cout<<B<<endl;
cout<<"Sa norme de Frobenius"<<endl;
cout<<FrobeniusNorm(B)<<endl;
}
| true |
1c168cb0806e1dcc99a3ff68ace58b603a52c95a | C++ | Shikhar-S/CodesSublime | /circle.cpp | UTF-8 | 2,028 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <utility>
#include <set>
#define mp make_pair
#define EPSILON 1e-6
#define PI 3.14159265
using namespace std;
#define ff first
#define ss second
int n,m;
double dist[501][501];
pair<double,int> angles[2001];
struct point{
double x,y;
point(double xx=0,double yy=0): x(xx), y(yy)
{
}
}points[501];
bool ok(int i,double radius)
{
int ptr=0;
for(int j=1;j<=n;j++)
{
if(i==j)continue;
double x=points[j].x-points[i].x;
double y=points[j].y-points[i].y;
if(2*radius-dist[i][j]<EPSILON)
continue;
double angle_extent=(180/PI)*acos(dist[i][j]/(2*radius));
double angle=(180/PI)*atan2(y,x);
if(angle<0)
angle+=360;
angles[ptr++]=mp(angle-angle_extent,1);
angles[ptr++]=mp(angle+angle_extent,-1);
}
int ctr=0;
sort(angles,angles+ptr);
for(int j=0;j<ptr;j++)
{
if(ctr>=m)
return true;
ctr+=angles[j].ss;
}
return (ctr>=m);
}
int main()
{
double xmax=1e-9,xmin=1e9;
double ymax=1e-9,ymin=1e9;
double x,y;
scanf("%d %d",&n,&m);m--;
for(int i=1;i<=n;i++)
{
scanf("%lf %lf",&x,&y);
xmax=max(xmax,x);
xmin=min(x,xmin);
ymax=max(ymax,y);
ymin=min(ymin,y);
points[i]=point(x,y);
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
dist[i][j]=sqrt((points[i].x-points[j].x)*(points[i].x-points[j].x)+(points[i].y-points[j].y)*(points[i].y-points[j].y));
double ans=max(abs(xmax-xmin),abs(ymax-ymin));
for(int i=1;i<=n;i++)
{
double low=0,high=ans;
double mid=(low+high)/2;
while(high-low>1e-4)
{
mid=(low+high)/2;
if(!ok(i,mid))
low=mid;
else
high=mid;
}
ans=min(high,ans);
}
printf("%.6lf\n",ans);
return 0;
}
| true |
c2b221a812d1ed90a72b9acbf6685b10eacee655 | C++ | SixSafety/mirametrix-fake-server | /mmServer.cpp | UTF-8 | 1,347 | 2.5625 | 3 | [] | no_license | //
// mmServer.cpp
//
#include <iostream>
#include <string>
#include <sstream>
#include <time.h>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
//Simple faked reading of the no eyes detected condition (with count)
std::string fake_reading()
{
static int count = 0;
std::ostringstream reading;
reading << "<REC CNT=\""
<< ++count
<< "\">\r\n"
<< "<Attachment guid=\"ACBFE1C2-EF41-4B9F-B019-A3E2A16A2CD6\" LEYE_FATIGUE=\"-1.000000\" LEYE_FCONF=\"-2.000000\" REYE_FATIGUE=\"-1.000000\" REYE_FCONF=\"-2.000000\" />\r\n"
<< "</REC>\r\n";
return (reading.str());
}
int main()
{
try
{
boost::asio::io_service io_service;
boost::system::error_code ec;
tcp::iostream stream;
tcp::endpoint endpoint(tcp::v4(), 4242);
tcp::acceptor acceptor(io_service, endpoint);
acceptor.accept(*stream.rdbuf(), ec);
if(ec)
{
std::cerr << ec.message() << std::endl;
}
for (;;)
{
struct timespec foo;
foo.tv_sec = 0;
foo.tv_nsec = 33333333L; //30Hz in nanoseconds
nanosleep(&foo,&foo);
stream << fake_reading();
if(!stream)
{
std::cerr << stream.error().message() << std::endl;
break;
}
}
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
| true |
8e926fd1f4c67526d9a705464b3d2194177c10a7 | C++ | sayemimtiaz/competitive-programming | /UVA/374.cpp | UTF-8 | 349 | 3.09375 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
long square(long s)
{
return s*s;
}
long bigmod(long b,long p,long m)
{
if(p==0)
return 1;
else if(p%2==0)
return square(bigmod(b,p/2,m))%m;
else
return ((b%m)*bigmod(b,p-1,m))%m;
}
int main()
{
long b,p,m;
while(scanf("%ld %ld %ld",&b,&p,&m)==3)
{
printf("%lld\n",bigmod(b,p,m));
}
return 0;
}
| true |
0e70f6ab1f7542e1e142db4d4cb3158c44fc4767 | C++ | Ilwel/ed1_trab | /List.cpp | UTF-8 | 4,132 | 3.609375 | 4 | [] | no_license | // Ilwel Isaac Campos Braga
// Mat 1440459
// ED1
#ifndef LIST
#define LIST
#include <iostream>
#include "Link.cpp"
using namespace std;
//class three -- List --
class List{
private: int _size; // attributes
Link* _first;
Link* _last;
// private method signatures
bool is_Empty ();
bool correct_Pos(int pos, bool insrt = true);
void null_List ();
public:
List(){ // constructor
_first = NULL;
_last = NULL;
_size = 0;
}
~List(){ // destructor
null_List();
}
// public method signatures
void print_Info ();
int insert_In(int elm, bool bgn = true);
int insert_Pos (int pos, int elm);
int remove_Pos (int pos);
bool search_For (int st);
};
// private implementation
bool List :: is_Empty(){
return _first == NULL;
}
bool List :: correct_Pos(int pos, bool insrt){
if(insrt) return pos <= _size + 1 and pos > 0;
else return pos <= _size and pos > 0;
}
void List :: null_List(){
while(!is_Empty()){
remove_Pos(_size);
}
}
// public implementation
void List :: print_Info(){
Link* aux;
// scrolling trough all the links
for(aux = _first; aux != NULL; aux = aux->Get_next()){
// printing info
cout << aux->Get_info() << " ";
}
cout << endl;
}
int List :: insert_In(int elm, bool bgn){
Link* neil = new Link();
neil->Set_info(elm);
if(bgn){
// in begin
if(is_Empty()){
_first = neil;
_last = neil;
}else{
neil->Set_next(_first);
_first = neil;
}
}else{
// in end
if(is_Empty()){
_first = neil;
_last = neil;
}else{
_last->Set_next(neil);
_last = neil;
}
}
_size++;
return elm;
}
int List :: insert_Pos(int pos, int elm){
if(correct_Pos(pos)){
if(pos == 1){
// in first position
insert_In(elm);
return elm;
}else if(pos == _size){
// in last position
insert_In(elm, false);
return elm;
}else{
// other positions
int i = 0;
Link* aux;
Link* neil = new Link();
neil->Set_info(elm);
for(i = 0, aux = _first; i < pos - 2; i++, aux = aux->Get_next());
neil->Set_next(aux->Get_next());
aux->Set_next(neil);
}
_size++;
return elm;
}
}
int List :: remove_Pos(int pos){
if(correct_Pos(pos, false)){
if(pos == 1){
// in first position
int return_of_function = _first->Get_info();
_first = _first->Get_next();
_size--;
return return_of_function;
}else{
// other positions
int i = 0;
Link* aux;
for(i = 0, aux = _first; i < pos - 2; i++, aux = aux->Get_next());
Link* aux_2 = aux->Get_next();
int return_of_function = aux->Get_next()->Get_info();
aux->Set_next(aux_2->Get_next());
aux_2 = NULL;
delete aux_2;
_size--;
return return_of_function;
}
}
}
bool List :: search_For(int st){
Link* aux;
for(aux = _first; aux != NULL; aux = aux->Get_next()){
// searching in list
if(aux->Get_info() == st) return true;
}
return false;
}
#endif // LIST
| true |
1eed47bcd170dc7afa545e69e3d8a1b84882e413 | C++ | JJJohan/DX12Engine | /Engine/Engine/Data/String.h | UTF-8 | 1,580 | 3.125 | 3 | [] | no_license | #pragma once
#ifndef ENGINENET_EXPORTS
#include "../External/src/CPPFormat/format.h"
#endif
namespace Engine
{
class String
{
public:
ENGINE_API String();
ENGINE_API String(std::stringstream stream);
ENGINE_API String(const char* string);
ENGINE_API String(const wchar_t* string);
ENGINE_API String(std::string string);
ENGINE_API String(std::wstring string);
ENGINE_API String(int value);
ENGINE_API String(float value);
ENGINE_API String(double value);
ENGINE_API String operator+(const String& rhs) const;
ENGINE_API bool operator==(const String& rhs) const;
ENGINE_API char operator[](size_t index);
ENGINE_API operator std::string() const;
ENGINE_API operator std::wstring() const;
ENGINE_API operator std::stringstream() const;
ENGINE_API int ToInt() const;
ENGINE_API float ToFloat() const;
ENGINE_API double ToDouble() const;
ENGINE_API String Trim();
ENGINE_API String ToLower() const;
ENGINE_API String ToUpper() const;
ENGINE_API bool Contains(String string) const;
ENGINE_API size_t Length() const;
ENGINE_API std::vector<String> Split(char delim) const;
ENGINE_API const std::string& Str() const;
#ifndef ENGINENET_EXPORTS
template <typename... Args>
static String Format(const String& string, Args ... args)
{
std::string text = fmt::format(string._string, args...);
return String(text);
}
#else
static String Format(const String& string)
{
return string;
}
#endif
private:
std::string _string;
std::vector<String>& Split(char delim, std::vector<String>& elems) const;
};
}
| true |
2705d7a5a3da2888f7f022639d3d0cf1099553ec | C++ | 1160208849wfl/cpp-primer5e | /snippets/c++/object_pool/main.cc | UTF-8 | 1,967 | 3.3125 | 3 | [] | no_license | #include <assert.h>
#include <chrono>
#include <iostream>
#include <memory>
#include <vector>
#include "pool.h"
// think: is this usage pattern good?
int main(int argc, char *argv[])
{
if (argc != 3)
{
std::cout << "usage: pool counter size" << std::endl;
return 1;
}
SmartObjectPool<int> pool;
pool.add(std::unique_ptr<int>(new int(42)));
assert(pool.size() == 1);
{
auto obj = pool.acquire();
assert(pool.size() == 0);
assert(*obj == 42);
*obj = 1337;
}
assert(pool.size() == 1);
auto obj = pool.acquire();
assert(*obj == 1337);
int counter = atoi(argv[1]);
int size = atoi(argv[2]);
{
std::chrono::steady_clock::time_point start =
std::chrono::steady_clock::now();
for (int i = 0; i < counter; ++i)
{
auto ptr = new std::vector<int>;
ptr->reserve(2000000);
for (int i = 0; i < size; ++i)
{
ptr->push_back(i);
}
delete ptr;
}
std::chrono::steady_clock::time_point end =
std::chrono::steady_clock::now();
auto cnt =
std::chrono::duration_cast<std::chrono::microseconds>(end - start)
.count();
std::cout << "newd: " << cnt << " us.\n";
}
{
SmartObjectPool<std::vector<int>> vec_pool;
for (int i = 0; i < 10; ++i)
{
auto ptr = new std::vector<int>();
ptr->reserve(2000000);
vec_pool.add(std::unique_ptr<std::vector<int>>(ptr));
}
std::chrono::steady_clock::time_point start =
std::chrono::steady_clock::now();
for (int i = 0; i < counter; ++i)
{
auto vec = vec_pool.acquire();
for (int i = 0; i < size; ++i)
{
vec->push_back(i);
}
vec->clear();
}
std::chrono::steady_clock::time_point end =
std::chrono::steady_clock::now();
auto cnt =
std::chrono::duration_cast<std::chrono::microseconds>(end - start)
.count();
std::cout << "pool: " << cnt << " us.\n";
}
}
| true |
17359031b58f5a4cb80d074bd4d50c3df2a35102 | C++ | kenschenke/Mak_Writing_Compilers_and_Interpreters | /Mak_Writing_Compiler_2nd_Ed/Chapter05/Ver_2/PARSEXPR.CPP | UTF-8 | 4,825 | 2.703125 | 3 | [] | no_license | //fig 5-23
// *************************************************************
// * *
// * P A R S E R (Expressions) *
// * *
// * Parse expressions. *
// * *
// * CLASSES: TParser *
// * *
// * FILE: prog5-2/parsexpr.cpp *
// * *
// * MODULE: Parser *
// * *
// * Copyright (c) 1996 by Ronald Mak *
// * For instructional purposes only. No warranties. *
// * *
// *************************************************************
#include "parser.h"
//--------------------------------------------------------------
// ParseExpression Parse an expression (binary relational
// operators = < > <> <= and >= ).
//--------------------------------------------------------------
void TParser::ParseExpression(void)
{
ParseSimpleExpression();
//--If there we now see a relational operator,
//--parse a second simple expression.
if ((token == tcEqual) || (token == tcNe) ||
(token == tcLt) || (token == tcGt) ||
(token == tcLe) || (token == tcGe)) {
GetTokenAppend();
ParseSimpleExpression();
}
}
//--------------------------------------------------------------
// ParseSimpleExpression Parse a simple expression
// (unary operators + or - , and
// binary operators + - and OR).
//--------------------------------------------------------------
void TParser::ParseSimpleExpression(void)
{
//--Unary + or -
if ((token == tcPlus) || (token == tcMinus)) {
GetTokenAppend();
}
//--Parse the first term.
ParseTerm();
//--Loop to parse subsequent additive operators and terms.
while ((token == tcPlus) || (token == tcMinus) ||
(token == tcOR)) {
GetTokenAppend();
ParseTerm();
}
}
//--------------------------------------------------------------
// ParseTerm Parse a term (binary operators * / DIV
// MOD and AND).
//--------------------------------------------------------------
void TParser::ParseTerm(void)
{
//--Parse the first factor.
ParseFactor();
//--Loop to parse subsequent multiplicative operators and factors.
while ((token == tcStar) || (token == tcSlash) ||
(token == tcDIV) || (token == tcMOD) ||
(token == tcAND)) {
GetTokenAppend();
ParseFactor();
}
}
//--------------------------------------------------------------
// ParseFactor Parse a factor (identifier, number,
// string, NOT <factor>, or parenthesized
// subexpression).
//--------------------------------------------------------------
void TParser::ParseFactor(void)
{
switch (token) {
case tcIdentifier: {
//--Search for the identifier. If found, append the
//--symbol table node handle to the icode. If not
//--found, enter it and flag an undefined identifier error.
TSymtabNode *pNode = SearchAll(pToken->String());
if (pNode) icode.Put(pNode);
else {
Error(errUndefinedIdentifier);
EnterLocal(pToken->String());
}
GetTokenAppend();
break;
}
case tcNumber: {
//--Search for the number and enter it if necessary.
//--Set the number's value in the symbol table node.
//--Append the symbol table node handle to the icode.
TSymtabNode *pNode = SearchAll(pToken->String());
if (!pNode) {
pNode = EnterLocal(pToken->String());
pNode->value = pToken->Type() == tyInteger
? (float) pToken->Value().integer
: pToken->Value().real;
}
icode.Put(pNode);
GetTokenAppend();
break;
}
case tcString:
GetTokenAppend();
break;
case tcNOT:
GetTokenAppend();
ParseFactor();
break;
case tcLParen:
//--Parenthesized subexpression: Call ParseExpression
//-- recursively ...
GetTokenAppend();
ParseExpression();
//-- ... and check for the closing right parenthesis.
if (token == tcRParen) GetTokenAppend();
else Error(errMissingRightParen);
break;
default:
Error(errInvalidExpression);
break;
}
}
//endfig
| true |
23748e23bed486b70c15ee44575d101afb93dbe6 | C++ | acnokego/LeetCode | /209_Minimum_Size_Subarray_Sum/two_ptr.cpp | UTF-8 | 931 | 3.1875 | 3 | [] | no_license | class Solution {
/*
* Complexity: O(n)
* Space: O(1)
*/
public:
int minSubArrayLen(int s, vector<int>& nums) {
int n = nums.size();
int start = 0, end = 0;
int arraySum = 0;
int minLength = n + 1;
while(end < n){
arraySum += nums[end];
// increasing end until the sum is bigger than s
if(arraySum >= s){
minLength = min(end - start + 1, minLength);
// increasing start to update the minLength until the sum is
// smaller than s;
while((arraySum - nums[start]) >= s && start <= end){
arraySum -= nums[start];
start += 1;
minLength = min(end - start + 1, minLength);
}
}
++end;
}
return (minLength == n+1) ? 0 : minLength;
}
};
| true |
4e37f5af996dc66c9b7051893029655b5659da5e | C++ | protohaus/handheld-ph-meter | /src/ph_io.cpp | UTF-8 | 8,142 | 2.5625 | 3 | [
"MIT"
] | permissive | #include "ph_io.h"
PhIo::PhIo(OneWire &one_wire) : dallas_sensor_(&one_wire) {}
void PhIo::init() {
dallas_sensor_.begin();
dallas_sensor_.setWaitForConversion(false);
dallas_sensor_.setResolution(12);
bool found_dallas_sensor = dallas_sensor_.getAddress(dallas_address_, 0);
if (!found_dallas_sensor) {
dallas_status_ = DallasError::DISCONNETED;
Serial.println("Nicht temperature kompensiert");
} else {
dallas_status_ = DallasError::NO_DATA;
Serial.println("Dallas sensor gefunden");
}
}
void PhIo::enable() { enabled_ = true; }
bool PhIo::isEnabled() { return enabled_; }
void PhIo::disable() {
// Mark the Dallas sensor as invalid
dallas_status_ = DallasError::DISCONNETED;
dallas_temperature_c_ = NAN;
dallas_request_phase_ = true;
// Mark the pH sensor as invalid
ph_error_ = Ezo_board::errors::FAIL;
ph_value_ = NAN;
reading_request_phase_ = true;
// Mark the calibration buffer as invalid
clearCalibration();
enabled_ = false;
}
std::tuple<Ezo_board::errors, PhIo::DallasError, PhIo::CalibrationState>
PhIo::getStatus() {
return std::make_tuple(ph_error_, dallas_status_, calibration_state_);
}
float PhIo::getPh() {
if (ph_error_ == Ezo_board::SUCCESS || ph_error_ == Ezo_board::NO_DATA) {
return ph_value_;
} else {
return NAN;
}
}
float PhIo::getTemperatureC() {
if (dallas_status_ == DallasError::SUCCESS ||
dallas_status_ == DallasError::NO_DATA) {
return dallas_temperature_c_;
} else {
return NAN;
}
}
void PhIo::exec() {
if (enabled_) {
performTemperatureReading();
performPhReading();
}
}
void PhIo::calibrate(CalibrationState calibration_state) {
enable();
calibration_state_ = calibration_state;
}
void PhIo::performPhReading() {
if (reading_request_phase_) {
// Request a new pH reading. Use temperature compensation if available
if (dallas_status_ == DallasError::SUCCESS) {
PH.send_read_with_temp_comp(dallas_temperature_c_);
} else {
PH.send_read_cmd();
}
// set when the reading will be ready and switch to the receiving phase
next_poll_time_ms_ = millis() + response_delay_ms_;
reading_request_phase_ = false;
} else {
// Retrieve the pH measurement if the timeout has elapsed
if (millis() >= next_poll_time_ms_) {
ph_error_ = PH.receive_read_cmd();
if (ph_error_ == Ezo_board::errors::SUCCESS) {
ph_value_ = PH.get_last_received_reading();
if (calibration_state_ != CalibrationState::NOT_CALIBRATING) {
addCalibrationPoint(ph_value_);
performCalibration();
updateStableReadingCount();
}
}
// switch back to ask for a new reading
reading_request_phase_ = true;
}
}
}
void PhIo::performTemperatureReading() {
if (dallas_request_phase_) {
// Request a new temperature reading
dallas_sensor_.requestTemperaturesByAddress(dallas_address_);
// set when the reading will be ready and switch to the receiving phase
dallas_request_ready_time_ms_ =
millis() + dallas_sensor_.millisToWaitForConversion(dallas_resolution_);
dallas_request_phase_ = false;
} else {
// Retrieve the temperature measurement if the timeout has elapsed
if (dallas_request_ready_time_ms_ < millis()) {
float temp_c = dallas_sensor_.getTempC(dallas_address_);
if (temp_c == DEVICE_DISCONNECTED_C) {
temp_c = NAN;
dallas_status_ = DallasError::DISCONNETED;
} else {
dallas_temperature_c_ = temp_c;
dallas_status_ = DallasError::SUCCESS;
}
dallas_request_phase_ = true;
}
}
}
void PhIo::performCalibration() {
// If calibration is active, only perform calculation once 2 or more values
// have been collected
if (calibration_state_ != CalibrationState::NOT_CALIBRATING &&
(calibration_position_ > 1 || calibration_is_full_)) {
// Calculate the range of measurements. If the calibration is full, the
// oldest values will be overwritten
CalibrationBuffer::iterator start = std::begin(calibration_measurements_);
CalibrationBuffer::iterator end;
uint8_t calibration_size;
if (calibration_is_full_) {
end = std::end(calibration_measurements_);
calibration_size = calibration_measurements_.size();
} else {
end = std::begin(calibration_measurements_) + calibration_position_;
calibration_size = calibration_position_;
}
double sum = std::accumulate(start, end, 0.0);
double m = sum / calibration_size;
double accum = 0.0;
std::for_each(start, end,
[&](const double d) { accum += (d - m) * (d - m); });
calibration_average_ = m;
calibration_std_dev_ = sqrt(accum / (calibration_size - 1));
}
}
float PhIo::getCalibrationStdDev() { return calibration_std_dev_; }
uint8_t PhIo::getCalibrationCount() {
if (!calibration_is_full_) {
return calibration_position_;
} else {
return calibration_measurements_.size();
}
}
uint8_t PhIo::getCalibrationTotal() { return calibration_measurements_.size(); }
float PhIo::getCalibrationTarget() {
switch (calibration_state_) {
case CalibrationState::HIGH_POINT:
return 10;
case CalibrationState::MID_POINT:
return 7;
case CalibrationState::LOW_POINT:
return 4;
case CalibrationState::NOT_CALIBRATING:
return NAN;
break;
default:
return NAN;
break;
}
}
uint8_t PhIo::getStableReadingCount() { return stable_reading_count_; }
uint8_t PhIo::getStableReadingTotal() { return stable_reading_total_; }
bool PhIo::isCalibrationPointDone() {
// Returns true if the buffer is more than half full
// and the standard deviation is within the calibration tolerance
// and within a plausible range for the offset
if (stable_reading_count_ >= stable_reading_total_) {
return true;
} else {
return false;
}
}
void PhIo::addCalibrationPoint(float ph_value) {
calibration_measurements_[calibration_position_] = ph_value;
calibration_position_++;
if (calibration_position_ >= calibration_measurements_.size()) {
calibration_position_ = 0;
calibration_is_full_ = true;
}
}
void PhIo::updateStableReadingCount() {
if (calibration_std_dev_ <= calibration_tolerance_ &&
abs(getCalibrationTarget() - calibration_average_) <
calibration_max_offset_) {
if (stable_reading_count_ < stable_reading_total_) {
stable_reading_count_++;
}
} else {
stable_reading_count_ = 0;
}
}
bool PhIo::completeCalibration(bool override) {
if (isCalibrationPointDone() || override) {
std::array<char, 5> point_name;
switch (calibration_state_) {
case CalibrationState::LOW_POINT:
strcpy(point_name.data(), "low");
break;
case CalibrationState::MID_POINT:
strcpy(point_name.data(), "mid");
break;
case CalibrationState::HIGH_POINT:
strcpy(point_name.data(), "high");
break;
default:
return false;
break;
}
std::array<char, 16> calibration_command;
sprintf(calibration_command.data(), "cal,%s,%.0f", point_name.data(),
getCalibrationTarget());
Serial.print(calibration_command.data());
PH.send_cmd(calibration_command.data());
disable();
return true;
} else {
return false;
}
}
void PhIo::clearCalibration() {
calibration_state_ = CalibrationState::NOT_CALIBRATING;
calibration_position_ = 0;
calibration_is_full_ = false;
calibration_std_dev_ = NAN;
calibration_average_ = NAN;
stable_reading_count_ = 0;
}
float PhIo::getCalibrationTolerance() { return calibration_tolerance_; }
float PhIo::setCalibrationTolerance(float tolerance_std_dev) {
if (tolerance_std_dev > 0) {
calibration_tolerance_ = tolerance_std_dev;
}
return calibration_tolerance_;
}
uint8_t PhIo::setStableReadingTotal(uint8_t stable_reading_total) {
if (stable_reading_total > calibration_measurements_.size()) {
stable_reading_total_ = calibration_measurements_.size();
} else {
stable_reading_total_ = stable_reading_total;
}
return stable_reading_total_;
} | true |
2ee20ca924a4246ca8cba522b8b9739e8d405365 | C++ | Tokiya-wang/CodeInLinux | /C++/cpp82184.cpp | UTF-8 | 356 | 2.890625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
using std::string;
using std::ifstream;
using std::vector;
using std::cout;
using std::endl;
int main()
{
ifstream is("test.txt");
vector<string> vec;
string temp;
while (is >> temp)
vec.push_back(temp);
for (const auto & it : vec)
cout << it << endl;
return 0;
}
| true |
f9d029c7f760f2d18b636c3e33f543f0bf93be7d | C++ | mnewhouse/tselements | /src/graphics/render_window.cpp | UTF-8 | 2,641 | 2.5625 | 3 | [
"MIT"
] | permissive | /*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/
#include "render_window.hpp"
#include "gl_context.hpp"
#include <string>
#include <stdexcept>
#include <SFML/Window.hpp>
#include <SFML/Window/ContextSettings.hpp>
#include <GL/glew.h>
namespace ts
{
namespace graphics
{
struct RenderWindow::Impl
: public sf::Window
{
Impl(const char* title, std::int32_t width, std::int32_t height, WindowMode window_mode)
{
sf::ContextSettings context_settings;
context_settings.majorVersion = gl_version::major;
context_settings.minorVersion = gl_version::minor;
context_settings.antialiasingLevel = 4;
context_settings.depthBits = 24;
context_settings.stencilBits = 8;
std::uint32_t style = sf::Style::Titlebar;
if (window_mode == WindowMode::FullScreen)
{
style = sf::Style::Fullscreen;
}
else if (window_mode == WindowMode::Borderless)
{
const auto& modes = sf::VideoMode::getFullscreenModes();
style = sf::Style::None;
width = modes.front().width;
height = modes.front().height;
}
sf::Window::create(sf::VideoMode(width, height, 32U), title, style, context_settings);
}
};
RenderWindow::RenderWindow(const char* title, std::int32_t width, std::int32_t height, WindowMode window_mode)
: impl_(std::make_unique<Impl>(title, width, height, window_mode))
{
}
RenderWindow::~RenderWindow()
{
}
Vector2i RenderWindow::size() const
{
auto result = impl_->getSize();
return Vector2i(result.x, result.y);
}
void RenderWindow::clear(Colorf color)
{
glStencilMask(0xFF);
glClearColor(color.r, color.g, color.b, color.a);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void RenderWindow::display()
{
impl_->display();
}
void RenderWindow::activate()
{
impl_->setActive(true);
}
bool RenderWindow::has_focus() const
{
return impl_->hasFocus();
}
bool RenderWindow::poll_event(sf::Event& event)
{
return impl_->pollEvent(event);
}
Vector2i RenderWindow::mouse_position() const
{
auto pos = sf::Mouse::getPosition(*impl_);
return{ pos.x, pos.y };
}
void RenderWindow::set_framerate_limit(std::uint32_t limit)
{
impl_->setFramerateLimit(limit);
}
void RenderWindow::set_vsync_enabled(bool enable)
{
impl_->setVerticalSyncEnabled(enable);
}
}
}
| true |
055b60ad2c3f7220206f173e5e318a07d735fa2f | C++ | divyanshu-avi/LeetCode-Solutions | /Top-Interview-Questions/054/54_d.cpp | UTF-8 | 1,252 | 3.0625 | 3 | [] | no_license | class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int l, r, u, d, i, j, m = matrix.size(), n;
vector<int> ans;
if(!m) return ans;
n = matrix[0].size();
if(!n) return ans;
l = u = 0;
r = n-1;
d = m-1;
while(l<r && u<d)
{
i = u; j = l-1;
while(++j <= r)
ans.push_back(matrix[i][j]);//Left to Right
j--;
while(++i <= d)
ans.push_back(matrix[i][j]);//Up to Down
i--;
while(--j >= l)
ans.push_back(matrix[i][j]);//Right to left
j++;
while(--i > u)//Not using >= because matrix[u][l] was already pushed in the beginning.
ans.push_back(matrix[i][j]);//Down to Up
cout<<l<<r<<u<<d<<' ';
u++; d--; l++; r--;//Updating boundaries
}
//If l==r or u==d then all four motions are not defined so handle that seperately.
if(u==d)
while(l <= r)
ans.push_back(matrix[u][l++]);//Extra style points 🤩
if(l==r)
while(u <= d)
ans.push_back(matrix[u++][l]);
return ans;
}
}; | true |
d95ec9845473e237482c1af4d1b5a1415b96426a | C++ | magicroyee/cppsource | /05.2.wripen.cpp | UTF-8 | 624 | 3.390625 | 3 | [] | no_license | #include <iostream>
using namespace std;
class wripen
{
public:
wripen() {};
virtual ~wripen() {};
virtual void writing() {};
};
class pencil : public wripen
{
public:
pencil() {};
~pencil() {};
void writing() {cout << "I'm a pencil.\n";};
};
class pen : public wripen
{
public:
pen() {};
~pen() {};
void writing() {cout << "I'm a pen.\n";};
};
int main(void)
{
char temp;
wripen * wp;
pencil c;
pen p;
cin >> temp;
if (temp == 'c')
wp = &c;
else
wp = &p;
wp->writing();
return 0;
} | true |
e2349e18e8befdf601955792c72a474d6d6cbb7c | C++ | bsella/fractal3001 | /shader.cpp | UTF-8 | 510 | 2.734375 | 3 | [] | no_license | #include "shader.h"
#include <iostream>
Shader::Shader(GLenum type){
m_id= glCreateShader(type);
}
Shader::~Shader(){
glDeleteShader(m_id);
}
bool Shader::compile(const char* code, std::ostream& ost)const{
glShaderSource(m_id, 1, &code, nullptr);
glCompileShader(m_id);
GLint success;
glGetShaderiv(m_id, GL_COMPILE_STATUS, &success);
if(!success){
char infoLog[1024];
glGetShaderInfoLog(m_id, 1024, nullptr, infoLog);
ost << infoLog << std::endl;
}
return static_cast<bool>(success);
}
| true |
d41ac366181f002d3be4d195b1b32124d554c38e | C++ | rookiezmh/my_cpp_code | /base/rc_string/detail.cc | UTF-8 | 836 | 3 | 3 | [] | no_license | #include "detail.h"
namespace detail {
ReferenceCountBase::ReferenceCountBase()
: reference_count_(0), shareable_(false) { }
ReferenceCountBase::ReferenceCountBase(const ReferenceCountBase &)
: reference_count_(0), shareable_(false) { }
ReferenceCountBase &ReferenceCountBase::operator =(const ReferenceCountBase &) {
return *this;
}
ReferenceCountBase::~ReferenceCountBase() { }
void ReferenceCountBase::AddReference() {
++reference_count_;
}
void ReferenceCountBase::RemoveReference() {
if (--reference_count_ == 0) {
delete this;
}
}
void ReferenceCountBase::MarkUnshareable() {
shareable_ = false;
}
bool ReferenceCountBase::IsShareable() const {
return shareable_;
}
bool ReferenceCountBase::IsShared() const {
return reference_count_ > 1;
}
}
| true |
0bd51e0afed55eb9c77908f5366d1272c7efc9df | C++ | iShubhamRana/DSA-Prep | /Leetcode-Contests/biweekly-47/1780.cpp | UTF-8 | 465 | 3.53125 | 4 | [] | no_license | // 3^x(1 + 3^y + 3^z ...)
// divide by 3^x
// 1 + 3^y + 3^z ...
// if num % 3 == 1, simply subtract 1
// and repeat ----> recursive solution!
// remainder can never be 2
// WHOLE IDEA -> Keep on substracting powers of 3 from number till number == 0
class Solution
{
public:
bool checkPowersOfThree(int n)
{
if (n == 0)
return true;
if (n % 3 == 2)
return false;
return checkPowersOfThree(n / 3);
}
}; | true |
d2b93b64aa42164e0104513d99c7518325e07469 | C++ | sedrik/GobblashX | /include/aitools.h | UTF-8 | 1,178 | 2.78125 | 3 | [
"MIT"
] | permissive | #ifndef __AITOOLS_H__
#define __AITOOLS_H__
#include "map.h"
#include "platform.h"
#include "creature.h"
#include "scanresult.h"
enum Scanfor { CREATURES = 0x1, PLATFORMS = 0x2 };
class Map;
class Aitools{
private:
Map *world;
public:
Aitools(Map *iworld);
Creature *identify_creature(int id); /* returns a pointer to the creature
with the given id */
Platform *identify_platform(int id); /* returns a pointer to the platform
with the given id */
int random(int min, int max); /* returns a random number x, where
min <= x <= max */
int box_scan( Scanfor scan_for, Scanresult &res, const SDL_Rect &box );
/* Scans for scan_for in box and putting the result in res
returns 0 if everything was ok, otherwise returns something nonzero */
bool px_pf_scan( int x, int y); /* is there a platform on the given coords?*/
/* scan for creatures and places then in the &res variable*/
void scan_down(int xstart, int ystart, Scanresult &res);
void scan_up(int xstart, int ystart, Scanresult &res);
};
#endif // __AITOOLS_H__
| true |
c7f33e3d1768baee3713a670fb679a7338be0bda | C++ | Shubhrajyoti-Dey-FrosTiK/My-Codes | /CodeForces/Contest/Div2_704/CardDeck/CardDeck.cpp | UTF-8 | 819 | 2.515625 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<unordered_map>
using namespace std;
typedef long long int ll;
int main()
{
ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL);
ll TestCases;
cin>>TestCases;
while(TestCases--)
{
ll NoOfTerms;
cin>>NoOfTerms;
vector <ll> Store;
unordered_map <ll,ll> IndexStore;
for(ll i=0;i<NoOfTerms;i++)
{ll n; cin>>n; Store.push_back(n); IndexStore[n]=i;}
ll max=Store.size();
while(Store.size()>0)-
{
if(IndexStore[max]>Store.size()-1){max--; continue;}
for(ll i=IndexStore[max];i<Store.size();i++)
{cout<<Store[i]<<" ";}
Store.erase(Store.begin()+IndexStore[max],Store.end());
max--;
}
cout<<endl;
}
return 0;
} | true |
5f434e2bb8460c29c7a004538008be2d1d17bece | C++ | CJHMPower/Fetch_Leetcode | /data/Submission/172 Factorial Trailing Zeroes/Factorial Trailing Zeroes_1.cpp | UTF-8 | 508 | 2.890625 | 3 | [] | no_license | //-*- coding:utf-8 -*-
// Generated by the Fetch-Leetcode project on the Github
// https://github.com/CJHMPower/Fetch-Leetcode/
// 172 Factorial Trailing Zeroes
// https://leetcode.com//problems/factorial-trailing-zeroes/description/
// Fetched at 2018-07-24
// Submitted 2 years ago
// Runtime: 4 ms
// This solution defeats 100.0% cpp solutions
class Solution {
public:
int trailingZeroes(int n) {
int count = 0;
while (n) {
count += (n / 5);
n /= 5;
}
return count;
}
}; | true |
0ee9ba2fcc84a199a25021cdbf85b187262fc651 | C++ | njsoly/Mixolotron | /Point.h | UTF-8 | 287 | 2.9375 | 3 | [
"MIT"
] | permissive | #ifndef POINT_H_
#define POINT_H_
/** Point.h
*
* by Nate Solyntjes
*/
class Point {
public:
uint16_t x,y;
Point(uint16_t x0=0, uint16_t y0=0){
x = x0;
y = y0;
}
/** copy constructor? */
Point(Point& p){
Point(p.x, p.y);
}
virtual ~Point(){
}
};
#endif /* POINT_H_ */ | true |
36adaa53753ccf45e3edc7414b362069659faf9c | C++ | vlad24/FIRST-SEMESTER | /HW_8/cockoo hash/cockoo hash/coo main.cpp | UTF-8 | 830 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include"hashTablesCoo.h"
int main()
{
int answer = 3;
char name[24] = {};
char phone[20] = {};
HashTable* hTab = createHashTable();
printf("0-end,1-add,2-search\n");
while(answer != 0)
{
printf("?_");
scanf("%d",&answer);
switch (answer)
{
case 1 :
{
printf("Enter the name : ");
scanf("%s",&name);
printf("Enter the phone : ");
scanf("%s",&phone);
addToHashTable(hTab,name,phone);
break;
}
case 2 :
{
printf("Enter the name : ");
scanf("%s",&name);
InfoBlock* block = searchTelephone(hTab,name);
if (block != NULL)
printf("%s\n",block->telephone);
else
printf("no such a phone\n");
break;
}
case 0 :
{
destroyHashTable(hTab);
printf("Buy");
}
default:
{
answer = 0;
}
}
}
getc(stdin);
} | true |
7c29f785aa9816017abae8aec82547c2297d543d | C++ | apdiazv/SantanderXVA | /source/interpola.cpp | UTF-8 | 1,691 | 2.765625 | 3 | [] | no_license | #include "headerFiles.h"
#include "interpola.h"
Interpola::Interpola(const Interpola& copyInterpola)
{
_coef = copyInterpola._coef;
x = copyInterpola.x;
N = copyInterpola.N;
r0 = copyInterpola.r0;
//cout <<" Constructing Interpola Copy "<< "\n";
}
Interpola::Interpola(Curva* curva)
{
_coef = clampedSpline(curva->tenors, curva->rates);
x = curva->tenors;
N = curva->tenors.size();
r0 = curva->rates[0];
//cout <<" Constructing Interpola "<< "\n";
}
void Interpola::getIndice(double t)
{
_t = t;
if ( _t < x[0])
{
val = true;
}
else
{
val = false;
k = index(x, _t);
if (k < (N-1))
k = k;
else
k = k-1;
}
}
double Interpola::getRate()
{
double result;
if ( val == true )
{
result = r0;
}
else
{
result = _coef[k + N] + (_t - x[k]) * (_coef[k + 2 * N] + _coef[k + 3 * N] * (_t - x[k]) + _coef[k + 4 * N] * (_t - x[k]) * (_t - x[k]));
}
return result;
}
double Interpola::getDerivativeRate()
{
double result;
if ( val == true )
{
result = 0.0;
}
else
{
result = _coef[k + 2 * N] + 2 * _coef[k + 3 * N] * (_t - x[k]) + 3 * _coef[k + 4 * N] * (_t - x[k])*(_t - x[k]);
}
return result;
}
double Interpola::getSecondDerivativeRate()
{
double result;
if ( val == true)
{
result = 0.0;
}
else
{
result = 2 * _coef[k + 3 * N] + 6 * _coef[k + 4 * N] * (_t - x[k]);
}
return result;
}
Interpola::Interpola()
{
//cout <<" Constructing Interpola Void"<< "\n";
}
Interpola::~Interpola()
{
_coef.clear();
_coef.swap(vector<double> (_coef));
x.clear();
x.swap(vector<double> (x));
//cout <<" Destructing Interpola "<< "\n";
} | true |
9d2182fb18dd3577b34d9236945dd2b43f7a4092 | C++ | Liccol/drm | /src/code_test/modern cpp json/json_test.cpp | GB18030 | 1,296 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include "assert.h"
#include "nlohmann/json.hpp"
using namespace std;
using nlohmann::json;
namespace ns {
struct person {
std::string name;
std::string address;
int age;
};
void to_json(json& j, const person& p) {
j = json{ {"name", p.name}, {"address", p.address}, {"age", p.age} };
}
void from_json(const json& j, person& p) {
p.name = j.at("name").get<std::string>();
p.address = j.at("address").get<std::string>();
p.age = j.at("age").get<int>();
}
}
int main(int arg, char args[]) {
string str = "{\"name\":\"test\",\"address\":\"1\",\"age\":12}";
try {
auto js = json::parse(str);
cout << js["name"] << endl;
//tt = js;
ns::person p2 = js;
cout << "test address: " << p2.address << endl;
}
catch(exception e){
cout << e.what() << endl;
}
// TODO: POSTݵstringparse, Ȼjsonнṹ帳ֵ structA = j;Ӷ浽ṹȥ.
// create a person
ns::person p{ "Ned Flanders", "744 Evergreen Terrace", 60 };
// conversion: person -> json
json j = p;
std::cout << j << std::endl;
// {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"}
// conversion: json -> person
ns::person p2 = j;
// that's it
std::cout << p2.address << std::endl;
cin.get();
return 0;
} | true |
f73186df450b45a5a7f011de142014932b043887 | C++ | jsh33hy/oldCpp | /318/map/elevationMap.cpp | UTF-8 | 18,146 | 2.84375 | 3 | [] | no_license | /************************************
Jeremiah Sheehy C09229858
EEN 318 - Dr. Murrell
United States Directions
December, 9, 2012
************************************/
#include "library.h"
#include "hashTable.h"
#include "vHeap.h"
#define PI 3.14159265
struct CoverageInfo{
int latTop;
int latBot;
int longLeft;
int longRight;
char fileName[18];
};
struct FileData{
string fileName;
int rows;
int cols;
int bpp; //bytesperpixel
int spp; //secondsperpixel
int lls; //leftlongseconds
int tls; //toplatseconds
int min;
int max;
int sv; //special value marine code=-500
short *d;//data
};
struct RoadSection{
char name[32];
char type[4]; //"T--" highway, "L--" Limited access highway, "F-T" Toll-Ferry Crossing
int locIndexA;
int locIndexB;
float length; //.100=6.9miles
char c;
};
void init_hashTable(HashTable*);//Create HashTable
void read_alphaplace_data(string, HashTable*);//read data from alphaplaces file and store in hashtable
void extractData(entry*, string);//extract data from 1 line of alphaplaces file and store it into an entry strucute
void lookUp(HashTable*,entry**);//look up 2 places form the hashtable and store them into a new entry structure
string getHashable(string);//takes a string and returns the hash value
string readLine(void);//reads a line from the stdin
char *get_coverage_file(float*, float*);//finds the minimum file that covers both places
void read_file(FileData *); //read binary data from elevation file
void load_locations_and_roads(FileData *,Vertex *,RoadSection *);//load locations and roads, update Current location and desitnation indices
int* get_color_map();//creates a color pallet
void draw_map(FileData*, int*);//draws the map
void find_shortest_path(Vertex*, RoadSection*, int*, bool);//find shortest path between two places (Using indexes from locations.txt file)
void draw_shortest_path(Vertex*, RoadSection*, int*);//draws the shortest path
void print_directions(Vertex*, vector<RoadSection*>);//prints directions of shortest calculated path
string get_compas_direction(float); //converets degree direction to compas direction
void main(){
int tableSize=25375;//number of lines in alphaplaces.txt file
HashTable hTable(tableSize);//create hashtable
init_hashTable(&hTable);
entry *places[2]; //structure for start and end location entries, defined in hashTable.h
lookUp(&hTable,places);
vector<CoverageInfo>dFileList;
float x[2]={places[0]->longitude, places[1]->longitude};//put longitude data into x cordinate structure
float y[2]={places[0]->latitude, places[1]->latitude};//put latitude data into y coordinate structure
int locIndices[2]={places[0]->closestLocI,places[1]->closestLocI};//closest location indices from closests.txt file
char coverageFile[18];//Name of file that minimally covers both locations
strcpy(coverageFile,get_coverage_file(x,y));//find the file that covers both and return the name as a char *
//string s="geo/";
//s+=coverageFile;
string s = coverageFile;
FileData *fd = new FileData;
fd->fileName=s;
read_file(fd);
//Location locations[29147]; //number of lines in locations.txt file
RoadSection sections[47015]; //number of lines in majorroads.txt file
Vertex v[29147];//array of vertices with pointers to locations (defined in vHeap.h)
load_locations_and_roads(fd,v,sections); //extract location and road section info
char yesOrNo;
bool drawPaths=false;
cout << "Do you want to watch the sortest path search? (y/n): ";
cin >> yesOrNo;
if(toupper(yesOrNo)=='Y')
drawPaths=true;
hide_console();
system("cls");
cout << "Location: \t" << places[0]->name << ", " << places[0]->state << endl;
cout << "Destination: \t" << places[1]->name << ", " << places[1]->state << endl;
cout << "-----------------------------------------------------------------\n";
int * colormap=get_color_map();
make_window(fd->cols,fd->rows);
set_caption("United States Directions -- Jeremiah Sheehy");
draw_map(fd,colormap);
set_pen_width_color(5,color::black);
draw_point(v[locIndices[0]].l->x,v[locIndices[0]].l->y);
draw_point(v[locIndices[1]].l->x,v[locIndices[1]].l->y);
find_shortest_path(v,sections,locIndices,drawPaths);
system("PAUSE");
exit(1);
}//end main
void init_hashTable(HashTable *hashT){
string fileName;
ifstream file;
file.open("alphaplaces.txt",ios::in);
if(file.fail())
fileName="/home/www/geographical/alphaplaces.txt"; //use absoulte path on rabbit
else
fileName="alphaplaces.txt"; //file is in working directory, use relative path
file.close();
read_alphaplace_data(fileName,hashT);
}//end init_hashTable
void read_alphaplace_data(string fileName, HashTable *hashT){
cout << "Loading alphaplaces data..." << endl;
ifstream inputFile;
inputFile.open(fileName.c_str(),ios::in);
if(inputFile.fail()){
cerr << "Failed to open alphaplaces file.\n";
exit(1);
}
FILE *fclosest = fopen("closests.txt", "r+");
if (fclosest == NULL){
cerr << "Closest file error.\n";
exit(1);
}
string line;
while(!inputFile.eof()){
getline(inputFile,line);
if(!line.empty()){
entry *e = new entry;
extractData(e,line);//extract data from alphaplaces.txt file
int n = fscanf(fclosest, "%d %f",&e->closestLocI,&e->distanceToLocI);//extract data from closests.txt ifle
if(n==EOF){
fclose(fclosest);
}
hashT->insert(e);
}
}
inputFile.close();
}//end read_alphaplace_data
void extractData(entry *e, string line){
e->state=line.substr(0,2);
e->stateFIP=line.substr(2,2);
e->placeFIP=line.substr(4,5);
int pos=9; //pos = line position
e->name="";
while(line[pos]<=47 || line[pos]>57){//char is not a digit (0-9)
if(line[pos]>0){
if(!(isspace(line[pos]) && isspace(line[pos+1])))
e->name+=line[pos];
}
else
e->name+=line.substr(pos,1); //for special characters, cctpye functions dont work for negative char values
pos++;
}
//pos = start of first digit of population
e->population=atoi(line.substr(pos,9).c_str());
pos+=9;
e->housingUnits=atoi(line.substr(pos,9).c_str());
pos+=9;
e->landAreaMeters=atoi(line.substr(pos,14).c_str());
pos+=14;
e->waterAreaMeters=atoi(line.substr(pos,14).c_str());
pos=143; //latitude marker always starts at 143
if(line[pos]=='-'){ //'-' denotes [S]outh
e->lati='S';
}
else
e->lati='N';
pos++;
e->latitude=atof(line.substr(pos,8).c_str());
pos=153;
while(!isdigit(line[pos+1]))//move position to longitude marker
pos++;
if(line[pos]=='-'){ //'-' denotes [W]est
e->longi='W';
}
else
e->longi='E';
e->longitude=atof(line.substr(pos,8).c_str());
e->hashString=getHashable(e->state+e->name);//generates string to be used for hashing: state abreviation+place name ALL CAPS.
}//end extractData
void lookUp(HashTable *hashT, entry **places){
string abrev="",str="",hashStr="";
int counter=0;
while(counter<2){
cout << "Place [" << (counter+1) << "] "<< "Enter State Abreviation: ";
abrev=readLine();
cout << "Enter Place Name: ";
str=readLine();
if(str=="done" || abrev=="done"){
system("PAUSE");
exit(1);
}
else{
hashStr=getHashable(abrev+str);//get hash string of place entered by user
entry *e=hashT->getEntry(hashStr);//get entry assosciated with that hash string
if(e!=NULL){
places[counter]=e;
counter++;
}
}
}
}//end lookUp
string getHashable(string str){
int pos=0;
string hashStr="";
while(pos<str.length()){
if(str[pos]>0){ //toupper doesn't work on special chars, so they are left out of the hashString
if(!isdigit(str[pos]) && !isspace(str[pos]))
hashStr+=toupper(str[pos]);
}
pos++;
}
return hashStr;
}//end getHashable
string readLine(){
string r="";
while (true){
int c = getc(stdin);
if (c=='\n' || c==EOF)
break;
r+=(char)c;
}
return r;
}//end readLine
char *get_coverage_file(float* x, float * y){
float xMin, xMax, yMin, yMax;
if(x[0]<x[1]){
xMin=x[0];xMax=x[1];
}else{
xMin=x[1]; xMax=x[0];
}
if(y[0]<y[1]){
yMin=y[0]; yMax=y[1];
}else{
yMin=y[1]; yMax=y[0];
}
FILE *f = fopen("coverage.txt", "r+"); //"r+" for reading
if (f == NULL){
cerr << "Can't create coverage file.\n";
exit(1);
}
int numFiles=0;//number of files that cover both locations
float distance_x=0, distance_y=0;//dimensions of the smallest file covering both locations
char fName[18];//FileData name assosciated with the file
while(true){
CoverageInfo ci;//struct to hold data from coverage.txt file
int n = fscanf(f,"%d %d %d %d %s", &ci.latTop, &ci.latBot, &ci.longLeft, &ci.longRight, ci.fileName);//load data into struct
if(n==EOF)
{
fclose(f);
break;
}
if(xMin>ci.longLeft && xMax<ci.longRight && yMin>ci.latBot && yMax<ci.latTop){
numFiles++;
//for first file found set inital dimensions, otherwise compare new dimensions to the previous best, update if necessary
if(numFiles==1 || abs(ci.longLeft-ci.longRight)*(ci.latTop-ci.latBot)<(distance_x*distance_x)){
distance_x=abs(ci.longLeft-ci.longRight);
distance_y=(ci.latTop-ci.latBot);
strcpy(fName,ci.fileName);//update fileName
}
}
}
if(numFiles>0)//at least one file was found
return fName;
else{
cout << "NO COVERAGE FILE COVERS BOTH LOCATIONS" << endl;
system("PAUSE");
return "NULL";
}
}//end get_coverage_file
void read_file(FileData * fd){
FILE *fdat = fopen(fd->fileName.c_str(), "rb"); //"rb" for reading binary
if (fdat == NULL){
cerr << "Can't create file.\n";
exit(1);
}
char h[16];//holder
int n = fscanf(fdat,"%s %d %s %d %s %d %s %d %s %d %s %d %s %d %s %d %s %d", h, &fd->rows, h, &fd->cols, h, &fd->bpp, h, &fd->spp, h, &fd->lls, h, &fd->tls, h, &fd->min, h, &fd->max, h, &fd->sv);
if(n!=18)
cerr << "Meta Data extraction error.\n";
short *data = new short[fd->cols*fd->rows];//structure to hold the short int data
fseek(fdat,sizeof(short)*fd->cols,SEEK_SET); //seek to the start of data
fread(data,sizeof(short),fd->cols*fd->rows,fdat);//extract the data
fclose(fdat);
fd->d=data;//store data in FileData structure
}//end read_file
void load_locations_and_roads(FileData *fd, Vertex *v, RoadSection * sections){
float leftLong=fd->lls, topLat=fd->tls, secpp=fd->spp, x=0 ,y=0;
string str="";
FILE *floc = fopen("locations.txt", "r+");
if (floc == NULL){
cerr << "Can't create file.\n";
exit(1);
}
int i = 0;
while(true){
Location *l = new Location;
int n = fscanf(floc, "%f %f %f %d %s %s %[^\n]", &l->longitude, &l->latitude, &l->distanceTo, &l->pop, l->type, l->abv, l->name);//extract necessary data from file
if(n==EOF){
fclose(floc);
break;
}
//calculate grid cords given long/lat cords and map info from filedata
x=l->longitude*3600,
y=l->latitude*3600;
x=abs((leftLong-x)/(secpp));
y=abs((topLat-y)/(secpp));
l->x=x; l->y=y;
v[i].l=l;//assign location point to vertex
v[i].index=i;//assign location index to vertex
i++;
}
FILE *froad = fopen("majorroads.txt", "r+");
if (froad == NULL){
cerr << "Can't create file.\n";
exit(1);
}
i = 0;
while(true){
int n = fscanf(froad, "%s %s %d %d %f", sections[i].name, sections[i].type, §ions[i].locIndexA, §ions[i].locIndexB, §ions[i].length);//extract necessary data from file
if(n==EOF){
fclose(froad);
break;
}
i++;
}
}//end load_locations_and_roads
int*get_color_map(){
int cmap[4049]; //Heighest elevation is 4048m
int i = 0, pos=0; //i is the iterator, pos is the array starting array index for eahc loop
double r=0,g=0,b=0; //red, green, blue
while(i<=152){
r=0.0; g=.25+.75*(i/152.0); b=0.0;
cmap[pos+i]=make_color(r,g,b);
i++;
//r=0.0 g=1.0 b=0.0 (Dark Green)
}
pos+=i;
i=0;
while(i<=152){
r=.66*(i/152.0); g=1.0; b=.184*(i/152.0);//interpolating colors
cmap[pos+i]=make_color(r,g,b);
i++;
//r=.66 g=1.0 b=.184 (Green-Yellow)
}
pos+=i;
i=0;
while(i<=304){
r=.66+.34*(i/304.0); g=1.0; b=.184-.184*(i/304.0);
cmap[pos+i]=make_color(r,g,b);
i++;
//r=1.0 g=1.0 b=0.0 (Yellow)
}
pos+=i;
i=0;
while(i<=912){
r=1.0; g=1.0-.33*(i/912.0); b=0.0;
cmap[pos+i]=make_color(r,g,b);
i++;
//r=1.0 g=.66 b=.0.0 (Orange)
}
pos+=i;
i=0;
while(i<=1523){
r=1.0-.46*(i/1523.0); g=.66-.39*(i/1523.0); b=.074*(i/1523.0);
cmap[pos+i]=make_color(r,g,b);
i++;
//r=.54 g=.27 b=.074 (Brown)
}
pos+=i;
i=0;
while(i<=1000){
r=.54+.205*(i/1000.0); g=.27+.475*(i/1000.0); b=.074+.671*(i/1000.0);
cmap[pos+i]=make_color(r,g,b);
i++;
//r=.745 g=.745 b=.745 (Gray)
}
return cmap;
}//end get_color_map
void draw_map(FileData *fd,int *cmap){
int cols = fd->cols, rows=fd->rows;
int col=0,row=0;//iterators for drawing pixels at (row,col)
short *data = fd->d;
for(int i = 0; i < (cols*rows); i++){
//my data is stored in a 1-dimensional array so the row counter needs to be incremented at multiples of the total column length
if(i%cols==0){
col=0;
row++;
}
if(data[i]==-500 || data[i]==fd->sv)//-500 is special value for water
set_pen_color(color::light_blue);
else{
if(data[i]<0)//there shouldn't be any negative data
data[i]=0;
if(data[i]>4048)//4048 should be heighest elevation possible
data[i]=4048;
set_pen_color(cmap[data[i]]);//loads color from pallet to match elevation data
}
draw_point(col,row);
col++;
}
return;
}//end draw_map
void find_shortest_path(Vertex *v, RoadSection *secs, int*indices, bool drawPaths){
int A=indices[0], B=indices[1];
vHeap h;//min-heap structure
set_pen_width_color(1,color::purple);//for drawing roads while searching
v[A].shortest=0;//Set starting location shortest path value to 0.
v[A].exp=true;//Set starting location explored value to true
int index = A;//Set current index to starting location
while(v[B].exp==false){
for(int i=0; i<47015; i++){
if(secs[i].locIndexA==index && v[secs[i].locIndexB].exp==false){
int j=secs[i].locIndexB;
if(v[index].shortest+secs[i].length<v[j].shortest){
v[j].shortest=v[index].shortest+secs[i].length;//update shortest distance to vertex
v[j].prev=index;//update previous vertex
if(drawPaths){
move_to(v[index].l->x,v[index].l->y);
draw_to(v[j].l->x,v[j].l->y);
}
h.AddElement(v[j]);//add vertex to heap
}
}
if(secs[i].locIndexB==index && v[secs[i].locIndexA].exp==false){
int k=secs[i].locIndexA;
if(v[index].shortest+secs[i].length<v[k].shortest){
v[k].shortest=v[index].shortest+secs[i].length;//update shortest distance to vertex
v[k].prev=index;//update previous vertex
if(drawPaths){
move_to(v[index].l->x,v[index].l->y);
draw_to(v[k].l->x,v[k].l->y);
}
h.AddElement(v[k]);//add vertex to heap
}
}
}
if(h.hSize()>=1){
index=h.RemoveRoot().index;//pop vertex with shortest path from heap
while(v[index].exp==true && h.hSize()>=1){//make sure that vertex hasn't already been fully explored and hash table isn't empty
index=h.RemoveRoot().index;
}
v[index].exp=true;//set current vertex index to sortest fully explored, this will be used next
}else{
cout << "HEAP ERROR -- NO PATH" << endl;
system("PAUSE");
exit(1);
}
}
draw_shortest_path(v,secs,indices);
}//end shortest_path
void draw_shortest_path(Vertex *v, RoadSection* secs, int *indices){
int A=indices[0], B=indices[1];
int loc1=v[B].index, loc2=v[B].prev;
vector<RoadSection *> roadList;
set_pen_width_color(2,color::red);
//go backwards from B to the previous index, repeat until we get to A
while(loc2!=-1){
for(int q=0; q < 47015; q++){
if((secs[q].locIndexA==loc1 && secs[q].locIndexB==loc2)){
secs[q].c='B';//remember we arrived at this road at index B
roadList.push_back(&secs[q]);
break;
}
if((secs[q].locIndexB==loc1 && secs[q].locIndexA==loc2)){
secs[q].c='A';//remember we arrived at this road at index A
roadList.push_back(&secs[q]);
break;
}
}
move_to(v[loc1].l->x,v[loc1].l->y);
draw_to(v[loc2].l->x,v[loc2].l->y);
loc1=loc2;//move back one road and repeat
loc2=v[loc2].prev;
}
print_directions(v,roadList);
}//end draw_shortest_path
void print_directions(Vertex *v,vector<RoadSection *>final){
show_console();
float distance = 0, dt=0, degree=0, x0=0, x1=0, y0=0, y1=0;
int a=0, b=0;
bool newRoad=true;
//start at end since we compiled our roadList from B to A
for(int i = final.size()-1; i>=0; i--){
distance+=final[i]->length;//update distance traveled on current road
if(newRoad==true){
if(final[i]->c=='A')//if road section started at locIndexA, we want locIndexA for the start point
a=final[i]->locIndexA;
else
a=final[i]->locIndexB;
}
//if there is at least 2 roads to compare and those roads have the same name, nothing needs to be done
if((i-1)>=0 && strcmp(final[i]->name,final[i-1]->name)==0){
newRoad=false;
}else{
if(final[i]->c=='A')//if road section started at locIndexA, we want locIndexB for the end point
b = final[i]->locIndexB;
else
b = final[i]->locIndexA;
x0=v[a].l->longitude; y0=v[a].l->latitude;
x1=v[b].l->longitude; y1=v[b].l->latitude;
degree=atan2(y1-y0,x1-x0)*180.0/PI;//convert from lat/longitude cords to a direction in degrees
if(degree<0)
degree=degree+360.0;//get rid of negative values
cout << "Take " << final[i]->name << "\nHead " << get_compas_direction(degree) << "\t for " << distance*69.0 << " miles" << endl;
cout << "-----------------------------------------------------------------\n";
dt+=distance;//update total distance
distance=0;//reset distance traveled on current road to 0
newRoad=true;//set new road to true
}
}
cout << "TOTAL DISTANCE:\t " << dt*69.0 << " miles " << endl;
}//end print_directions
string get_compas_direction(float d){
//separate 360 degrees into 8 compas directions, each covers 45 degrees.
string str="";
if((d>=0.0 && d<22.5) || (d>= 337.5 && d<=360.0))
str="East";
else if(d>=22.5 && d<67.5)
str="North East";
else if(d>=67.5 && d < 112.5)
str="North";
else if (d>=112.5 && d<157.5)
str="North West";
else if(d>=157.5 && d<202.5)
str="West";
else if(d>=202.5 && d<247.5)
str="South West";
else if(d>=247.5 && d<292.5)
str="South";
else if (d>=292.5 && d < 337.5)
str="South East";
return str;
}//end get_compas_direction
| true |
4c701696478c63d298e3ddabfe0f1097a60437bf | C++ | shivam-2002/cpp | /inheritence/hierarchical-inheritance.cpp | UTF-8 | 424 | 3.203125 | 3 | [] | no_license | #include<iostream>
using namespace std;
class B
{
protected:
int x;
public:
void input()
{
cout<<"Enter x: ";
cin>>x;
}
};
class D1:public B
{
protected: int y;
public:
void output()
{
y=x*x;
cout<<y<<endl;
}
};
class D2:public B
{
public:
void output()
{
cout<<(x*x*x);
}
};
main()
{
D1 d1;
D2 d2;
d1.output();
d2.output();
}
| true |
ae827f5cfdc8138ff56e9170ddf6c0b5c820b53b | C++ | ShawnTheHuman-zz/p0_4280 | /main.cpp | UTF-8 | 1,463 | 2.90625 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include "node.h"
#include "tree.h"
using namespace std;
int main(int argc, char** argv)
{
string inputFile,input;
FILE *fp;
fstream in,pre,post;
if (argc == 1)
{
ofstream temp, in, post, pre;
temp.open("output.sp2021");
printf("Enter data through keyboard, CTRL+c to save and exit.\n");
while(cin >> input){
temp << input << endl;
}
temp.close();
struct node *root = NULL;
root = buildTree("output.sp2021");
in.open("out.inorder");
pre.open("out.preorder");
post.open("out.postorder");
in.close();
pre.close();
post.close();
printInorder(root, "output.inorder",0);
printPostorder(root, "output.postorder",0);
printPreorder(root, "output.preorder",0);
}
else if (argc == 2)
{
struct node *root = NULL;
string infile = argv[1];
root = buildTree(infile.c_str());
ofstream out;
if(out.is_open()) {
out.open(infile.c_str());
printInorder(root,infile,0);
printPostorder(root,infile,0);
printPreorder(root,infile,0);
}
else{
cout << "Error opening file.\n";
exit(0);
}
}
else
{
cout << "ERROR: too many arguments" << std::endl;
}
return 0;
}
| true |
61bf45bd5d6ba248357be0eead96a2beb0d2e6a0 | C++ | rs2488876/Salazar-RIcardo_CIS5_47948 | /Hmwk/Assingment_1/PracticeProgram_5/PP5.cpp | UTF-8 | 994 | 3.28125 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: Ricardo Jr
*
* Created on September 3, 2018, 9:11 PM
*/
#include <iostream>
using namespace std;
int main ( )
{
int width, height, totalLenght;
cout << "Press return after entering a number.\n";
cout << "Enter the length, in feet, of one of the short sides of the fence:\n";
cin >> width;
cout << "Enter the length, in feet, of one of the longer sides of the fence:\n";
cin >> height;
totalLenght = 2 * (width + height);
cout << "If you have ";
cout << width;
cout << " feet on one of the short sides of the fence\n";
cout << "and ";
cout << height;
cout << " feet on one of the longer sides of the fence, then\n";
cout << "you will need ";
cout << totalLenght;
cout << " feet of fencing.\n";
return 0;
} | true |
65d204c63e4b87c22d1793ebc89110900a494757 | C++ | ChanChiChoi/code_snippet | /cpu/Numerical_Analysis/Levenberg_Marquardt/Levenberg_Marquardt.cpp | UTF-8 | 2,422 | 3.140625 | 3 | [] | no_license | #include<iostream>
#include<iomanip>
#include<cmath>
#include<Eigen/Dense>
#include "Normal_LM.h"
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
void func(MatrixXd& mat, VectorXd& X){
mat(0,0)=1; mat(0,1)=3;
mat(1,0)=2; mat(1,1)=5;
mat(2,0)=2; mat(2,1)=7;
mat(3,0)=3; mat(3,1)=5;
mat(4,0)=4; mat(4,1)=1;
X(0)=1; X(1)=1; X(2)=1;
}
void getAfromJacobi(MatrixXd& A, MatrixXd& points, VectorXd& X){
for(int row=0; row<A.rows(); row++){
A(row,0) = exp(-X(1)*(points(row,0)-X(2))*(points(row,0)-X(2)));
A(row,1) = -X(0)*(points(row,0)-X(2))*(points(row,0)-X(2))*exp(-X(1)*(points(row,0)-X(2))*(points(row,0)-X(2)));
A(row,2) = 2*X(0)*X(1)*(points(row,0)-X(2))*exp(-X(1)*(points(row,0)-X(2))*(points(row,0)-X(2)));
}
}
float f(float c1, float c2, float c3, float t, float y){
return c1*exp(-c2*(t-c3)*(t-c3)) - y;
}
void get_r(VectorXd& r, MatrixXd& points,VectorXd& X){
r(0) = f(X(0),X(1),X(2),points(0,0), points(0,1));
r(1) = f(X(0),X(1),X(2),points(1,0), points(1,1));
r(2) = f(X(0),X(1),X(2),points(2,0), points(2,1));
r(3) = f(X(0),X(1),X(2),points(3,0), points(3,1));
r(4) = f(X(0),X(1),X(2),points(4,0), points(4,1));
}
//-----------------------------------
void Levenberg_Marquardt(MatrixXd& A, MatrixXd& points, VectorXd& X){
float epsilon = 1e-6;
float lambda = 50;
VectorXd xpre = X;
int i=0;
for(;;i++){
// 用方程组,计算Jacobi矩阵
getAfromJacobi(A,points,X);
cout<<"["<<i<<"]th A:"<<endl<<A<<endl;
//将当前的迭代值放入方程组,获取每个方程的值
VectorXd r(points.rows());
get_r(r,points,X) ;
//用法线方程计算下面式子
// A_T*A*v^k = -A^T * r(x^k)
// 然后这就是法线方程计算的过程,所以不需要事先左右两边乘以A^T
r *= -1;
cout<<"["<<i<<"]th r:"<<endl<<r<<endl;
VectorXd v = VectorXd::Zero(X.rows());
Normal_LM(A,lambda,r,v);
cout<<"["<<i<<"]th v:"<<endl<<v<<endl;
//进行迭代 x^(k1) = x^k + v^k;
X += v;
if ((X-xpre).norm()<epsilon )
break;
xpre = X;
}
}
int
main(){
MatrixXd points(5,2);
VectorXd X(3);
func(points,X);
cout<<"---mat:"<<endl<<points<<endl;
cout<<"---X:"<<endl<<X<<endl;
cout<<"---Gaussian Newton---"<<endl;
MatrixXd A = MatrixXd::Zero(5,3);
Levenberg_Marquardt(A,points,X);
cout<<"---x:"<<endl<<X<<endl;
}
| true |
8049078fda394ef5a412d31ea2c3329d6a99d47a | C++ | Plantyplantyplanty/CS3A | /animate.h | UTF-8 | 2,286 | 2.609375 | 3 | [] | no_license | #define _CRTDBG_MAP_ALLOC
#ifndef GAME_H
#define GAME_H
#include "system.h"
#include "sidebar.h"
#include "fileHandler.h"
#include <fstream>
class animate {
public:
animate();
/*Big Three*/
animate(animate& rhs);
animate& operator=(const animate& rhs);
~animate();
void run();
//Runs the program
void processEvents();
//Takes in user input and processes it
void update();
//Calls system's step and updates the mouse pointer
void render();
//Clears, draws, and displays the window
void Draw();
//Draws the calculator. Takes into account the input and help flags.
private:
void copy(const animate &rhs); //For the copy constructor
Graph_info* _info;
sf::RenderWindow window;
sf::CircleShape mousePoint; //The little red dot
System system; //container for all the animated objects
bool mouseIn; //mouse is in the screen
Sidebar sidebar; //rectangular message sidebar
bool input; //if input is being entered
bool help; //if display "help". First set by sidebar
Queue<string> oldEq; //Contains all of the equations entered in this session
fileHandler f; //handles the saving of old equations
void initializeText(); //Sets all the attributes of the text objects
void initializeFuncBox(); //Sets all the attributes of the function box
string getMyTextLabel(); //Gets the string for the text label
void stripSpaces(string& str); //strips the white spaces from a string
sf::Font font; //font to draw on main screen
sf::Text myTextLabel; //text to draw on main screen
sf::String equationInput; //The new equation as a set of characters
sf::Text newEquation; //The new equation as a string
sf::Text yequals; //holds the string y =
sf::Text Help; //Holds the help
sf::RectangleShape functionBox; //To draw the function box
};
//Returns the mouse position as a string
string mouse_pos_string(sf::RenderWindow& window);
#endif // GAME_H
| true |
688bb1857c758fb34413bbd3c3690d5120117aa8 | C++ | MayankChaturvedi/competitive-coding | /codechef/carvans.cpp | UTF-8 | 348 | 2.53125 | 3 | [] | no_license | #include<stdio.h>
int main()
{ int t, n, x, y, c;
scanf("%d",&t);
while(t--)
{ scanf("%d",&n); c=0; y=0;
while(n--)
{ scanf("%d",&x);
if(y>=x || y==0)
{ c++;
}
else{x=y;}
y=x;
}
printf("%d\n",c);
}
return 0;
}
| true |
04d750ca70babfdfdd1e0cabb1c8412a18cbfc31 | C++ | vikas436/DSA | /Leetcode - top 100 liked question/1. Two Sum.cpp | UTF-8 | 417 | 2.765625 | 3 | [] | no_license | class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int>mp;
vector<int> vec;
for(int i=0;i<nums.size();i++) {
if(mp.find(target-nums[i])!=mp.end()) {
vec.push_back(mp[target-nums[i]]);
vec.push_back(i);
return vec;
}
mp[nums[i]]=i;
}
return vec;
}
};
| true |
969754b14ac93e8782d578f9ee2746eaf0891275 | C++ | Siimon13/Data-Structure-HW | /8/Balance.cpp | UTF-8 | 6,705 | 2.875 | 3 | [] | no_license | /*
Simon Chen
N10013388
sc4900
*/
// Code from Weiss
// Symbol is the class that will be placed on the Stack.
// This is code from Weiss
#include <iostream>
#include <fstream>
#include <string>
#include <stack>
#include <sstream>
#include <map>
#include <vector>
using namespace std;
class Tokenizer
{
public:
Tokenizer( istream & input )
: currentLine( 1 ), errors( 0 ), inputStream( input ) { }
// The public routines
char getNextOpenClose( );
string getNextID( );
int getLineNumber( ) const;
int getErrorCount( ) const;
private:
enum CommentType { SLASH_SLASH, SLASH_STAR };
istream & inputStream; // Reference to the input stream
char ch; // Current character
int currentLine; // Current line
int errors; // Number of errors detected
// A host of internal routines
bool nextChar( );
void putBackChar( );
void skipComment( CommentType start );
void skipQuote( char quoteType );
string getRemainingString( );
};
// nextChar sets ch based on the next character in
// inputStream and adjusts currentLine if necessary.
// It returns the result of get.
// putBackChar puts the character back onto inputStream.
// Both routines adjust currentLine if necessary.
bool Tokenizer::nextChar( )
{
if( !inputStream.get( ch ) )
return false;
if( ch == '\n' )
currentLine++;
return true;
}
void Tokenizer::putBackChar( )
{
inputStream.putback( ch );
if( ch == '\n' )
currentLine--;
}
// Precondition: We are about to process a comment;
// have already seen comment start token.
// Postcondition: Stream will be set immediately after
// comment ending token.
void Tokenizer::skipComment( CommentType start )
{
if( start == SLASH_SLASH )
{
while( nextChar( ) && ( ch != '\n' ) )
;
return;
}
// Look for */
bool state = false; // Seen first char in comment ender.
while( nextChar( ) )
{
if( state && ch == '/' )
return;
state = ( ch == '*' );
}
cout << "Unterminated comment at line " << getLineNumber( ) << endl;
errors++;
}
// Precondition: We are about to process a quote;
// have already seen beginning quote.
// Postcondition: Stream will be set immediately after
// matching quote.
void Tokenizer::skipQuote( char quoteType )
{
while( nextChar( ) )
{
if( ch == quoteType )
return;
if( ch == '\n' )
{
cout << "Missing closed quote at line " << ( getLineNumber( ) - 1 ) << endl;
errors++;
return;
}
// If a backslash, skip next character.
else if( ch == '\\' )
nextChar( );
}
}
// Return the next opening or closing symbol or '\0' (if EOF).
// Skip past comments and character and string constants.
char Tokenizer::getNextOpenClose( )
{
while( nextChar( ) )
{
if( ch == '/' )
{
if( nextChar( ) )
{
if( ch == '*' )
skipComment( SLASH_STAR );
else if( ch == '/' )
skipComment( SLASH_SLASH );
else if( ch != '\n' )
putBackChar( );
}
}
else if( ch == '\'' || ch == '"' )
skipQuote( ch );
else if( ch == '\\' ) // Extra case, not in text
nextChar( );
else if( ch == '(' || ch == '[' || ch == '{' ||
ch == ')' || ch == ']' || ch == '}' )
return ch;
}
return '\0'; // End of file
}
// Return current line number.
int Tokenizer::getLineNumber( ) const
{
return currentLine;
}
// Return current line number.
int Tokenizer::getErrorCount( ) const
{
return errors;
}
// Return indicates if ch can be part of a C++ identifier.
bool isIdChar( char ch )
{
return ch == '_' || isalnum( ch );
}
// Return an identifier read from input stream.
// First character is already read into ch.
string Tokenizer::getRemainingString( )
{
string result;
for( result = ch; nextChar( ); result += ch )
if( !isIdChar( ch ) )
{
putBackChar( );
break;
}
return result;
}
// Return next identifier, skipping comments
// string constants, and character constants.
// Return "" if end of stream is reached.
string Tokenizer::getNextID( )
{
while( nextChar( ) )
{
if( ch == '/' )
{
if( nextChar( ) )
{
if( ch == '*' )
skipComment( SLASH_STAR );
else if( ch == '/' )
skipComment( SLASH_SLASH );
else
putBackChar( );
}
}
else if( ch == '\\' )
nextChar( );
else if( ch == '\'' || ch == '"' )
skipQuote( ch );
else if( !isdigit( ch ) && isIdChar( ch ) )
return getRemainingString( );
}
return ""; // End of file
}
struct Symbol
{
char token;
int theLine;
};
class Balance
{
public:
Balance( istream & is ):tok( is ),errors( 0 ){}
int checkBalance(); // returns the number of mismatched parenthesis
private:
Tokenizer tok;
int errors;
void checkMatch( const Symbol & oParen, const Symbol & cParen );
};
int Balance::checkBalance(){
stack<char> parastack;
char currpara = '\n';
char check;
while(currpara != '\0'){
currpara = tok.getNextOpenClose();
if (currpara == '(' || currpara == '{' || currpara == '['){
parastack.push(currpara);
}
else if( currpara != '\0'){
if (parastack.size() == 0){
errors++;
}
else{
check = parastack.top();
parastack.pop();
if ((currpara == ')' && check != '(') ||
(check == '{' && currpara != '}') ||
(check == '[' && currpara != ']')){
errors++;
}
}
}
}
errors += parastack.size();
return errors;
}
void Balance::checkMatch( const Symbol & oParen, const Symbol & cParen ){
}
void stringToUpper(string &s)
{
for(unsigned int l = 0; l < s.length(); l++)
{
s[l] = toupper(s[l]);
}
}
int wordValue (const vector<int>& pointValues, const string& word) {
int points = 0;
string uWord = word;
stringToUpper(uWord);
for(const char& c : uWord) {
int ind = c-'A';
points += pointValues[ind];
}
return points;
}
int main(){
ifstream ifs("Letter_point_value.txt");
if (!ifs) cerr << "Failure to open file" << endl;
char letter;
int pt;
vector<int> ptVal(26);
map<char, int> ptdict;
while (ifs >> pt >> letter) {
int ind = letter - 'A';
ptVal[ind] = pt;
}
// cout << wordValue(ptVal, "cAT");
ifstream efs("ENABLE.txt");
if (!efs) cerr << "Failure to open file" << endl;
string word;
map<string, int> wordValues;
while(efs >> word){
wordValues[word] = wordValue(ptVal,word);
}
// cerr << "test.cc" << endl;
// Balance b(ifs);
// cout << b.checkBalance();
}
| true |
2c1b77e1653bf3b76a22cf5b95fcd0e032a5501a | C++ | DanielDFY/LeetCode | /Problems/437. Path Sum III/solution.h | UTF-8 | 1,134 | 3.140625 | 3 | [
"MIT"
] | permissive | #ifndef LEETCODE_SOLUTION_H
#define LEETCODE_SOLUTION_H
#include <vector>
using std::vector;
#include <unordered_map>
using std::unordered_map;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
unordered_map<int, int> cache;
return pathSum(root, sum, cache, 0);
}
private:
int pathSum(TreeNode* root, int sum, unordered_map<int, int>& cache, int preSum) {
if (root == nullptr)
return 0;
int curSum = root->val + preSum;
int res = (curSum == sum) + (cache.count(curSum - sum) ? cache[curSum - sum] : 0);
++cache[curSum];
res += pathSum(root->left, sum, cache, curSum)
+ pathSum(root->right, sum, cache, curSum);
--cache[curSum];
return res;
}
};
#endif //LEETCODE_SOLUTION_H | true |
945fa646382e6162b9e032d52f2f528da0924566 | C++ | HectorDiazFlores98/CSUSB-CSE-Courses | /CSE202/lab5/slots.cpp | UTF-8 | 3,478 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
void displaySlotMachine(vector<int>&slotArray)
{
cout << " ---Slot Machine----\n";
cout << "Line 1 |- " << slotArray[0] << " | " << slotArray[1] << " | " << slotArray[2] << " -|\n";
cout << " -------------------\n";
cout << "Line 2 |- " << slotArray[3] << " | " << slotArray[4] << " | " << slotArray[5] << " -|\n";
cout << " -------------------\n";
cout << "Line 3 |- " << slotArray[6] << " | " << slotArray[7] << " | " << slotArray[8] << " -|\n";
}
void checkWinorLoss(vector<int>&slotArray, int &userBet, int &userCoins)
{
if(slotArray[3] == slotArray[4] && slotArray[4] == slotArray[5])
{
cout << "\nLine 2 win!\nYou won " << userBet*100 << " coins!\n";
userCoins += (userBet * 100);
}
else if(slotArray[0] == slotArray[1] && slotArray[1] == slotArray[2])
{
cout << "\nLine 1 win!\nYou won " << userBet*50 << " coins!\n";
userCoins += (userBet * 50);
}
else if(slotArray[6] == slotArray[7] && slotArray[7] == slotArray[8])
{
cout << "\nLine 3 win!\nYou won " << userBet*50 << " coins!\n";
userCoins += (userBet * 50);
}
else if(slotArray[0] == slotArray[4] && slotArray[4] == slotArray[8])
{
cout << "\nDiagonal down win!\nYou won " << userBet*25 << " coins!\n";
userCoins += (userBet * 25);
}
else if(slotArray[6] == slotArray[4] && slotArray[4] == slotArray[2])
{
cout << "\nDiagonal up win!\nYou won " << userBet*25 << " coins!\n";
userCoins += (userBet * 25);
}
else
{
cout << "Bad luck, you lost: " << userBet << " coins!";
userCoins -=userBet;
}
}
void checkBet(int &userCoins, int &userBet, bool &gameOver)
{
if(userCoins == 0)
{
gameOver = true;
}
else if(userBet == 99)
{
gameOver = true;
}
}
int main()
{
srand(time(NULL));
//This block is for users coins
bool gameOver = false;
int userCoins = 100;
int userBet = 0;
vector<int>slotArray;
for(int i = 0; i <= 9; i++)
{
slotArray.push_back(rand() % 9 + 1);
}
//intro message
cout << "Welcome to the slot machine\n"
<< "You start with 100 coins to bet with.\n"
<< "The game ends when you run out of coins, or you type in 99 in the coin selection\n";
while(userBet != 99 && userCoins >= 1)
{
cout << "\nPlease choose to bet 1, 2 or 3 coins, or enter 99 to cash out: ";
cin >> userBet;
while(userBet != 99 && userCoins >= 1)
{
displaySlotMachine(slotArray);
checkWinorLoss(slotArray,userBet,userCoins);
for(int k = 0; k <=slotArray.size()-1;k++)
{
slotArray[k] = rand() % 9 + 1;
}
cout << "\nCoins: " << userCoins << endl;
cout << "\nPlease choose to bet 1, 2 or 3 coins, or enter 99 to cash out: ";
cin >> userBet;
}
if(userCoins <= 1)
{
cout << "You've lost all your coins!\n"
<< "Better luck next time!\n";
}
else if(userBet == 99)
{
cout << "Thanks for playing\n"
<< "You're cashing out with " << userCoins << " coins!\n";
}
}
} | true |
caba7bcb0e760064641fcd4b7504a9065ef2a575 | C++ | nakru03/Baekjoon_Practice | /BaaaaaaaaaaarkingDog의 실전 알고리즘/0x01/2562.cpp | UTF-8 | 343 | 2.734375 | 3 | [] | no_license | #include <bits/stdc++.h>
#include <vector>
using namespace std;
int main() {
vector<int> arr;
for(int i=0; i<9; ++i) {
int n;
cin >> n;
arr.push_back(n);
}
cout<<*max_element(arr.begin(), arr.end())<<"\n";
int index = max_element(arr.begin(), arr.end()) - arr.begin();
cout << index+1<<"\n";
} | true |
532e9209aa1456e451a5f973b4880d3a9c5045a3 | C++ | ORTConectandoCosas/thingsBoardLED | /thingsBoardLED/thingsBoardLED.ino | UTF-8 | 7,343 | 2.59375 | 3 | [] | no_license |
/* Ejemplo para utilizar la comunicación con thingboards paso a paso con nodeMCU v2
* Gastón Mousqués
* Basado en varios ejemplos de la documentación de https://thingsboard.io
*
*/
// includes de bibliotecas para comunicación
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
//***************MODIFICAR PARA SU PROYECTO *********************
// includes de bibliotecas sensores, poner las que usen en este caso un DHT11 y un Servo
#include "DHT.h"
//***************MODIFICAR PARA SU PROYECTO *********************
// configuración datos wifi
// descomentar el define y poner los valores de su red y de su dispositivo
#define WIFI_AP "SSID RED"
#define WIFI_PASSWORD "PASSWORD RED"
// configuración datos thingsboard
#define NODE_NAME "NOMBRE DISPOSITIVO" //nombre que le pusieron al dispositivo cuando lo crearon
#define NODE_TOKEN "TOKEN DISPOSITIVO" //Token que genera Thingboard para dispositivo cuando lo crearon
//***************NO MODIFICAR *********************
char thingsboardServer[] = "demo.thingsboard.io";
/*definir topicos.
* telemetry - para enviar datos de los sensores
* request - para recibir una solicitud y enviar datos
* attributes - para recibir comandos en baes a atributtos shared definidos en el dispositivo
*/
char telemetryTopic[] = "v1/devices/me/telemetry";
char requestTopic[] = "v1/devices/me/rpc/request/+"; //RPC - El Servidor usa este topico para enviar rquests, cliente response
// declarar cliente Wifi y PubSus
WiFiClient wifiClient;
PubSubClient client(wifiClient);
// declarar variables control loop (para no usar delay() en loop
unsigned long lastSend;
const int elapsedTime = 1000; // tiempo transcurrido entre envios al servidor
//***************MODIFICAR PARA SU PROYECTO *********************
// configuración sensores que utilizan
#define DHTPIN D1
#define DHTTYPE DHT11
// Declarar e Inicializar sensores.
DHT dht(DHTPIN, DHTTYPE);
//
//************************* Funciones Setup y loop *********************
// función setup micro
void setup()
{
Serial.begin(9600);
// inicializar wifi y pubsus
connectToWiFi();
client.setServer( thingsboardServer, 1883 );
// agregado para recibir callbacks
client.setCallback(on_message);
lastSend = 0; // para controlar cada cuanto tiempo se envian datos
// ******** AGREGAR INICIALZICION DE SENSORES PARA SU PROYECTO *********
pinMode(LED_BUILTIN, OUTPUT);
dht.begin(); //inicaliza el DHT
delay(10);
digitalWrite(LED_BUILTIN, LOW); // prender el LED
}
// función loop micro
void loop()
{
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > elapsedTime ) { // Update and send only after 1 seconds
// FUNCION DE TELEMETRIA para enviar datos a thingsboard
getAndSendData(); // FUNCION QUE ENVIA INFORMACIÓN DE TELEMETRIA
lastSend = millis();
}
client.loop();
}
//***************MODIFICAR PARA SU PROYECTO *********************
/*
* función para leer datos de sensores y enviar telementria al servidor
* Se debe sensar y armar el JSON especifico para su proyecto
* Esta función es llamada desde el loop()
*/
void getAndSendData()
{
// Lectura de sensores
Serial.println("Collecting temperature data.");
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
String temperature = String(t);
String humidity = String(h);
//Debug messages
Serial.print( "Sending temperature and humidity : [" );
Serial.print( temperature ); Serial.print( "," );
Serial.print( humidity );
Serial.print( "] -> " );
// Preparar el payload, a modo de ejemplo el mensaje se arma utilizando la clase String. esto se puede hacer con
// la biblioteca ArduinoJson
// el formato del mensaje es {key"value, Key: value, .....}
// en este caso seria {"temperature:"valor, "humidity:"valor}
//
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
// Enviar el payload al servidor usando el topico para telemetria
char attributes[100];
payload.toCharArray( attributes, 100 );
if (client.publish( telemetryTopic, attributes ) == true)
Serial.println("publicado ok");
Serial.println( attributes );
}
//***************MODIFICAR PARA SU PROYECTO *********************
/*
* Este callback se llama cuando se utilizan widgets de control que envian mensajes por el topico requestTopic
* Notar que en la función de reconnect se realiza la suscripción al topico de request
*
* El formato del string que llega es "v1/devices/me/rpc/request/{id}/Operación. donde operación es el método get declarado en el
* widget que usan para mandar el comando e {id} es el indetificador del mensaje generado por el servidor
*/
void on_message(const char* topic, byte* payload, unsigned int length)
{
// Mostrar datos recibidos del servidor
Serial.println("On message");
char message[length + 1];
strncpy ( message, (char*)payload, length);
message[length] = '\0';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println( message);
//Parsear mensaje usando ArduinoJson
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, message);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
//Obtener los valores que vienen en el Json
const char* method = doc["method"];
bool params = doc["params"];
// Print values.
Serial.print("método:");
Serial.print(method);
Serial.print("- Parametros:");
Serial.println(params);
// Segun el paramtro prender y apagar el LED del NodeMCU
if(params == true) {
digitalWrite(LED_BUILTIN, LOW);
}
else {
digitalWrite(LED_BUILTIN, HIGH);
}
}
//***************NO MODIFICAR - Conexion con Wifi y ThingsBoard *********************
/*
* funcion para reconectarse al servidor de thingsboard y suscribirse a los topicos de RPC y Atributos
*/
void reconnect() {
int statusWifi = WL_IDLE_STATUS;
// Loop until we're reconnected
while (!client.connected()) {
statusWifi = WiFi.status();
connectToWiFi();
Serial.print("Connecting to ThingsBoard node ...");
// Attempt to connect (clientId, username, password)
if ( client.connect(NODE_NAME, NODE_TOKEN, NULL) ) {
Serial.println( "[DONE]" );
// Suscribir al Topico de request
client.subscribe(requestTopic);
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.print( client.state() );
Serial.println( " : retrying in 5 seconds]" );
// Wait 5 seconds before retrying
delay( 5000 );
}
}
}
/*
* función para conectarse a wifi
*/
void connectToWiFi()
{
Serial.println("Connecting to WiFi ...");
// attempt to connect to WiFi network
WiFi.begin(WIFI_AP, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
| true |
acdd63d8a0b164e92e739e9d7655b56d229de872 | C++ | fabiankmroh/jamcodehs | /baekjoon/17611.cpp | UTF-8 | 1,673 | 2.71875 | 3 | [] | no_license | #include <stdio.h>
#include <vector>
#include <algorithm>
#define ZERO 500000
using namespace std;
int c[100010][2];
int horizontal[1000005];
int vertical[1000005];
vector <pair<int, int> > x; // Start, End
vector <pair<int, int> > y; // Start, End
int xmin = 500000;
int xmax = -500000;
int ymin = 500000;
int ymax = -500000;
int n, i;
int main(void){
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf("%d %d", &c[i][0], &c[i][1]);
}
c[n][0] = c[0][0];
c[n][1] = c[0][1];
for(i = 0; i < n; i++){
if(c[i][1] == c[i+1][1]){
if(c[i+1][0] > c[i][0])
x.push_back(make_pair(c[i][0], c[i+1][0]));
else
x.push_back(make_pair(c[i+1][0], c[i][0]));
}
if(c[i][0] == c[i+1][0]){
if(c[i+1][1] > c[i][1])
y.push_back(make_pair(c[i][1], c[i+1][1]));
else
y.push_back(make_pair(c[i+1][1], c[i][1]));
}
}
int l, r;
// x
for(i = 0; i < x.size(); i++){
l = x[i].first + ZERO;
r = x[i].second + ZERO;
horizontal[l]++;
horizontal[r]--;
}
// y
for(i = 0; i < y.size(); i++){
l = y[i].first + ZERO;
r = y[i].second + ZERO;
vertical[l]++;
vertical[r]--;
}
int cnt = 0;
int max = 0;
// Check X
for(i = 0; i < 1000005; i++){
cnt += horizontal[i];
if(max < cnt)
max = cnt;
}
cnt = 0;
for(i = 0; i < 1000005; i++){
cnt += vertical[i];
if(max < cnt)
max = cnt;
}
printf("%d\n", max);
return 0;
} | true |
6638e384e0f3bd74ea09bea9295d92e95a7f9981 | C++ | sakishum/My_Algorithm | /BCZM/get_count_of_1_from_char/main.cpp | UTF-8 | 1,056 | 3.3125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
// 有/无符号整型
int getAllOne(char data) {
char a = 0x1;
int count = 0;
for (int i = 0; i != 8; ++i) {
if (((data >> i) & a) == 1) {
++count;
}
}
return count;
}
// 只针对无符号整型
int getAllOneDx(char data) {
unsigned char count = 0;
while (data > 0) {
++count;
data = data & (data - 1);
}
return count;
}
int getBit(long int a) {
int count = 0;
while (a>0) {
a >>= 1;
++count;
}
return count;
}
bool isPowerOfTwo(long int a) {
bool ret = false;
if ((a & (a-1)) == 0) {
ret = true;
}
return ret;
}
int main(int, char**) {
// 7 : 0000 0111
// -7 : 1111 1001
// -7 + 3:
// 1111 1001
// +0000 0011
// ------------
// 1111 1100
// >1000 0011 + 1
// 1000 0100 => -4
//char data = 0x7;
char data = 7;
//int count = getAllOne(data);
int count = getAllOneDx(data);
printf("result = %d\n", count);
printf("ret = %d\n", getBit(256)); // 9 位
// 求是否是2的幂
if (isPowerOfTwo(16)) {
printf("Is Power Of 2.\n");
}
exit(EXIT_SUCCESS);
}
| true |
43909d304045082c688d5b83f3c9f3df43f327fb | C++ | akhikolla/testpackages | /fuzzedpackages/rococo/src/rcor_bm.cpp | UTF-8 | 6,654 | 2.625 | 3 | [] | no_license | #include <math.h>
#include "rcor_bm.h"
#include "tnorms.h"
using namespace Rcpp;
RcppExport SEXP rcor_matrix_classical(SEXP vx, SEXP r)
{
int i, j, n;
NumericVector x(vx);
n = x.length();
NumericMatrix Rx(n, n);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = 1;
Rx(j, i) = 0;
}
else if (x(i) > x(j))
{
Rx(j, i) = 1;
Rx(i, j) = 0;
}
}
}
return Rx;
}
RcppExport SEXP rcor_matrix_linear(SEXP vx, SEXP r)
{
int i, j, n;
double rx;
NumericVector x(vx);
n = x.length();
NumericMatrix Rx(n, n);
rx = NumericVector(r)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = MIN(1, (x(j) - x(i)) / rx);
Rx(j, i) = 0;
}
else
{
Rx(j, i) = MIN(1, (x(i) - x(j)) / rx);
Rx(i, j) = 0;
}
}
}
return Rx;
}
RcppExport SEXP rcor_matrix_exp(SEXP vx, SEXP r)
{
int i, j, n;
double rx;
NumericVector x(vx);
n = x.length();
NumericMatrix Rx(n, n);
rx = NumericVector(r)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = 1 - exp((x(i) - x(j)) / rx);
Rx(j, i) = 0;
}
else
{
Rx(j, i) = 1 - exp((x(j) - x(i)) / rx);
Rx(i, j) = 0;
}
}
}
return Rx;
}
RcppExport SEXP rcor_matrix_gauss(SEXP vx, SEXP r)
{
int i, j, n;
double rx, x_res, x_diff;
NumericVector x(vx);
n = x.length();
NumericMatrix Rx(n, n);
rx = NumericVector(r)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
x_diff = x(i) - x(j);
x_res = 1 - exp(-0.5 * (x_diff / rx) * (x_diff / rx));
if (x(i) < x(j))
{
Rx(i, j) = x_res;
Rx(j, i) = 0;
}
else
{
Rx(j, i) = x_res;
Rx(i, j) = 0;
}
}
}
return Rx;
}
RcppExport SEXP rcor_matrix_epstol(SEXP vx, SEXP r)
{
int i, j, n;
double rx;
NumericVector x(vx);
n = x.length();
NumericMatrix Rx(n, n);
rx = NumericVector(r)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(j) > (x(i) + rx))
{
Rx(i, j) = 1;
Rx(j, i) = 0;
}
else if (x(i) > (x(j) + rx))
{
Rx(j, i) = 1;
Rx(i, j) = 0;
}
else
{
Rx(i, j) = Rx(j, i) = 0;
}
}
}
return Rx;
}
RcppExport SEXP rcor_matrices_classical(SEXP vx, SEXP vy, SEXP r1, SEXP r2)
{
int i, j, n;
NumericVector x(vx);
NumericVector y(vy);
n = x.length();
NumericMatrix Rx(n, n);
NumericMatrix Ry(n, n);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = 1;
Rx(j, i) = 0;
}
else if (x(i) > x(j))
{
Rx(j, i) = 1;
Rx(i, j) = 0;
}
if (y(i) < y(j))
{
Ry(i, j) = 1;
Ry(j, i) = 0;
}
else if (y(i) > y(j))
{
Ry(j, i) = 1;
Ry(i, j) = 0;
}
}
}
List ret = List::create(Named("Rx") = Rx, Named("Ry") = Ry);
return ret;
}
RcppExport SEXP rcor_matrices_linear(SEXP vx, SEXP vy, SEXP r1, SEXP r2)
{
int i, j, n;
double rx, ry;
NumericVector x(vx);
NumericVector y(vy);
n = x.length();
NumericMatrix Rx(n, n);
NumericMatrix Ry(n, n);
rx = NumericVector(r1)[0];
ry = NumericVector(r2)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = MIN(1, (x(j) - x(i)) / rx);
Rx(j, i) = 0;
}
else
{
Rx(j, i) = MIN(1, (x(i) - x(j)) / rx);
Rx(i, j) = 0;
}
if (y(i) < y(j))
{
Ry(i, j) = MIN(1, (y(j) - y(i)) / ry);
Ry(j, i) = 0;
}
else
{
Ry(j, i) = MIN(1, (y(i) - y(j)) / ry);
Ry(i, j) = 0;
}
}
}
List ret = List::create(Named("Rx") = Rx, Named("Ry") = Ry);
return ret;
}
RcppExport SEXP rcor_matrices_exp(SEXP vx, SEXP vy, SEXP r1, SEXP r2)
{
int i, j, n;
double rx, ry;
NumericVector x(vx);
NumericVector y(vy);
n = x.length();
NumericMatrix Rx(n, n);
NumericMatrix Ry(n, n);
rx = NumericVector(r1)[0];
ry = NumericVector(r2)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(i) < x(j))
{
Rx(i, j) = 1 - exp((x(i) - x(j)) / rx);
Rx(j, i) = 0;
}
else
{
Rx(j, i) = 1 - exp((x(j) - x(i)) / rx);
Rx(i, j) = 0;
}
if (y(i) < y(j))
{
Ry(i, j) = 1 - exp((y(i) - y(j)) / ry);
Ry(j, i) = 0;
}
else
{
Ry(j, i) = 1 - exp((y(j) - y(i)) / ry);
Ry(i, j) = 0;
}
}
}
List ret = List::create(Named("Rx") = Rx, Named("Ry") = Ry);
return ret;
}
RcppExport SEXP rcor_matrices_gauss(SEXP vx, SEXP vy, SEXP r1, SEXP r2)
{
int i, j, n;
double rx, ry;
double x_res, y_res;
double x_diff, y_diff;
NumericVector x(vx);
NumericVector y(vy);
n = x.length();
NumericMatrix Rx(n, n);
NumericMatrix Ry(n, n);
rx = NumericVector(r1)[0];
ry = NumericVector(r2)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
x_diff = x(i) - x(j);
y_diff = y(i) - y(j);
x_res = 1 - exp(-0.5 * (x_diff / rx) * (x_diff / rx));
y_res = 1 - exp(-0.5 * (y_diff / ry) * (y_diff / ry));
if (x(i) < x(j))
{
Rx(i, j) = x_res;
Rx(j, i) = 0;
}
else
{
Rx(j, i) = x_res;
Rx(i, j) = 0;
}
if (y(i) < y(j))
{
Ry(i, j) = y_res;
Ry(j, i) = 0;
}
else
{
Ry(j, i) = y_res;
Ry(i, j) = 0;
}
}
}
List ret = List::create(Named("Rx") = Rx, Named("Ry") = Ry);
return ret;
}
RcppExport SEXP rcor_matrices_epstol(SEXP vx, SEXP vy, SEXP r1, SEXP r2)
{
int i, j, n;
double rx, ry;
NumericVector x(vx);
NumericVector y(vy);
n = x.length();
NumericMatrix Rx(n, n);
NumericMatrix Ry(n, n);
rx = NumericVector(r1)[0];
ry = NumericVector(r2)[0];
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (x(j) > (x(i) + rx))
{
Rx(i, j) = 1;
Rx(j, i) = 0;
}
else if (x(i) > (x(j) + rx))
{
Rx(j, i) = 1;
Rx(i, j) = 0;
}
else
{
Rx(i, j) = Rx(j, i) = 0;
}
if (y(j) > (y(i) + ry))
{
Ry(i, j) = 1;
Ry(j, i) = 0;
}
else if (y(i) > (y(j) + ry))
{
Ry(j, i) = 1;
Ry(i, j) = 0;
}
else
{
Ry(i, j) = Ry(j, i) = 0;
}
}
}
List ret = List::create(Named("Rx") = Rx, Named("Ry") = Ry);
return ret;
}
| true |
59def0bdb77157b1c923b6b9490b4a59ea3f4db8 | C++ | gurusawhney/CS-Courses-Code | /Object Oriented Programming (C++)/Homework8/Polynomial.cpp | UTF-8 | 5,677 | 3.578125 | 4 | [] | no_license | #include "Polynomial.h"
#include <string>
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
Node::Node(int data, Node* link) : data(data), link(link) {}
void addEnd(int entry, Node*& headPtr) { //adds the node to the end of the linked list
if (headPtr == nullptr) { //checks if linked list is empty
headPtr = new Node(entry);
}
else {
Node* p = headPtr;
while (p->link != nullptr) { //finds end
p = p->link;
}
p->link = new Node(entry);
}
}
Polynomial::Polynomial() {}
Polynomial::Polynomial(const vector<int>& v = {0}) {
int headdata = v[0];
degree = 0;
Node* n = new Node(headdata);
headNode = n;
if (v.size() > 0) {
for (size_t i = 1; i < v.size(); i++) { //goes through vector
int tempdata = v[i];
addEnd(tempdata, headNode); //adds linked list from greatest to least
degree++; //adds degree level
}
}
}
Polynomial::~Polynomial() {
Node* temp = headNode;
while (temp != nullptr) {
Node* next = temp->link;
delete temp; //deletes the node
temp = next; //assigns temp node to the next node in the link
}
headNode = nullptr;
}
Node* Polynomial::getHead() {
return headNode;
}
int Polynomial::getDegree() {
return degree;
}
int Polynomial::evaluate(int num) {
Node* tempNode = headNode;
int tempdegree = degree;
int result = 0; //base result
while (tempNode != nullptr) {
if (tempdegree >= 1) {
result += (tempNode->data)*(pow(num,tempdegree)); //adds the value of each linked list to the result
}
else if (tempdegree == 0) { //since there are no x's this adds the last number
result += tempNode->data;
}
tempNode = tempNode->link;
tempdegree--; //decreases the degree for operation purposes
}
return result; //ending result
}
Polynomial& Polynomial::operator= (Polynomial& p) {
if (this != &p) { //if they are not the same
Node* temp = headNode;
while (temp != nullptr) { //deletes the original data
Node* next = temp->link;
delete temp;
temp = next;
}
headNode = nullptr;
degree = p.getDegree(); //copies the parameter's data
Node* selftemp = new Node(p.getHead()->data);
headNode = selftemp;
Node* copytemp = p.getHead();
if (degree > 0) {
while (copytemp->link != nullptr) {
Node* temp = new Node(copytemp->link->data);
selftemp->link = temp;
copytemp = copytemp->link;
selftemp = selftemp->link;
}
}
}
return *this;
}
Polynomial& Polynomial::operator+= (Polynomial& p) {
int degdiff = degree - p.getDegree(); //the difference between the degrees
if (degree >= p.getDegree()) {
Node* selftemp = headNode;
Node* addtemp = p.getHead();
for (size_t i = 0; i < degdiff; i++) { //allows me to skip the nodes in which the degree is higher
selftemp = selftemp->link;
}
while (selftemp != nullptr) {
selftemp->data += addtemp->data; //adds the data of the respective degree until the end
selftemp = selftemp->link;
addtemp = addtemp->link;
}
}
else if (p.getDegree() > degree) {
Polynomial temp(*this); //stores the lower value
*this = p; //assigns the higher value
Node* selftemp = headNode;
Node* addtemp = temp.getHead();
for (size_t i = 0; i < (degdiff*-1); i++) {
selftemp = selftemp->link; //this and below is the same function of adding as the previous circumstance
}
while (selftemp != nullptr) {
selftemp->data += addtemp->data;
selftemp = selftemp->link;
addtemp = addtemp->link;
}
}
return *this;
}
Polynomial::Polynomial(Polynomial& p) {
degree = p.getDegree(); //copy constructor
Node* selftemp = new Node(p.getHead()->data); //build headNode
headNode = selftemp;
Node* copytemp = p.getHead();
if (degree > 0) {
while (copytemp->link != nullptr) {
Node* temp = new Node(copytemp->link->data); //builds the list
selftemp->link = temp;
copytemp = copytemp->link;
selftemp = selftemp->link;
}
}
}
Polynomial operator+(Polynomial& lhs, Polynomial& rhs)
{
Polynomial temp(lhs);
temp += rhs; //uses the += operator
return temp;
}
ostream& operator<<(ostream& os, Polynomial& p) {
Node* tempNode = p.getHead();
int tempdegree = p.getDegree();
while (tempNode != nullptr) { //iterates through the linked list
if (tempNode->data != 0) os << showpos << tempNode->data; //prints out the coefficient
if (tempdegree > 1) {
os << "x^" << noshowpos << tempdegree; //prints out the variable with its degree
}
else if (tempdegree == 1 && tempNode->data != 0) { //since there is no degree just print out the x.
os << "x";
}
tempNode = tempNode->link;
tempdegree--; //decrease the degree for operation purposes
}
return os;
}
bool operator==(Polynomial& lhs, Polynomial& rhs) {
if (lhs.getDegree() == rhs.getDegree()) {
Node* left = lhs.getHead();
Node* right = rhs.getHead();
for (size_t i = 0; i <= lhs.getDegree(); i++) { //go through the polynomials
if (left->data == right->data) {
left = left->link;
right = right->link;
}
else return false;
}
return true; //if everything is equal returns false but when not in any case returns true
}
else return false;
}
bool operator!=(Polynomial& lhs, Polynomial& rhs) { //same as == but outputs opposite bool values
if (lhs.getDegree() == rhs.getDegree()) {
Node* left = lhs.getHead();
Node* right = rhs.getHead();
for (size_t i = 0; i <= lhs.getDegree(); i++) {
if (left->data == right->data) {
left = left->link;
right = right->link;
}
else return true;
}
return false;
}
else return true;
}
| true |
e8ea3787d8416a62831b845639bb601460837c02 | C++ | facebook/hermes | /include/hermes/VM/SingleObject.h | UTF-8 | 1,936 | 2.640625 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_VM_SINGLEOBJECT_H
#define HERMES_VM_SINGLEOBJECT_H
#include "hermes/VM/JSObject.h"
namespace hermes {
namespace vm {
/// JavaScript single object, include Math and JSON.
template <CellKind kind>
class SingleObject final : public JSObject {
public:
using Super = JSObject;
static const ObjectVTable vt;
static constexpr CellKind getCellKind() {
return kind;
}
static bool classof(const GCCell *cell) {
return cell->getKind() == kind;
}
/// Create a SingleObject.
static CallResult<HermesValue> create(
Runtime &runtime,
Handle<JSObject> parentHandle) {
auto *cell = runtime.makeAFixed<SingleObject>(
runtime,
parentHandle,
runtime.getHiddenClassForPrototype(
*parentHandle, numOverlapSlots<SingleObject>()));
return JSObjectInit::initToHermesValue(runtime, cell);
}
SingleObject(
Runtime &runtime,
Handle<JSObject> parent,
Handle<HiddenClass> clazz)
: JSObject(runtime, *parent, *clazz) {}
};
template <CellKind kind>
struct IsGCObject<SingleObject<kind>> {
static constexpr bool value = true;
};
template <CellKind kind>
const ObjectVTable SingleObject<kind>::vt = {
VTable(kind, cellSize<SingleObject<kind>>(), nullptr, nullptr),
SingleObject::_getOwnIndexedRangeImpl,
SingleObject::_haveOwnIndexedImpl,
SingleObject::_getOwnIndexedPropertyFlagsImpl,
SingleObject::_getOwnIndexedImpl,
SingleObject::_setOwnIndexedImpl,
SingleObject::_deleteOwnIndexedImpl,
SingleObject::_checkAllOwnIndexedImpl,
};
using JSMath = SingleObject<CellKind::JSMathKind>;
using JSJSON = SingleObject<CellKind::JSJSONKind>;
} // namespace vm
} // namespace hermes
#endif // HERMES_VM_SINGLEOBJECT_H
| true |
42f97a7f636d1fb81ed0f803132bc4fe83038d6c | C++ | watmough/Advent-of-Code-2018 | /day_07.cpp | UTF-8 | 4,663 | 2.96875 | 3 | [] | no_license | // Advent of Code 2018
// Day 07 - The Sum of Its Parts
#include "aoc.hpp"
using namespace std;
#if 1
#define FILENAME "day_07.txt"
#define COUNT 101
#define WORKERS 5
#define TIME 61
#else
#define FILENAME "day_07_tst.txt"
#define COUNT 7
#define WORKERS 2
#define TIME 1
#endif
void load_input(set<char>& chars, multimap<char,char>& has_dep)
{
// Sample data: Step T must be finished before step W can begin.
FILE *f = fopen(FILENAME,"rb");
char fs,ss;
while (!feof(f) && fscanf(f,"Step %c must be finished before step %c can begin.\n",&fs,&ss)) {
// printf("%c -> %c\n",fs,ss);
chars.insert(fs);
chars.insert(ss);
has_dep.insert(make_pair(ss,fs));
}
fclose(f);
}
set<char> available(set<char> chars, multimap<char,char> has_dep)
{
for (auto dep : has_dep) {
// cout << dep.first << " has dep of " << dep.second << "\n";
chars.erase(dep.first);
}
return chars;
}
multimap<char,char> done_step(char c, multimap<char,char> has_dep)
{
multimap<char,char> new_deps;
for (auto d : has_dep) {
if (d.second!=c)
new_deps.insert(d);
}
return new_deps;
}
// Part 1 - Calculate the required ordering of the steps given the constraints
void part1()
{
auto chars = set<char>{};
auto has_dep = multimap<char,char>{};
load_input(chars,has_dep);
auto order = string{""};
while (chars.size()>0) {
// candidates w/ no dependencies
auto candidates = available(chars,has_dep);
// do first only
auto c = *(begin(candidates));
order.push_back(c);
// done a task, make more tasks available
has_dep = done_step(c, has_dep);
chars.erase(c);
}
cout << "Part 1: The required task ordering is: " << order << "\n";
}
// Simulate a work queue ... of Elves
class work_queue
{
public:
work_queue(int workers) : tasks(), workers(workers), thetime{0} {};
bool inflight(char c) {
return any_of(begin(tasks),end(tasks),[&](const auto& t)->bool{return t.first==c;});
}
int gettime() {
return thetime;
};
int tick() { // tick to the soonest available job, returning the time (may be >1 job)
assert(haswork());
std::stable_sort(begin(tasks),end(tasks),[&](const auto& l,const auto& r){return l.second<r.second;});
return (thetime=tasks.front().second);
};
vector<pair<char,int>> completed()
{
auto done = vector<pair<char,int>>{};
copy_if(begin(tasks),end(tasks),std::back_inserter(done),[&](const auto& t)->bool{return t.second==thetime;});
for_each(begin(done),end(done),[&](const auto& t){tasks.erase(tasks.begin());});
return done;
}
bool haswork() {
return !tasks.empty();
}
bool busy() {
return tasks.size()==workers;
};
pair<char,int> work(char c) { // assign and return task,eta for this job
assert(!busy()); // must have at least one elf free
auto t = make_pair(c,thetime+/* 61 or 1 */TIME+c-'A');
tasks.push_back(t);
return t;
};
private:
vector<pair<char,int>> tasks;
int workers;
int thetime;
};
int part2()
{
auto chars = set<char>{};
auto has_dep = multimap<char,char>{};
load_input(chars,has_dep);
// create a work queue
work_queue w(WORKERS);
// get candidates for next worker
auto candidates = available(chars,has_dep);
// for each step,
while (chars.size()>0) {
// assign a worker
while (candidates.size() && !w.busy()) {
auto c = *(begin(candidates));
if (!w.inflight(c))
w.work(c);
candidates.erase(c);
}
// if busy, clock the next job to completion
if (w.busy() || candidates.size()==0) {
// clock
w.tick();
// handle completed tasks
auto done = w.completed();
for (auto completed : done) {
// cout << "Completed: " << completed.first << " at time: " << completed.second << "\n";
// completed a task
has_dep = done_step(completed.first, has_dep);
chars.erase(completed.first);
// refresh list of candidates
// ### No Clang warning for having an auto on the next line ###
candidates = available(chars,has_dep);
}
}
}
printf("Part 2: Finished at time: %d\n",w.gettime());
return 0;
}
int main()
{
part1();
part2();
return 0;
}
| true |
7d5c14d5c91fe4e0f5161dd7a033f0ed5f7df200 | C++ | Sandalf/numeric-expressions | /numeric-expressions/main.cpp | UTF-8 | 554 | 2.6875 | 3 | [] | no_license | //
// main.cpp
// numeric-expressions
//
// Created by Luis Sandoval on 12/10/19.
// Copyright © 2019 Luis Sandoval. All rights reserved.
//
#include <stdio.h>
#include <iostream>
extern FILE* yyin;
extern int yyparse();
extern float resultado;
bool parse(const char *fname) {
yyin = fopen(fname,"r");
int x = yyparse();
fclose(yyin);
return x == 0;
}
int main(int argc, const char * argv[]) {
if (parse("prueba.txt")) {
printf("Resultado: %f\n", resultado);
} else {
printf("Not ok\n");
}
return 0;
}
| true |
e1f93b66f0d1f61c9d3146c20658bcc770cdf8cc | C++ | yotam-medini/cj | /ymutil/factor.cc | UTF-8 | 2,204 | 2.984375 | 3 | [] | no_license | #include <array>
#include <vector>
using namespace std;
typedef unsigned u_t;
typedef vector<u_t> vu_t;
typedef array<u_t, 2> au2_t;
typedef vector<au2_t> vau2_t;
extern void tuple_next(vu_t& t, const vu_t& bound);
void factor(vau2_t& factors, u_t n, const vu_t& primes)
{
factors.clear();
for (u_t pi = 0; n > 1;)
{
for (; (n > 1) && ((n % primes[pi]) != 0); ++pi) {}
const u_t prime = primes[pi];
au2_t pe{prime, 1};
for ( n /= prime; n % prime == 0; ++pe[1], n /= prime) {}
factors.push_back(pe);
}
}
void get_divisors(vu_t& divisors, u_t n, const vu_t& primes)
{
vau2_t factors;
factor(factors, n, primes);
const u_t nf = factors.size();
vu_t powers_bounds; powers_bounds.reserve(nf);
for (const au2_t& pe: factors)
{
powers_bounds.push_back(pe[1] + 1);
}
divisors.clear();
for (vu_t powers = vu_t(nf, 0); !powers.empty();
tuple_next(powers, powers_bounds))
{
u_t d = 1;
for (u_t fi = 0; fi < nf; ++fi)
{
const u_t prime = factors[fi][0];
for (u_t power = 1; power <= powers[fi]; ++power)
{
d *= prime;
}
}
divisors.push_back(d);
}
}
#if defined(TEST_FACTOR)
#include <algorithm>
#include <iostream>
#include <cstdlib>
extern void get_primes(vu_t& primes, u_t till);
int main(int argc, char **argv)
{
int rc = 0;
u_t n_max = 2;
for (int ai = 1; ai < argc; ++ai)
{
u_t n = strtoul(argv[ai], nullptr, 0);
n_max = max(n_max, n);
}
vu_t primes;
get_primes(primes, n_max);
for (int ai = 1; ai < argc; ++ai)
{
u_t n = strtoul(argv[ai], nullptr, 0);
vau2_t factors;
vu_t divisors;
factor(factors, n, primes);
cout << n << " =";
for (const au2_t& pe: factors)
{
cout << ' ' << pe[0] << '^' << pe[1];
}
cout << "\n divisors:";
get_divisors(divisors, n, primes);
for (u_t d: divisors)
{
cout << ' ' << d;
}
cout << '\n';
}
return rc;
}
#endif /* TEST_FACTOR */
| true |
8edab021ec0f997ac1cb7d89909dd5fc57b297c5 | C++ | CTurner22/school-projects | /AlgorithmsAlgoBowlFramework/src/main.cpp | UTF-8 | 728 | 2.640625 | 3 | [] | no_license | # include "CreateInput/InputGenerator.h"
# include "ReadFiles/InputReader.h"
# include "SolutionAlgorithm/SolutionAlgorithm.h"
# include "CheckSolution/CheckSolution.h"
int main() {
/*
* We`ll obviously have to change main to accommodate the different steps that we have to do, but
* this just allows for easy testing to start with
*/
//creates a random input
inputGenerator inputCreate(1000, 500);
inputCreate.outputToFile("InputTest.txt");
// pass the input to the actual algorithm logic
solutionFinder algo("InputTest.txt");
algo.outputToFile("OutputTest.txt");
// verify the output file
verifySolution verify("InputTest.txt", "OutputTest.txt");
verify.isValid();
} | true |
a917a9a0c54170eb167b856c11741bad79f8aeae | C++ | JonathanDamiani/TurnBased_CPlusPlus | /RTSApp/Logger.cpp | UTF-8 | 3,014 | 3.59375 | 4 | [] | no_license | #include "Logger.h"
// Contructor
Logger::Logger() {};
// Change the console size
void Logger::ChangeConsoleSize(int width, int height)
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, width, height, true);
}
// Function to write a color message to the console, centred or not.
void Logger::Write(std::string text, ColorsEnum textColor)
{
// Handle to manage the colors
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE);
// Set console color using the colors enum and casting it to int
SetConsoleTextAttribute(color, static_cast<int>(textColor));
// Print the text line
std::cout << text;
// Set the color back
SetConsoleTextAttribute(color, static_cast<int>(ColorsEnum::White));
}
// Function to write a color message to the console, centred or not.
void Logger::WriteLine(std::string text, ColorsEnum textColor, bool isCentred, bool centerHeight)
{
// Handle to manage the colors
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE);
// Set console color using the colors enum and casting it to int
SetConsoleTextAttribute(color, static_cast<int>(textColor));
// If center Height is true set the heigh position of the text
if (centerHeight)
{
Logger::CenterText(text, true);
}
// Centralize string in the horizontal
if (isCentred)
{
Logger::CenterText(text);
}
// Print the text line
std::cout << text << std::endl << std::flush;
// Set the color back
SetConsoleTextAttribute(color, static_cast<int>(ColorsEnum::White));
}
// Method to add spaces to the logger
void Logger::AddSpaces(int numberOfSpaces)
{
int counter = 0;
// While to create lots of line
while (counter != numberOfSpaces)
{
std::cout << std::endl;
counter++;
}
}
// Method to center text
void Logger::CenterText(std::string str, bool centerHeight)
{
int cols;
int rows;
// Get the windows size using the address operator
Logger::GetWindowsSize(rows, cols);
// Calculate the positon of the rol the string should be when centralized
// get the number os cols less the size of the string and divide by 2
int positionCol = (int)((cols - str.length()) / 2);
// Center the text in the middle of the width
for (int i = 0; i < positionCol; i++)
{
std::cout << " ";
}
// Center the text in the middle of the height if its true
if (centerHeight)
{
// It is the same as the colums but with the rows to define the height
int positionRow = (int)((rows) / 2);
Logger::AddSpaces(positionRow);
}
}
// Method to get windows size
void Logger::GetWindowsSize(int& rRows, int& rCols)
{
// Get the current console info
CONSOLE_SCREEN_BUFFER_INFO consoleBufferInfo;
// Get the console screen buffer info function
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &consoleBufferInfo);
// Getting the number of columns and rows and pass to the parameters;
rCols = consoleBufferInfo.srWindow.Right - consoleBufferInfo.srWindow.Left;
rRows = consoleBufferInfo.srWindow.Bottom - consoleBufferInfo.srWindow.Top;
}
| true |
69257060d759ddd016e3be8852e67e1f15f94ba3 | C++ | xGreat/CppNotes | /src/algorithms/data_structures/string/str_replace_spaces.hpp | UTF-8 | 1,065 | 3.65625 | 4 | [
"MIT"
] | permissive | #ifndef STR_REPLACE_SPACES_HPP_
#define STR_REPLACE_SPACES_HPP_
// Write a method to replace all spaces in a string with '%20'. You may assume
// that the string has sufficient space at the end of the string to hold the
// additional characters, and that you are given the "true" length of the
// string.
#include <cstring>
namespace Algo::DS::String {
void ReplaceSpaces(char * const str) {
int strLength = static_cast<int>(strlen(str));
if (strLength <= 1) { return; }
int spaces = 0;
for (int i = 0; i < strLength; ++i) {
if (str[i] == ' ') {
++spaces;
}
}
int newLength = strLength + 2 * spaces;
str[newLength] = '\0';
for (int i = strLength - 1, j = newLength - 1; i >= 0; --i) {
if (str[i] == ' ') {
str[j--] = '0';
str[j--] = '2';
str[j--] = '%';
}
else {
str[j--] = str[i];
}
}
}
}
#endif /* STR_REPLACE_SPACES_HPP_ */
| true |