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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9db97fa742d7c9dbe5b3bd900b1aba2d8c26984d | C++ | pheller/libbgp | /src/bgp-sink.h | UTF-8 | 2,174 | 2.828125 | 3 | [
"MIT"
] | permissive | /**
* @file bgp-sink.h
* @author Nato Morichika <nat@nat.moe>
* @brief The BGP sink.
* @version 0.1
* @date 2019-07-05
*
* @copyright Copyright (c) 2019
*
*/
#ifndef BGP_SINK_H_
#define BGP_SINK_H_
#include <mutex>
#include <stdint.h>
#include <unistd.h>
#include "bgp-packet.h"
#include "bgp-log-handler.h"
namespace libbgp {
/**
* @brief The BgpSink class.
*
* BGP sink is a packet buffering utility for BGP. It consumes binary buffer to
* fill the sink (buffer) and allows users to get full BGP packet from the sink
* (buffer). This is useful since BGP uses TCP, and TCP streams the data. (so we
* might not get a full BGP packet in buffer every time)
*/
class BgpSink {
public:
// create a new sink
BgpSink(bool use_4b_asn);
// feed stream of packets into sink
ssize_t fill(const uint8_t *buffer, size_t len);
// get a pointer to next packet from sink (might chane if fill())
//BufferPtr pourPtr();
// get a pointer to datas in sink (might chane if fill())
//BufferPtr pourPtrAll();
// get and remove a single BGP packet from sink (max size = 4096)
//ssize_t pour(uint8_t *buffer, size_t len);
// get a packet from sink and remove that packet from sink. if no packet
// currently avaliable, 0 will be returned. if error, -2 will be returned,
// if error happend during parse but the packet object has already been
// created, -1 will be returned.
// otherwise, pkt is set to point to the new packet, and bytes drained is
// returned. (> 0)
ssize_t pour(BgpPacket **pkt);
// get and remove all packets from sink (max size = sink buffer size)
//ssize_t pourAll(uint8_t *buffer, size_t len);
// get number of bytes currently in sink
size_t getBytesInSink() const;
// discard packets in sink
void drain();
void setLogger(BgpLogHandler *logger);
~BgpSink();
private:
// settle the sink
void settle();
// exapnd the sink
void expand();
uint8_t *buffer;
size_t buffer_size;
size_t offset_start;
size_t offset_end;
bool use_4b_asn;
std::recursive_mutex mutex;
BgpLogHandler *logger;
};
}
#endif // BGP_SINK_H_ | true |
28ce21ff69354d8eb932b32764ca55d5c1a1090c | C++ | Pandinosaurus/flow_ros | /flow_ros/test/unit/publisher.cpp | UTF-8 | 2,202 | 2.671875 | 3 | [
"MIT"
] | permissive | /**
* @copyright 2020 Fetch Robotics Inc.
* @author Brian Cairl
*/
// C++ Standard Library
#include <cstdint>
#include <vector>
// GTest
#include <gtest/gtest.h>
// ROS
#include <ros/time.h>
// ROS Messages
#include <std_msgs/Header.h>
// Flow
#include <flow/flow.h>
#include <flow_ros/message_stamp_access.h>
#include <flow_ros/publisher.h>
#include <flow_ros/router.h>
/// A ROS messages-like object
struct TestMessage
{
using Ptr = std::shared_ptr<TestMessage>;
using ConstPtr = std::shared_ptr<const TestMessage>;
std_msgs::Header header;
};
TEST(PublisherLocal, Default)
{
flow_ros::Router router{"/router"};
flow_ros::Publisher<TestMessage> pub{router, "topic", 1};
EXPECT_EQ(pub.getNumSubscribers(), 0UL);
EXPECT_EQ(pub.getTransportMethod(), flow_ros::routing::TransportMethod::LOCAL);
EXPECT_EQ(pub.getTopic(), "/router/topic");
}
TEST(PublisherLocal, PublishSingleInvalid)
{
flow_ros::Router router{"/router"};
flow_ros::Publisher<TestMessage> pub{router, "topic", 1};
std::size_t counter = 0;
auto sub = router.subscribe<TestMessage>("topic", 1, [&counter](const TestMessage::ConstPtr& msg) { ++counter; });
pub.publish(TestMessage::ConstPtr{});
ASSERT_EQ(counter, 0UL);
}
TEST(PublisherLocal, PublishSingleValid)
{
flow_ros::Router router{"/router"};
flow_ros::Publisher<TestMessage> pub{router, "topic", 1};
std::size_t counter = 0;
auto sub = router.subscribe<TestMessage>("topic", 1, [&counter](const TestMessage::ConstPtr& msg) { ++counter; });
pub.publish(std::make_shared<TestMessage>());
ASSERT_EQ(counter, 1UL);
}
TEST(PublisherLocal, PublishMultiValid)
{
flow_ros::Router router{"/router"};
flow_ros::MultiPublisher<const TestMessage> pub{router, "topic", 1};
std::vector<TestMessage::ConstPtr> sub_msgs;
auto sub = router.subscribe<TestMessage>(
"topic", 1, [&sub_msgs](const TestMessage::ConstPtr& msg) { sub_msgs.emplace_back(msg); });
const std::vector<TestMessage::Ptr> pub_msgs{
std::make_shared<TestMessage>(),
std::make_shared<TestMessage>(),
std::make_shared<TestMessage>(),
};
pub.publish(pub_msgs.begin(), pub_msgs.end());
ASSERT_EQ(sub_msgs.size(), pub_msgs.size());
}
| true |
ce1aa6fdc63a9ce66eb3a43ab3e3f57d62026237 | C++ | BEN2suzuka/proconlib | /AOJ_GRL/grl_5c_2.cpp | UTF-8 | 2,505 | 3.109375 | 3 | [] | no_license | // GRL 5_C
// C++14
#include <bits/stdc++.h>
using namespace std;
// 最小共通祖先 (LCA : Lowest Common Ancestor)
// 根付き木の 2 頂点 u, v の共通祖先で最も根から遠い祖先
vector<vector<int>> G;
const int INF = 2147483647; // 2^31 - 1
// Euler Tour (DFS 木も作る)
// t := タイマー
// pre[i] := もとの頂点番号 i に対応する DFS 木の頂点番号
// ET[i] := DFS の訪問順をもつ (2*N-1 要素)
// step[i] := 頂点 i を最初に訪問するまでに何歩歩いたか
void dfs(int v, int &t, vector<int> &pre, vector<int> &ET, vector<int> &step) {
int preOrder = t;
pre.at(v) = preOrder;
t++;
step.at(pre.at(v)) = ET.size();
ET.push_back(pre.at(v));
for (auto nx : G.at(v)) {
dfs(nx, t, pre, ET, step);
ET.push_back(pre.at(v));
}
}
// A.at(i) を x に更新
void update(vector<int> &A, int i, int x, int num) {
i += num - 1; // ノード番号
A.at(i) = x;
while (i > 0) {
i = (i - 1) / 2; // 親のノードへ
A.at(i) = min(A.at(i*2 + 1), A.at(i*2 + 2));
}
}
// [a, b) の最小値を求める
// ノード番号 k は [l, r) に対応している
int query(vector<int> &A, int a, int b, int k, int l, int r) {
if (r <= a || b <= l) return INF; // [a, b) と [l, r) が交差していない
if (a <= l && r <= b) return A.at(k); // [a, b) が [l, r) を完全に含む
else {
int c1 = query(A, a, b, 2*k+1, l, (l+r)/2);
int c2 = query(A, a, b, 2*k+2, (l+r)/2, r);
return min(c1, c2);
}
}
int main() {
int N; cin >> N;
G.resize(N);
vector<int> pre(N), ET, step(N);
for (int i = 0; i < N; i++) {
int k; cin >> k;
for (int j = 0; j < k; j++) {
int c; cin >> c;
G.at(i).push_back(c);
}
}
int timer = 0;
dfs(0, timer, pre, ET, step);
vector<int> rev(N); // DFS 木の頂点番号 -> もとの頂点番号
for (int i = 0; i < N; i++) rev.at(pre.at(i)) = i;
int num = 1;
while (num < 2*N-1) num *= 2;
vector<int> A(2*num - 1, 0); // EulerTour をセグ木で管理
for (int i = 0; i < 2*N-1; i++) update(A, i, ET.at(i), num);
int Q; cin >> Q;
for (int i = 0; i < Q; i++) {
int u, v; cin >> u >> v;
if (u == v) { cout << u << endl; continue; }
u = pre.at(u); // DFS 木の頂点番号に変換
v = pre.at(v);
if (step.at(u) > step.at(v)) swap(u, v);
// LCA(i, j) は RMQ[ step[i], step[j] ) (DFS 木の頂点 i < j)
int c = query(A, step.at(u), step.at(v), 0, 0, num);
cout << rev.at(c) << endl;
}
} | true |
5b5464e523602b84eeb44f4e8b5b6e45e0eda688 | C++ | alifahrri/nmtools | /include/nmtools/meta/expr.hpp | UTF-8 | 5,733 | 2.921875 | 3 | [] | no_license | #ifndef NMTOOLS_META_EXPR_HPP
#define NMTOOLS_META_EXPR_HPP
#include "nmtools/meta/common.hpp"
#include "nmtools/meta/bits/transform/add_reference.hpp"
#include "nmtools/utility/get.hpp"
namespace nmtools::meta
{
namespace expr
{
/**
* @brief helper alias template to check if given type T has member function `at`
* taking size_types as parameters.
*
* @tparam T type to check
* @tparam size_types arguments to `at`
*/
template <typename T, typename...size_types>
using atnd = decltype(declval<T>().at(declval<size_types>()...));
/**
* @brief helper alias template to check if given type T has operator() overload
* that takes size_types as arguments.
*
* @tparam T type to check
* @tparam size_types arguments to `operator()`
*/
template <typename T, typename...size_types>
using funcnd = decltype(declval<T>().operator()(declval<size_types>()...));
/**
* @brief helper alias template to check if given type T has operator [] overload
* that takes size_types as arguments.
*
* @tparam T type to check
* @tparam size_types arguments to `operator[]`
*/
template <typename T, typename...size_types>
using bracketnd = decltype(declval<T>().operator[](declval<size_types>()...));
/**
* @brief helper alias template to check if given type T has member function `resize`
* taking size_types as parameters.
*
* @tparam T type to check
* @tparam size_types parameter(s) to `resize`
*/
template <typename T, typename...size_types>
using resizend = decltype(declval<T>().resize(declval<size_types>()...));
/**
* @brief helper alias template to deduce the return value of member function `size` of type `T`
*
* @tparam T type to check
*/
template <typename T>
using size = decltype(declval<T>().size());
/**
* @brief helper alias template to deduce the return value of member function `shape` of type `T`
*
* @tparam T type to check
*/
template <typename T>
using shape = decltype(declval<T>().shape());
/**
* @brief helper alias template to deduce the return value of member function `dim` of type `T`
*
* @tparam T type to check
*/
template <typename T>
using dim = decltype(declval<T>().dim());
/**
* @brief helper alias template to deduce the return value from index subscript `[]`.
*
* @note not to be confused with bracketnd that deduce from `operator[]` that takes variadic
* types as arguments.
*
* @tparam T type to check
* @tparam size_type argument type to index subscript `[]`
*/
template <typename T, typename size_type>
using square_bracket = decltype(declval<T>()[declval<size_type>()]);
/**
* @brief helper alias template to check if T has member type 'type'
*
* @tparam T type to check
*/
template <typename T>
using type = typename T::type;
template <typename T, typename Is, typename=void>
struct template_get_helper {};
template <typename T, auto...Is>
struct template_get_helper<T,index_sequence<Is...>,
void_t<decltype(get<Is...>(declval<T>()))>>
{
using type = decltype(get<Is...>(declval<T>()));
}; // template_get_helper
template <typename T, typename Is>
using template_get = typename template_get_helper<T,Is>::type;
} // namespace expr
namespace detail
{
/**
* @brief helper traits to check if given expression
* (provided as alias template that takes T and tparams...)
* is well-formed (calling expression<T,tparams...> results in a type).
* Roughly adapted from https://en.cppreference.com/w/cpp/experimental/is_detected
*
* @tparam always_void provided as specialization point (e.g. using void_t for true case)
* @tparam expression template template parameter take T and tparams as template arguments
* @tparam T the type to be checked
* @tparam tparams optional additional type parameters
*/
template <typename always_void, template<typename...> typename expression, typename T, typename...tparams>
struct expression_check : false_type {};
/**
* @brief specialization of expression_check traits that check if given expression
* (provided as alias template that takes T and tparams...)
* is well-formed (calling expression<T,tparams...> results in a type) for true case.
* Roughly adapted from https://en.cppreference.com/w/cpp/experimental/is_detected
*
* @tparam expression template template parameter take T and tparams as template arguments
* @tparam T the type to be checked
* @tparam tparams optional additional type parameters
*/
template <template<typename...> typename expression, typename T, typename...tparams>
struct expression_check<void_t<expression<T,tparams...>>, expression, T, tparams...> : true_type {};
} // namespace detail
template <template<typename...> typename expression, typename T, typename...tparams>
constexpr inline auto expression_check_v = detail::expression_check<void,expression,T,tparams...>::value;
} // namespace nmtools::meta
#endif // NMTOOLS_META_EXPR_HPP | true |
db4e121f596f68f200d66b07c78eec2ae4b8e3e9 | C++ | dmrudy17/Rainfall | /rainfall.cpp | UTF-8 | 772 | 3.765625 | 4 | [] | no_license | /*
rainfall.cpp
Rainfall report
*/
#include <iostream>
#include <vector>
int main() {
// input hourly rainfall data
std::vector<double> rainfall;
double n;
while (std::cin >> n) {
rainfall.push_back(n);
}
// calculate average and heaviest rainfall
double total = rainfall[0];
double max = rainfall[0];
for (int i = 1; i < rainfall.size(); ++i) {
total += rainfall[i];
if (rainfall[i] > max)
max = rainfall[i];
}
double average = total / rainfall.size();
// output rainfall report
std::cout << "Average Hourly Rainfall: " << average << " hundreds of inches" << '\n';
std::cout << "Heaviest Hourly Rainfall: " << max << " hundreds of inches" << '\n';
return 0;
}
| true |
9636b6be6ca40ee8142300af4022748afefdb9bf | C++ | JanaSabuj/Leetcode-solutions | /Apr'20/907(Sum of SubArray Minimums).cpp | UTF-8 | 1,390 | 2.6875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
const int mod = 1e9 + 7;
int n = A.size();
vector<int> g1(n), g2(n);
stack<int> s;// next smaller element
// increasing stack
for(int i = 0; i < n; i++){
while(!s.empty() and A[s.top()] > A[i]){
int x = s.top();
s.pop();
g1[x] = i;// NSE
}
s.push(i);
}
while(!s.empty()){
int x = s.top();
s.pop();
g1[x] = n;
}
// for(int i = 0; i < n; i++)
// cout << i <<
stack<int> r;
for(int i = n - 1; i >= 0; i--){
while(!r.empty() and A[r.top()] >= A[i]){
int x = r.top();
r.pop();
g2[x] = i;// PSE
}
r.push(i);
}
while(!r.empty()){
int x = r.top();
r.pop();
g2[x] = -1;
}
int ans = 0;
for(int i = 0; i < n; i++){
int k = ((g1[i] - i) * (i - g2[i]) * A[i]) % mod;
cout << k << endl;
ans += k;
ans = ans % mod;
}
return ans;
}
};
| true |
57ee74630ed4f44ccfb0e27607532efd4aa23ff6 | C++ | 20191864235/G22 | /c7/7.9/7.9.cpp | UTF-8 | 510 | 3.28125 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
void fun(char s[])
{
int len=strlen(s);
int letter=0,num=0,space=0,other=0;
for (int i=0; i<len; i++)
{
if ((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z'))
letter++;
else if (s[i]>='0'&&s[i]<='9')
num++;
else if (s[i]==' '||s[i]=='\t')
space++;
else
other++;
}
printf("Letter=%d, Number=%d, Space=%d, Ohter=%d\n", letter, num, space, other);
}
int main()
{
char s[81];
gets(s);
fun(s);
return 0;
}
| true |
9d9fae26a59346af9fcd8fbdeee47e87513c5dff | C++ | PraneshASP/COMPETITVE-PROGRAMMING | /_LEETCODE/1561.cpp | UTF-8 | 349 | 2.59375 | 3 | [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | #include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxCoins(vector<int> &piles)
{
sort(piles.begin(), piles.end());
int n = piles.size();
int i = n / 3, j = n - 2, ans = 0;
while (i--)
{
ans += piles[j];
j -= 2;
}
return ans;
}
};
| true |
bc77cffc120478d2c5c3aa1f1eb02999f44fd73c | C++ | isvelasc/CPP-How-To-Program | /Ch 5/5_16_Mod_Compound_Interest.cpp | UTF-8 | 582 | 3.28125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <cmath>
int main() {
int amount;
int principal = 1000 * 100;
double rate = 1.05;
std::cout << "Year" << std::setw( 21 ) << "Amount on deposit" << std::endl;
std::cout << std::fixed << std::setprecision( 2 );
for (unsigned int year = 1; year <= 10; ++year) {
amount = principal * pow(rate, year);
int dollars = amount / 100;
amount %= 100;
int pennies = amount;
std::cout << std::setw( 4 ) << year << std::setw( 21 ) << dollars << "." << pennies << std::endl;
}
return 0;
}
| true |
5a0fcbfabd4c4042f5eee05b7ed9919c90c8a8f3 | C++ | doug0102/GAM1514FinalProject | /Source/Common/Game/Enemy.h | UTF-8 | 399 | 2.671875 | 3 | [] | no_license | #include "Player.h"
class Enemy : public Player
{
public:
Enemy(Level* level, float speed);
virtual ~Enemy();
const char* getType();
void update(double delta);
void paint();
void reset();
void fireProjectile(float x, float y);
void slowEnemy(double length, float power);
protected:
void handlePlayerCollision(Projectile* projectile);
double m_SlowTimer;
double m_PreviousSpeed;
}; | true |
5c9b13f37a9b951da2fd1f1294ee1b52f84161ec | C++ | lvsszz/suan_fa_jing_sai_bao_dian | /chapter3/1_freopen.cpp | UTF-8 | 426 | 3 | 3 | [] | no_license | //freopen方式读写文件
#include <iostream>
#include <cstdlib>//此行必加,否则linux下可能出问题
using namespace std;
int main()
{
int a,b;
freopen("sum.in","r",stdin); //从sum.in中读取数据 https://www.cplusplus.com/reference/cstdio/freopen/
freopen("sum.out","w",stdout);//输出到sum.out文件
cin>>a>>b;
cout<<a+b<<endl;
//system("pause"); 一定要将此句注释掉
return 0;
}
| true |
33bf8e5256260c2d8a7944dccfc3435b8da87ca5 | C++ | zackdlut/designpattern | /factoryMethod/src/Log.h | UTF-8 | 298 | 3.015625 | 3 | [] | no_license | #ifndef _LOG_H_
#define _LOG_H_
#include<iostream>
class Log
{
public:
Log();
virtual ~Log();
virtual void writeLog(std::string log) = 0;
};
Log::Log()
{
std::cout<<"Construct Base Log"<<std::endl;
}
Log::~Log()
{
std::cout<<"Destruct Base Log"<<std::endl;
}
#endif //_LOG_H_ | true |
3c3353bf7b764c1c5ed269680a8c6e31fbe27470 | C++ | rstms/splishsplash | /splish/AudioCapturer.h | UTF-8 | 1,132 | 2.640625 | 3 | [
"MIT"
] | permissive | #pragma once
/// Responsible for launching a thread that continually captures the audio output and makes
/// it available in a cyclic buffer. An event is raised every time new audio data is
/// available.
class AudioCapturer
{
public:
AudioCapturer(int bufferSizeInSeconds, int latencyInMilliseconds);
~AudioCapturer(void);
HRESULT Initialize(void);
HRESULT Start(void);
HRESULT Stop(void);
BYTE *GetBuffer() const;
UINT32 GetBufferSize() const;
UINT32 GetBufferPosition() const;
HANDLE GetAudioCapturedEvent() const;
private:
static const int TargetFrameSize = 8; // 2 channels at 32 bits per sample.
int _latencyInMilliseconds;
UINT32 _bufferSize;
BYTE *_buffer;
UINT32 _bufferIndex;
HANDLE _audioCapturedEvent;
CComPtr<IAudioClient> _audioClient;
CComPtr<IAudioCaptureClient> _captureClient;
WAVEFORMATEX *_pWaveFormat;
HANDLE _captureThread;
volatile bool _shutDown;
// helpers
HRESULT GetDefaultRenderDevice(IMMDevice **device);
static DWORD __stdcall CaptureThreadStart(LPVOID Context);
HRESULT CaptureThread(void);
};
| true |
1aa3aa4092c832889dba67d184a3bd68fa3655a7 | C++ | MIDAS2020/Midas | /ClusterMaintenance/misc.h | UTF-8 | 955 | 2.640625 | 3 | [] | no_license | #pragma once
using namespace std;
#ifndef MISC_H
#define MISC_H
const bool POPULATE_CHECK = false;
const short ENDOFTREETAG = 3002;
const short ENDTAG = 3001;
const short INFINITY_SHORT = 3003; //a number greater than any short
const long INFINITY_LONG = 2000000000; //a number greater than any long
extern long SUPPORT_THRESHOLD;
//as a result, the maximal number of vertices in a tree is 3000
class FreeTree;
typedef FreeTree* ptrFreeTree;
struct Edge
{
short vertex1; //one end of the edge
short vertex2; //the other end of the edge
short eLabel; //the label of the edge
Edge(short v = 0, short w = 0, short eLabel = 0) :
vertex1(v), vertex2(w), eLabel(eLabel) { }
Edge(const Edge& rhs) { vertex1 = rhs.vertex1; vertex2 = rhs.vertex2; eLabel = rhs.eLabel; }
Edge& operator=(const Edge& rhs)
{
vertex1 = rhs.vertex1; vertex2 = rhs.vertex2; eLabel = rhs.eLabel; return *this;
}
};
#endif //MISC_H
| true |
503730a3880a462748b334bfd39ac2a3bef08936 | C++ | Gaspard--/Kontext_kompiler | /include/Stack.hpp | UTF-8 | 437 | 3.140625 | 3 | [] | no_license | #pragma once
#include <memory>
#include <deque>
#include "Value.hpp"
class Stack : public std::deque<std::unique_ptr<Value>>
{
public:
Stack() = default;
Stack(Stack const &) = delete;
Stack(Stack &&) = delete;
~Stack() = default;
/// I didn't find anything about stack resize destrcution order so using pop instead
void unwind(Value *until)
{
while (back().get() != until)
pop_back();
pop_back();
}
};
| true |
b9a7f334ceaa54a6289948db0dbd003914ff8c61 | C++ | goodfella/libndgpp | /include/libndgpp/bounded_integer.hpp | UTF-8 | 20,812 | 3.28125 | 3 | [
"MIT"
] | permissive | #ifndef LIBNDGPP_BOUNDED_INTEGER_HPP
#define LIBNDGPP_BOUNDED_INTEGER_HPP
#include <cstdint>
#include <cstring>
#include <functional>
#include <limits>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <libndgpp/error.hpp>
#include <libndgpp/safe_operators.hpp>
#include <libndgpp/strto.hpp>
namespace ndgpp
{
struct bounded_integer_error: public std::invalid_argument
{
bounded_integer_error(const char * what):
std::invalid_argument(what)
{}
};
struct bounded_integer_underflow final: public bounded_integer_error
{
bounded_integer_underflow():
bounded_integer_error("ndgpp::bounded_integer underflow")
{}
};
struct bounded_integer_overflow final: public bounded_integer_error
{
bounded_integer_overflow():
bounded_integer_error("ndgpp::bounded_integer overflow")
{}
};
struct bounded_integer_invalid final: public bounded_integer_error
{
bounded_integer_invalid():
bounded_integer_error("ndgpp::bounded_integer invalid value")
{}
};
struct bounded_integer_min_t {};
constexpr bounded_integer_min_t bounded_integer_min {};
struct bounded_integer_max_t {};
constexpr bounded_integer_max_t bounded_integer_max {};
/** An integer type that has a bounded value range
*
* @tparam T The underlying integer type
*
* @tparam Min The minimal value this type is allowed to
* represent. Defaults to
* std::numeric_limits<T>::min()
*
* @tparam Max The maximum value this type is allowed to
* represent. Defaults to
* std::numeric_limits<T>::max()
*
* @tparam Tag Allows for differentiating between two
* bounded_integer types with the same ranges.
*/
template <class T,
T Min = std::numeric_limits<T>::min(),
T Max = std::numeric_limits<T>::max(),
class Tag = void>
class bounded_integer final
{
public:
static_assert(std::is_integral<T>::value, "T must be a integral type");
/// The underlying integer type
using value_type = std::decay_t<T>;
/// The tag type
using tag_type = Tag;
/// Returns the minimum value this bounded_integer can represent
static constexpr value_type min() noexcept {return Min;}
/// Returns the maximum value this bounded_integer can represent
static constexpr value_type max() noexcept {return Max;}
/// Constructs a bounded integer assigned to the minimum allowed value
constexpr bounded_integer() noexcept;
/// Constructs a bounded integer assigned to the minimum allowed value
constexpr bounded_integer (bounded_integer_min_t) noexcept;
/// Constructs a bounded integer assigned to the maximum allowed value
constexpr bounded_integer (bounded_integer_max_t) noexcept;
/** Constructs a bounded_integer given a compile time constant
*
* @tparam U The constant's integral type
* @tparam Val The constant's value
*
* @param v The std::integral_constant instance
*/
template <class U, U Val>
constexpr bounded_integer(std::integral_constant<U, Val> v) noexcept;
/** Constructs a bounded_integer
*
* @param value The value to assign the bounded_integer to
*/
template <class U>
bounded_integer(const U value);
/** Constructs a bounded integer from a C string
*
* @tparam DelimIter The delimiter iterator type
*
* @param str The value represented as a string
* @param pos The offset in the string to start parsing for a value
* @param base The base to use for the conversion see std::strtoul
* @param first The first element in the iterator range
* @param last The last element in the iterator range
*/
template <class DelimIter>
explicit
bounded_integer(char const * const str,
const std::size_t pos,
const int base,
const DelimIter begin,
const DelimIter end);
/** Constructs a bounded integer from a C string
*
* @param str The value represented as a string
* @param pos The offset in the string to start parsing for a value
* @param base The base to use for the conversion see std::strtoul
* @param delimiters A string containing the set of delimiters
*/
explicit
bounded_integer(char const * const str,
const std::size_t pos = 0,
const int base = 0,
char const * const delimiters = "");
/** Constructs a bounded integer from a std::string
*
* @tparam DelimIter The delimiter iterator type
*
* @param str The value represented as string
* @param pos The offset in the string to start parsing for a value
* @param base The base to use for the conversion see std::strtoul
* @param first The first element in the iterator range
* @param last The last element in the iterator range
*/
template <class DelimIter>
explicit
bounded_integer(const std::string& str,
const std::size_t pos,
const int base,
const DelimIter begin,
const DelimIter end);
/** Constructs a bounded integer from a std::string
*
* @param str The value represented as a string
* @param pos The offset in the string to start parsing for a value
* @param base The base to use for the conversion see std::strtoul
* @param delimiters A string containing the set of delimiters
*/
explicit
bounded_integer(const std::string& str,
const std::size_t pos = 0,
const int base = 0,
char const * const delimiters = "");
bounded_integer(const bounded_integer&) noexcept;
bounded_integer& operator=(const bounded_integer&) noexcept;
bounded_integer(bounded_integer&&) noexcept;
bounded_integer& operator=( bounded_integer&&) noexcept;
/// Assigns the integer to the integral value
template <class U>
bounded_integer & operator=(const U value);
/// Assigns the integer to the value represented in the std::string
bounded_integer & operator=(const std::string & value);
/// Assigns the integer to the value represented in the C string
bounded_integer & operator=(char const * const value);
/// Assigns the integer to the integral constant
template <class U, U Val>
bounded_integer & operator=(const std::integral_constant<U, Val>) noexcept;
/// Assigns the integer to its maximum allowed value
bounded_integer & operator=(bounded_integer_max_t) noexcept;
/// Assigns the integer to its minimum allowed value
bounded_integer & operator=(bounded_integer_min_t) noexcept;
/// Returns the underlying value
constexpr value_type value() const noexcept;
/// Swaps two bounded_integer values
void swap(bounded_integer& other) noexcept;
private:
value_type value_ = Min;
};
template <class T, T Min, T Max, class Tag>
constexpr bounded_integer<T, Min, Max, Tag>::bounded_integer() noexcept = default;
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>::bounded_integer(const bounded_integer&) noexcept = default;
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>&
bounded_integer<T, Min, Max, Tag>::bounded_integer::operator=(const bounded_integer&) noexcept = default;
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>::bounded_integer::bounded_integer(bounded_integer&&) noexcept = default;
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>&
bounded_integer<T, Min, Max, Tag>::bounded_integer::operator=(bounded_integer&&) noexcept = default;
template <class T, T Min, T Max, class Tag>
constexpr bounded_integer<T, Min, Max, Tag>::bounded_integer(bounded_integer_min_t) noexcept:
value_(Min)
{}
template <class T, T Min, T Max, class Tag>
constexpr bounded_integer<T, Min, Max, Tag>::bounded_integer(bounded_integer_max_t) noexcept:
value_(Max)
{}
template <class T, T Min, T Max, class Tag>
template <class U, U Val>
constexpr bounded_integer<T, Min, Max, Tag>::bounded_integer(std::integral_constant<U, Val>) noexcept:
value_(Val)
{
static_assert(Val >= Min && Val <= Max,
"integral constant out of bounded_integer range");
}
template <class T, T Min, T Max, class Tag>
template <class U>
bounded_integer<T, Min, Max, Tag>::bounded_integer(const U value)
{
if (ndgpp::safe_op::lt(value, Min))
{
throw ndgpp::error<bounded_integer_underflow>(ndgpp_source_location);
}
else if (ndgpp::safe_op::gt(value, Max))
{
throw ndgpp::error<bounded_integer_overflow>(ndgpp_source_location);
}
value_ = value;
}
template <class T, T Min, T Max, class Tag>
template <class DelimIter>
bounded_integer<T, Min, Max, Tag>::bounded_integer(char const * const str,
const std::size_t pos,
const int base,
const DelimIter begin,
const DelimIter end)
{
const ndgpp::strto_result<value_type> result =
ndgpp::strtoi<value_type, DelimIter, Min, Max>(str + pos, base, begin, end);
if (result)
{
value_ = result.value();
return;
}
if (result.overflow())
{
throw ndgpp::error<bounded_integer_overflow>(ndgpp_source_location);
}
if (result.underflow())
{
throw ndgpp::error<bounded_integer_underflow>(ndgpp_source_location);
}
if (result.invalid())
{
throw ndgpp::error<bounded_integer_invalid>(ndgpp_source_location);
}
}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>::bounded_integer(char const * const str,
const std::size_t pos,
const int base,
char const * const delimiters):
bounded_integer(str, pos, base, delimiters, delimiters + std::strlen(delimiters))
{}
template <class T, T Min, T Max, class Tag>
template <class DelimIter>
bounded_integer<T, Min, Max, Tag>::bounded_integer(const std::string& str,
const std::size_t pos,
const int base,
const DelimIter begin,
const DelimIter end):
bounded_integer(str.c_str(), pos, base, begin, end)
{}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>::bounded_integer(const std::string& str,
const std::size_t pos,
const int base,
char const * const delimiters):
bounded_integer(str.c_str(), pos, base, delimiters, delimiters + std::strlen(delimiters))
{}
template <class T, T Min, T Max, class Tag>
template <class U>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(const U value)
{
if (ndgpp::safe_op::lt(value, Min))
{
throw ndgpp::error<bounded_integer_underflow>(ndgpp_source_location);
}
else if (ndgpp::safe_op::gt(value, Max))
{
throw ndgpp::error<bounded_integer_overflow>(ndgpp_source_location);
}
this->value_ = value;
return *this;
}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(const std::string& value)
{
const ndgpp::strto_result<value_type> result =
ndgpp::strtoi<value_type, Min, Max>(value.c_str());
if (result)
{
value_ = result.value();
return *this;
}
if (result.overflow())
{
throw ndgpp::error<bounded_integer_overflow>(ndgpp_source_location);
}
if (result.underflow())
{
throw ndgpp::error<bounded_integer_underflow>(ndgpp_source_location);
}
if (result.invalid())
{
throw ndgpp::error<bounded_integer_invalid>(ndgpp_source_location);
}
return *this;
}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(char const * const value)
{
const ndgpp::strto_result<value_type> result =
ndgpp::strtoi<value_type, Min, Max>(value);
if (result)
{
value_ = result.value();
return *this;
}
if (result.overflow())
{
throw ndgpp::error<bounded_integer_overflow>(ndgpp_source_location);
}
if (result.underflow())
{
throw ndgpp::error<bounded_integer_underflow>(ndgpp_source_location);
}
if (result.invalid())
{
throw ndgpp::error<bounded_integer_invalid>(ndgpp_source_location);
}
return *this;
}
template <class T, T Min, T Max, class Tag>
template <class U, U Val>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(std::integral_constant<U, Val>) noexcept
{
static_assert(Val >= Min, "Val is less than Min");
static_assert(Val <= Max, "Val is less than Min");
this->value_ = Val;
return *this;
}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(bounded_integer_max_t) noexcept
{
this->value_ = Max;
return *this;
}
template <class T, T Min, T Max, class Tag>
bounded_integer<T, Min, Max, Tag>& bounded_integer<T, Min, Max, Tag>::operator=(bounded_integer_min_t) noexcept
{
this->value_ = Min;
return *this;
}
template <class T, T Min, T Max, class Tag>
inline constexpr std::decay_t<T> bounded_integer<T, Min, Max, Tag>::value() const noexcept
{
return this->value_;
}
template <class T, T Min, T Max, class Tag>
inline void bounded_integer<T, Min, Max, Tag>::swap(bounded_integer& other) noexcept
{
std::swap(this->value_, other.value_);
}
template <class T, T Min, T Max, class Tag>
inline bool operator < (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return lhs.value() < rhs.value();
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator < (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return ndgpp::safe_op::lt(lhs.value(), rhs);
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator < (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::lt(lhs, rhs.value());
}
template <class T, T Min, T Max, class Tag>
inline bool operator == (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return lhs.value() == rhs.value();
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator == (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return lhs.value() == rhs;
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator == (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return lhs == rhs.value();
}
template <class T, T Min, T Max, class Tag>
inline bool operator != (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return lhs.value() != rhs.value();
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator != (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return lhs.value() != rhs;
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator != (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return lhs != rhs.value();
}
template <class T, T Min, T Max, class Tag>
inline bool operator > (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::gt(lhs.value(), rhs.value());
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator > (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return ndgpp::safe_op::gt(lhs.value(), rhs);
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator > (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::gt(lhs, rhs.value());
}
template <class T, T Min, T Max, class Tag>
inline bool operator >= (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::gte(lhs.value(), rhs.value());
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator >= (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return ndgpp::safe_op::gte(lhs.value(), rhs);
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator >= (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::gte(lhs, rhs.value());
}
template <class T, T Min, T Max, class Tag>
inline bool operator <= (const bounded_integer<T, Min, Max, Tag> lhs,
const bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::lte(lhs.value(), rhs.value());
}
template <class T, T Min, T Max, class Tag, class U>
inline bool operator <= (const bounded_integer<T, Min, Max, Tag> lhs,
const U rhs) noexcept
{
return ndgpp::safe_op::lte(lhs.value(), rhs);
}
template <class U, class T, T Min, T Max, class Tag>
inline bool operator <= (const U lhs,
bounded_integer<T, Min, Max, Tag> rhs) noexcept
{
return ndgpp::safe_op::lte(lhs, rhs.value());
}
template <class T, T Min, T Max, class Tag>
std::ostream& operator << (std::ostream& out, const bounded_integer<T, Min, Max, Tag> rhs)
{
out << rhs.value();
return out;
}
}
namespace std
{
template <class T, T Min, T Max, class Tag>
struct hash<ndgpp::bounded_integer<T, Min, Max, Tag>> final
{
using bounded_integer_type = ndgpp::bounded_integer<T, Min, Max, Tag>;
using argument_type = bounded_integer_type;
using result_type = typename std::hash<T>::result_type;
result_type operator() (argument_type val) const noexcept
{
return hasher(val.value());
}
std::hash<T> hasher;
};
}
#endif
| true |
565586403124982918f8c960e2126dd3e716df75 | C++ | Arkozak/New-Repo | /Homework 4/tokenizer.cpp | UTF-8 | 485 | 3.046875 | 3 | [] | no_license |
#include "tokenizer.hpp"
int main()
{
vector<string> tokens;
string str;
int x = 0;
cout << "Please enter some text.";
cout << " To end type end." << endl;
while (str != "end" && str != "END" && str != "End") //Grabing inputs
{
if (ReadLine(str) == true)
{
tokens.push_back(str);
tokens.push_back("");
}
}
x = StringToTokensWS(tokens); //Fixing vector to seperate everything
AnalyzeTokens(tokens); //outputing everything and identifying stuff
return 0;
} | true |
cb9e901f77dc6305ad1374da4b949966451b6a84 | C++ | rahulbeeram12/ABC_Assignments | /Assignment 2/q7.cpp | UTF-8 | 281 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
int min = a;
if (b < min) min = b;
if (c < min) min = c;
//another approach using ternary operator
// min = c < (a < b ? a : b) ? c : (a < b ? a : b);
cout << min << "\n";
return 0;
} | true |
df2b636f4da43961c7dc1d40d30c28f532b84bd3 | C++ | heavy3/stanforg-cs106b | /w3/permutation/src/permutation.cpp | UTF-8 | 1,140 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include "simpio.h"
#include "stack.h"
#include "console.h"
#include "lexicon.h"
#include "filelib.h"
using namespace std;
void intro();
void permute(string s);
void permute(string sofar, string remain);
Lexicon english;
int main() {
intro();
english = Lexicon("dictionary.txt");
string word;
do {
word = getLine("Enter a set of letter (blank to quit): ");
permute(word);
} while (word != ""); // in evaluate also has the same condition, but we pass by value :)
return 0;
}
void intro() {
cout << "A program to print all valid permutation for a set of letter" << endl;
}
void permute(string s) {
permute("", s);
}
void permute(string sofar, string remain) {
if (remain == "") {
if (english.contains(sofar)) {
cout << sofar << endl;
}
}
else {
for (int i = 0, len = remain.length(); i < len; i++) {
// get a random letter from set and add it to remain
string remaining = remain.substr(0, i) + remain.substr(i+1);
permute(sofar + remain[i], remaining);
}
}
}
| true |
c5891e3baeb77b162e60091b4a36d3969a8c9059 | C++ | tianjun-love/HelloWorld | /DateTime/include/Date.hpp | UTF-8 | 951 | 2.9375 | 3 | [] | no_license | /*******************************************
功能:日期处理类
作者:田俊
时间:2019-05-22
修改:
*******************************************/
#ifndef __DATE_HPP__
#define __DATE_HPP__
#include "DateTime.hpp"
class CDate : public CDateTime
{
public:
CDate();
CDate(unsigned int iYear, unsigned int iMon, unsigned int iDay);
CDate(const std::string &szDate);
CDate(time_t lSeconds);
CDate(const CDateTime &DateTime);
CDate(const CDate &Other);
virtual ~CDate();
CDate &operator=(const CDate &Other);
CDate &operator=(const std::string &szDate);
CDate &operator=(time_t lSeconds);
CDate &operator=(const CDateTime &DateTime);
operator std::string() const;
void InitCurrDate(time_t lSecond = 0);
private:
void CopyFromDate(const std::string &szDate);
void CopyFromDateTime(const CDateTime &Other);
void truncateTime(time_t &tDateTime);
};
std::ostream& operator<<(std::ostream &out, const CDate& Date);
#endif | true |
b6f746fd451bc481300a3654bfdd1f398e86b50c | C++ | ValKmjolnir/NUAA-CCST-Data-Structure | /exp8-src/quick_sort.cpp | UTF-8 | 688 | 3.15625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
int num[1024];
void init()
{
std::srand(unsigned(std::time(NULL)));
for(int i=0;i<1024;++i)
num[i]=rand()%1024;
return;
}
void quick_sort(int begin,int end)
{
int i=begin;
int j=end;
if(i<j)
{
int mid=num[(begin+end)>>1];
while(i<=j)
{
while(num[j]>mid)--j;
while(num[i]<mid)++i;
if(i<=j)
{
int t=num[i];
num[i]=num[j];
num[j]=t;
++i;
--j;
}
}
quick_sort(begin,j);
quick_sort(i,end);
}
return;
}
int main()
{
init();
quick_sort(0,1023);
for(int i=0;i<1024;++i)
std::cout<<num[i]<<" ";
return 0;
}
| true |
4bdce010665dbf0fdb99caac41c2285a23e4289b | C++ | prashrock/CPP | /string/substring.h | UTF-8 | 11,276 | 3.28125 | 3 | [
"MIT"
] | permissive | #ifndef _SUBSTRING_UTILS_CPP_
#define _SUBSTRING_UTILS_CPP_
/**
* @file Substring
* @brief Substring functions
*/
#include <vector> /* std:vector */
#include <algorithm> /* std::max */
#include "hash_fns.h" /* rolling_hash() */
/**
* Naive Substring method: *
* @param text *
* Text in which to search for pattern (haystack) *
* @param pat *
* Pattern to search for (needle) *
* @return *
* 0-based pattern start idx or -1 if pattern not found *
* For every position in text, consider it as a starting *
* position for pattern and see if there is a match. *
* Best for : Short text and pattern *
* Worst Case Time Complexity = O(NM) (Typical = O(1.1N)) *
* Space Complexity = O(1) */
template<typename T=std::string>
static inline int substring_brute(T text, T pat) {
if(text.empty() || pat.empty()) return -1;
for(size_t i = 0, j = 0; i <= (text.size() - pat.size()); ++i) {
for(j = 0; j < pat.size() && i + j < text.size(); ++j)
if(text[i + j] != pat[j]) break;
if(j == pat.size()) return i; /* Return on 1st match */
}
return -1;
}
/**
* Optimized Naive method: *
* @param text *
* Text in which to search for pattern (haystack) *
* @param pat *
* Pattern to search for (needle) *
* @return *
* 0-based pattern start idx or -1 if pattern not found *
* Use one for-loop to iterate over the text and backup text *
* explicitly everytime there is a mismatch (rewind pattern *
* as well). *
* Best for : Short text and pattern *
* Worst Case Time Complexity = O(NM) (Typical = O(1.1N)) *
* Space Complexity = O(1) */
template<typename T=std::string>
static inline int substring_opt(T text, T pat)
{
size_t i, j;
if(text.empty() || pat.empty()) return -1;
/* Break loop when either text or pat is fully traversed */
for(i = 0, j = 0; i < text.size() && j < pat.size(); ++i) {
if(text[i] == pat[j]) j++;
/* if mismatch, backtrack text by j and reset pat */
else {
i -= j;
j = 0;
}
}
if(j == pat.size()) return (i - pat.size());
else return -1;
}
/**
* Knuth Morris Pratt Discrete Finite State Machine Algo: *
* @param pat *
* Pattern to search for (needle) *
* @param lps *
* Int arr = Longest Proper Prefix which is also a suffix *
* @param n *
* Pattern length *
* @return *
* 0 on success and -1 on failure *
* DFA preprocessing involves constructing an auxiliary array*
* lps[pattern_size]. For each sub-pattern pat[0 - i] where *
* i = 0 to m-1: *
* lps[i] = ln of longest matching proper prefix which is *
* also a suffix of the sub-pattern pat[0..i]. *
* There are three cases handled below: *
* Case 1 : Match *
* - If cur prefix and i'th char match, lps_len++ and i++ *
* Case 2 : No Match + LPS length == 0 *
* - LPS empty and pat[i] != pat[0], lps[i] = 0 and i++ *
* Case 3 : No Match + LPS length != 0 *
* - lps_len > 0 && pat[i] != pat[0], point lps_len to prev *
* lps char (lps_len = lps[lps_len - 1] && don't increment i *
* i.e., stay in case 3, till lps_len = 0 (i.e., case 2) */
template<typename T=std::string>
static inline int kmp_prefix_dfa(T pat, int lps[], int n) {
/* length of previous longest prefix that is also suffix */
int lps_len = 0;
lps[0] = 0; /* single char string = no proper prefix */
for(int i = 1; i < n;) {
/* Case 1: Cur Prefix and the ith char match, move fwd */
if(pat[lps_len] == pat[i]) lps[i++] = ++lps_len;
/* Case 2: No match and the lps_length is 0, move fwd */
else if(lps_len == 0) lps[i++] = 0;
/* Case 3: No match and lps_length is non-zero (stay) */
else lps_len = lps[lps_len - 1];
}
return 0;
}
/* Dump the pattern string and LPS table from a pattern str */
void kmp_lps_dump_helper(const std::string pattern_str) {
const int N = pattern_str.size();
std::vector<char> pat(pattern_str.begin(), pattern_str.end());
std::vector<int> val(N, 0);
print_table_row<char>("pattern", pat);
kmp_prefix_dfa(pattern_str, &val[0], N);
print_table_row<int>("KMP Result", val);
}
/**
* Knuth Morris Pratt Search Algo: *
* @param text *
* Text in which to search for pattern (haystack) *
* @param pat *
* Pattern to search for (needle) *
* @return *
* 0-based pattern start idx or -1 if pattern not found *
* Build pattern prefix table - Longest proper prefix which *
* is also a suffix *
* Best for : Long text + Pattern with small radix and lot *
* of repetitions (example: DNA sequence) *
* Worst Case Time Complexity = O(3N) (Typical = O(1.1N)) *
* Space Complexity = O(M) *
* Advantages: *
* - No text backtrack needed (supports input text stream) */
template<typename T=std::string>
static inline int substring_kmp(T text, T pat) {
size_t M = pat.size();
/* LPS = store the DFA result of longest prefix match */
std::vector<int> lps(M);
size_t i, j;
if(text.empty() || pat.empty()) return -1;
kmp_prefix_dfa(pat, &lps[0], M);
for(i = 0, j = 0; i < text.size() && j < M; ++i) {
/* Backtrack pat if required but not the text */
while (j > 0 && text[i] != pat[j])
j = lps[j - 1];
if(text[i] == pat[j]) j++;
}
if(j == M) return (i - M);
else return -1;
}
/**
* Boyer-Moore Substring Match Algo: *
* @param text *
* Text in which to search for pattern (haystack) *
* @param pattern *
* Pattern to search for (needle) *
* @return *
* 0-based pattern start idx or -1 if pattern not found *
* Scan pattern chars from right to left. Skip as many as M *
* text chars when finding one not in the pattern *
* Best for :Long pattern resembling natural text(eg:English)*
* Worst Case Time Complexity = O(MN) (Typical = O(N/M)) *
* Space Complexity = O(R) where R = Radix *
* Note - below impl assumes Radix is 256 (Extended ASCII *
* char sequence). *
* Note - GNU grep uses Boyer Moore with unrolled inner loop *
* Note2- Implementation based on Robert Sedgewick lectures@ *
* algs4.cs.princeton.edu/lectures/53SubstringSearch.pdf */
template<typename T=std::string, size_t R=256>
static inline int substring_boyer_moore(T text, T pat) {
const auto N = text.size(), M = pat.size();
if(text.empty() || pat.empty()) return -1;
std::vector<int> radix(R, -1);
/* Pre-processing - pre-compute the rightmost occurence *
* of each character 'c' in the pattern */
for(size_t i = 0; i < M; ++i) {
unsigned pos = static_cast<char>(pat[i]);
radix[pos] = i; /*Only store last occur of character */
}
/* Actual Boyer-Moore String Search Algorithm */
int skip = 0; /* How many char to skip matching in text */
/* Use condition <= to facilitate text == pattern case */
for(size_t i = 0; i <= (N - M); i += skip) {
skip = 0;
for(int j = M - 1; j >= 0; j--) {
if(text[i+j] != pat[j]) {
skip = std::max(1, j - radix[pat[j]]);
break;
}
}
if(skip == 0) return i;
}
return -1;
}
/**
* Rabin-Karp Substring Match Algo(Monte-Carlo approach): *
* @param text *
* Text in which to search for pattern (haystack) *
* @param pattern *
* Pattern to search for (needle) *
* @return *
* 0-based pattern start idx or -1 if pattern not found *
* Modular Hashing approach. Compute hash of pattern[0, M-1] *
* For each i, compute hash of text[i, M+i-1]. *
* If pattern_hash==text_substring_hash --> potential match. *
* With Monte-Carlo approach, no validation done, i.e., *
* potential match substrings are not compared (validated), *
* just assume very low probability of hash collision, i.e., *
* (tolerate false-positives) *
* Worst Case Time Complexity = O(7N) (Typical = O(7N)) *
* Space Complexity = O(1) */
template<typename T=std::string, size_t R=256,
unsigned long prime=5915587277>
static inline int substring_rabin_karp(T text, T pattern) {
if(text.empty() || pattern.empty()) return -1;
size_t M = pattern.size();
unsigned long RM1 = 1; /* R^(M-1) % prime */
unsigned long pattern_hash = rolling_hash(pattern, R, prime);
unsigned long hash = rolling_hash(text.substr(0, M), R, prime);
/* Precompute R^(M-1) % prime */
for(size_t i = 1; i < M; ++i)
RM1 = (R * RM1) % prime;
/* Actual Rabin-Karp String Search Algorithm */
if(pattern_hash == hash) return 0; /* Full/1st match */
for(size_t i = M; i < text.size(); ++i) {
/* Remove left-most character from rolling hash */
hash = (hash + prime - (RM1 * text[i-M] % prime)) % prime;
/* Add right-most character to the rolling hash */
hash = ((hash * R) + text[i]) % prime;
/* Monte-Carlo version. Don't verify substrings */
if(pattern_hash == hash)
return (i - M + 1);
}
return -1;
}
template<typename T=std::string>
static inline int substring_stil_find(T text, T pat) {
if(text.empty() || pat.empty()) return -1;
auto ret = text.find(pat);
if(ret == std::string::npos) return -1;
else return static_cast<int> (ret);
}
#endif //_SUBSTRING_UTILS_CPP_
| true |
b6d1c2ff952048f5c25a198935cac61a547c2ad5 | C++ | Nexarian/Coverage-Finder | /Multi-Threaded Coverage Finder/Path.cpp | UTF-8 | 5,997 | 2.78125 | 3 | [] | no_license | #include "StdAfx.h"
#include "Path.h"
#include <fstream>
Path::Path(void)
{
}
Path::~Path(void)
{
ClearData();
}
void Path::SavePathVectors(const char* FileName) const {
std::ofstream OutputFile(FileName);
//each of these is a vector
for (std::list< std::pair<POINT, POINT> >::const_iterator VectIt = LastPathVectors.begin(); VectIt != LastPathVectors.end(); ++VectIt) {
OutputFile << GeometricObject::Range(VectIt->first, VectIt->second) << " " << atan2((double)VectIt->first.y - VectIt->second.y, (double)VectIt->second.x - VectIt->first.x) << std::endl;
}
OutputFile.close();
}
void Path::ReadData(FileStream& File) {
ClearData();
}
void Path::WriteData(FileStream& File) const {
}
bool Path::PointIntersect(POINT ThePoint, RECT TheRect) {
return (ThePoint.x >= TheRect.left && ThePoint.x <= TheRect.right) && (ThePoint.y >= TheRect.top && ThePoint.y <= TheRect.bottom);
}
void Path::DrawPath(const PointAr& PathToDraw, const HDC DestDC, const COLORREF Color, const int DrawSpeed) const {
GeometricObject::ResetDrawCounter();
for (PointArCItr VectIt = PathToDraw.begin(); VectIt != PathToDraw.end(); ++VectIt) {
GeometricObject::DrawFilibuster();
SetPixel(DestDC, VectIt->x, VectIt->y, Color);
}
}
PointAr Path::GeneratePath(POINT StartLocation, POINT EndLocation) {
PointAr ReturnPath;
ReturnPath.clear();
LastPathVectors.clear();
ShortestPath.ResetData();
//prevent a 0-length path from being returned
if (StartLocation == EndLocation) {
ReturnPath.push_back(StartLocation);
PathsGenerated.push_back(ReturnPath);
return ReturnPath;
}
GetArea()->MakeProbeOK();
//update the class records
StartPoint = StartLocation;
EndPoint = EndLocation;
MappedLine OrgLine(StartLocation, EndLocation);
for (MappedPointPtrArItr VertexLoop = GetArea()->Vertices.begin(); VertexLoop != GetArea()->Vertices.end(); ++VertexLoop) {
(*VertexLoop)->Range = OrgLine.PerpDist((*VertexLoop)->PointPart);
}
//the dummy path
PathDescriptor DummyPath;
DummyPath.TotalDistance = 0;
//add in the ending point
MappedPoint DummyEnd;
DummyEnd.PointPart = EndLocation;
DummyEnd.IsVertex = true;
//this mutilates the vertices for path-finding purposes
GetArea()->FillInLegalNodes(DummyEnd, GetArea()->Vertices, false, false, true);
//add in the starting point
MappedPoint DummyStart;
DummyStart.PointPart = StartLocation;
DummyStart.IsVertex = true; //hack-ish
GetArea()->FillInLegalNodes(DummyStart, GetArea()->Vertices, true, false, false);
DummyPath.Points.push_back(&DummyStart); //add it to the dummy path
//now add the ending point as a node to the starting point (if it's legal)
if (!GetArea()->GetFirstInvalidLinePoint(StartLocation, EndLocation)) {
DummyPath.Points.front()->PossibleNodes().push_back(&DummyEnd);
DummyPath.Points.clear();
DummyPath.Points.push_back(&DummyStart);
DummyPath.Points.push_back(&DummyEnd);
DummyPath.TotalDistance = Range(DummyStart, DummyEnd);
ShortestPath = DummyPath;
}
else {
for (MappedPointPtrArItr VertexLoop = GetArea()->Vertices.begin(); VertexLoop != GetArea()->Vertices.end(); ++VertexLoop) {
(*VertexLoop)->PossibleNodes().sort();
}
DevelopPathsRecursive(&DummyPath);
}
//now search for the shortest path and return it
if (ShortestPath.TotalDistance) {
MappedPointPtrArCItr cur_it = ShortestPath.Points.begin();
for (MappedPointPtrArCItr prev_it = cur_it++; cur_it != ShortestPath.Points.end(); prev_it = cur_it++) {
GetArea()->AddSTLArrays(ReturnPath, LinePath((*prev_it)->PointPart, (*cur_it)->PointPart, false, false), true);
LastPathVectors.push_back( std::pair<POINT, POINT>((*prev_it)->PointPart, (*cur_it)->PointPart));
}
PathsGenerated.push_back(ReturnPath);
}
else {
OutputDebugString(L"Pathfinding has failed.\n");
}
for (MappedPointPtrArCItr VertLoop = GetArea()->Vertices.begin(); VertLoop != GetArea()->Vertices.end(); ++VertLoop) {
(*VertLoop)->ClearPointStorage(true, true, true, true, true);
}
GetArea()->VertexNodeFind(); //restore all vertices nodes
return ReturnPath;
}
void Path::DevelopPathsRecursive(PathDescriptor* PathToDevelop) {
//NOTE: This procedure uses MappedPoint::IsConcaveVertex as a "hit" indicator
MappedPoint* DataBuffer;
for (MappedPointPtrArCItr PathsItr = PathToDevelop->Points.back()->PossibleNodes().begin(); PathsItr != PathToDevelop->Points.back()->PossibleNodes().end(); ++PathsItr) {
DataBuffer = *PathsItr;
//look for the current point in the current path - if found, do nothing (continue the loop), otherwise continue the operation
if (!DataBuffer->IsConcaveVertex) {
//change the transferbuffer, then undo the changes to speed up the procedure
double RangeBuffer = Range(*PathToDevelop->Points.back(), DataBuffer->PointPart);
PathToDevelop->TotalDistance += RangeBuffer;
if (!(PathToDevelop->TotalDistance > ShortestPath.TotalDistance && ShortestPath.TotalDistance)) {
PathToDevelop->Points.push_back(*PathsItr);
DataBuffer->IsConcaveVertex = true;
if (**PathsItr == EndPoint) {
if (!ShortestPath.TotalDistance || (ShortestPath.TotalDistance > PathToDevelop->TotalDistance)) {
ShortestPath = *PathToDevelop;
}
}
else {
DevelopPathsRecursive(PathToDevelop);
}
PathToDevelop->Points.pop_back();
DataBuffer->IsConcaveVertex = false;
}
PathToDevelop->TotalDistance -= RangeBuffer;
}
}
}
void Path::Draw(HDC DrawDC) {
HPEN DrawPen = CreatePen(PS_SOLID, 1, RGB(0, 255, 0));
HPEN OldPen = SelectPen(DrawDC, DrawPen);
for (std::list< PointAr >::const_iterator VectIt = PathsGenerated.begin(); VectIt != PathsGenerated.end(); ++VectIt) {
::MoveToEx(DrawDC, VectIt->front().x, VectIt->front().y, NULL);
::LineTo(DrawDC, VectIt->back().x, VectIt->back().y);
DrawPath(*VectIt, DrawDC, RGB(0, 0, 255));
}
SelectPen(DrawDC, OldPen);
DeletePen(DrawPen);
}
void Path::ClearData() { //does not clear obstacles
PathsGenerated.clear();
LastPathVectors.clear();
ShortestPath.ResetData();
} | true |
591702ca3705be174f4d852b0721af297b0f221b | C++ | Rufian55/Cpp | /makeChange.cpp | UTF-8 | 1,643 | 3.4375 | 3 | [
"MIT"
] | permissive | /******************************************************************************
* makeChange.cpp outputs minimum number of coins to make a given change input
* as argv[1]. Usage is makeChange {int currency2Return}
* Compile: g++ makeChange.cpp -o makeChange -g -Wall
* [1]
*******************************************************************************/
#include <climits>
#include <cstdlib>
#include <iostream>
using std::cout;
// Prototypes.
int minCoins(int coins[], int m, int V);
int main(int argc, char** argv) {
if (argc != 2) {
cout << "Usage: makeChange {int currency2Return}\n";
exit(1);
}
int coins[] = { 50, 20, 10, 5, 2, 1 }; // U.K.
int m = sizeof(coins) / sizeof(coins[0]); // m is size of coins array (# of diff. coins)
int V = atoi(argv[1]);
cout << "Minimum coins required is " << minCoins(coins, m, V) << '\n';
return 0;
}
int minCoins(int coins[], int m, int V) {
// table[i] will store the minimum number of coins
// required for i value, therefore table[V] is result.
int table[V + 1];
// Base case (If given value V is 0)
table[0] = 0;
// Initialize all table values EXCEPT table[0] as Infinite.
for (int i = 1; i <= V; i++)
table[i] = INT_MAX;
// Compute min coins required for all values from 1 to V.
for (int i = 1; i <= V; i++) {
// Process all coins smaller than i.
for (int j = 0; j < m; j++) {
if (coins[j] <= i) {
int sub_res = table[i - coins[j]];
if (sub_res != INT_MAX && sub_res + 1 < table[i]) {
table[i] = sub_res + 1;
}
}
}
}
return table[V];
}
// [1] Adapted from http://www.geeksforgeeks.org/find-minimum-number-of-coins-that-make-a-change/ | true |
0b7fa8ec43f5c234d7b73e1ec87844705d2f5240 | C++ | cy-peng/C_homework | /計算機技術作業HW5(4).cpp | UTF-8 | 761 | 2.953125 | 3 | [] | no_license |
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main( )
{int a,b,c,d,count,out,sum,n1,n2,n3,n4;
while(a==b||b==c||c==d||a==d||a==c||b==d){
srand(time(NULL));
a=rand()%10;
b=rand()%10;
c=rand()%10;
d=rand()%10;
}
printf("%d%d%d%d",a,b,c,d);
while(count!=4){
printf("\nPlease input four digits(0~9):\n");
scanf("%d%d%d%d",&n1,&n2,&n3,&n4);
count=0;out=0;
if(a==n1)
count++;
if(a==n2)
out++;
if(a==n3)
out++;
if(a==n4)
out++;
if(b==n2)
count++;
if(b==n1)
out++;
if(b==n3)
out++;
if(b==n4)
out++;
if(c==n3)
count++;
if(c==n1)
out++;
if(c==n2)
out++;
if(c==n4)
out++;
if(d==n4)
count++;
if(d==n3)
out++;
if(d==n2)
out++;
if(d==n1)
out++;
sum++;
printf("The result is %dA%dB",count,out);
}
printf("You got it %d times",sum);
}
| true |
c1a1518d7dfb4ee4c790dbbba415b6b60b80c829 | C++ | isaevi/PodcastLoader | /recordinfo.cpp | UTF-8 | 2,540 | 2.703125 | 3 | [] | no_license | #include <QtCore>
#include "recordinfo.h"
RecordInfo::RecordInfo(QObject *parent) : QObject(parent), _downloadPercent(0), _status(Ready)
{
}
bool RecordInfo::operator ==(const RecordInfo& other)
{
return _title.compare(other._title) == 0 && _url.matches(other._url, QUrl::None) && _date == other._date;
}
QString RecordInfo::title() const
{
return _title;
}
QUrl RecordInfo::url() const
{
return _url;
}
QString RecordInfo::guid() const
{
return _guid;
}
QDateTime RecordInfo::date() const
{
return _date;
}
void RecordInfo::setTitle(QString arg)
{
if (_title == arg)
return;
_title = arg;
emit titleChanged(arg);
}
void RecordInfo::setUrl(QUrl arg)
{
if (_url == arg)
return;
_url = arg;
emit urlChanged(arg);
}
void RecordInfo::setGuid(QString arg)
{
if (_guid == arg)
return;
_guid = arg;
emit guidChanged(arg);
}
void RecordInfo::setDate(QString date)
{
// QString date = "Sat, 19 Apr 2014 22:30:00 +0000";
const QString format = "ddd, dd MMM yyyy hh:mm:ss";
// QLocale loc( QLocale::C );
// QDateTime result = loc.toDateTime(date, format);
_date = QDateTime::fromString(date.remove(QRegExp("(\\s[+]\\d\\d\\d\\d)")), format);
if(!_date.isValid())
qWarning() << date;
}
int RecordInfo::downloadPercent() const
{
return _downloadPercent;
}
RecordInfo::Status RecordInfo::status() const
{
return _status;
}
int RecordInfo::length() const
{
return _length;
}
QString RecordInfo::description() const
{
return _description;
}
void RecordInfo::setDate(QDateTime arg)
{
if (_date == arg)
return;
_date = arg;
emit dateChanged(arg);
}
void RecordInfo::setLength(int arg)
{
if (_length == arg)
return;
_length = arg;
emit lengthChanged(arg);
}
void RecordInfo::setDescription(QString arg)
{
if (_description == arg)
return;
_description = arg;
emit descriptionChanged(arg);
}
void RecordInfo::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
if(bytesTotal > 0)
setDownloadPercent(bytesReceived * 100/bytesTotal);
}
void RecordInfo::setDownloadPercent(int arg)
{
if (_downloadPercent == arg)
return;
_downloadPercent = arg;
emit downloadPercentChanged(arg);
setStatus(_downloadPercent == 100 ? Downloaded : Downloading);
}
void RecordInfo::setStatus(Status arg)
{
if (_status == arg)
return;
_status = arg;
emit statusChanged(arg);
}
| true |
55fcc2d90d8dc672dbde0aa3388247ae268de3d0 | C++ | madhuri29/Thesis_25_5 | /Practice/Partitioning/Headers/matrix.h | UTF-8 | 948 | 2.984375 | 3 | [] | no_license | /*------------------Class Details------------------------
* Name: Matrix
*
* Description: Defines the connectivity matrix
* A vector of vectors that stores the connectivity information
* between nodes
*--------------------------------------------------------*/
#ifndef _MATRIX_H
#define _MATRIX_H
#include <iostream>
#include <vector>
#include <string>
#include "edge.h"
#include "data.h"
#include "claim.h"
#include <algorithm>
using namespace std;
class Matrix : public Data
{
vector<vector<Edge> > mat;
//methods
int binarySearchMat(vector<Edge> &thisvector, int searchId, int low, int high);
public:
//constructors/destructors
Matrix();
Matrix(int nodes, int edges);
~Matrix();
//methods
int edgeExists(int node1Id,int node2Id );
void addEdge (int node1Id,int node2Id );
int getWeight (int node1Id,int node2Id);
vector<int> getNeighbors(int nodeId);
void printMatrix();
void checkConnectivityMatrix();
};
#endif
| true |
28170d96f53a943778e3cb390338c6a64af92f62 | C++ | ostvld/figure | /source/CFigureFactory.cpp | UTF-8 | 479 | 2.53125 | 3 | [] | no_license | #include "CFigureFactory.h"
namespace NFigure {
IFigure *CFigureFactory::getFigure(EFigure type)
{
if (NFigure::EFigure::Rectangle == type)
{
return new NFigure::CRectangle("прямоугольник");
}
else if (NFigure::EFigure::Circle == type)
{
return new NFigure::CCircle("окружность");
}
else if (NFigure::EFigure::Triangle == type)
{
return new NFigure::CTriangle("треугольник");
}
}
}
| true |
72e4d82687aa8f4129b68ff0edb909974d9096f1 | C++ | kamyu104/LeetCode-Solutions | /C++/flip-equivalent-binary-trees.cpp | UTF-8 | 2,773 | 3.640625 | 4 | [
"MIT"
] | permissive | // Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// bfs solution
class Solution {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
queue<TreeNode *> q1({root1}), q2({root2});
while (!q1.empty() && !q2.empty()) {
auto node1 = q1.front(); q1.pop();
auto node2 = q2.front(); q2.pop();
if (!node1 && !node2) {
continue;
}
if (!node1 || !node2 || node1->val != node2->val) {
return false;
}
if ((!node1->left && !node2->right) ||
(node1->left && node2->right && node1->left->val == node2->right->val)) {
q1.emplace(node1->right);
q1.emplace(node1->left);
} else {
q1.emplace(node1->left);
q1.emplace(node1->right);
}
q2.emplace(node2->left);
q2.emplace(node2->right);
}
return q1.empty() && q2.empty();
}
};
// Time: O(n)
// Space: O(h)
// iterative dfs solution
class Solution2 {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
vector<TreeNode *> stk1 = {root1}, stk2 = {root2};
while (!stk1.empty() && !stk2.empty()) {
auto node1 = stk1.back(); stk1.pop_back();
auto node2 = stk2.back(); stk2.pop_back();
if (!node1 && !node2) {
continue;
}
if (!node1 || !node2 || node1->val != node2->val) {
return false;
}
if ((!node1->left && !node2->right) ||
(node1->left && node2->right && node1->left->val == node2->right->val)) {
stk1.emplace_back(node1->right);
stk1.emplace_back(node1->left);
} else {
stk1.emplace_back(node1->left);
stk1.emplace_back(node1->right);
}
stk2.emplace_back(node2->left);
stk2.emplace_back(node2->right);
}
return stk1.empty() && stk2.empty();
}
};
// Time: O(n)
// Space: O(h)
// recursive dfs solution
class Solution3 {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) {
return true;
}
if (!root1 || !root2 || root1->val != root2->val) {
return false;
}
return (flipEquiv(root1->left, root2->left) &&
flipEquiv(root1->right, root2->right) ||
flipEquiv(root1->left, root2->right) &&
flipEquiv(root1->right, root2->left));
}
};
| true |
315e861fac76171798ecf257491ea5283944a051 | C++ | ankityadav107/Solutions-in-Place | /Leetcode/Trees/ConvertSortedArraytoBinarySearchTree.cpp | UTF-8 | 840 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
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:
TreeNode *treemake(vector<int> arr, int l, int r)
{
if (l > r)
return NULL;
int mid = (l + r) / 2;
TreeNode *node = new TreeNode(arr[mid]);
node->left = treemake(arr, l, mid - 1);
node->right = treemake(arr, mid + 1, r);
return node;
}
TreeNode *sortedArrayToBST(vector<int> &nums)
{
int n = nums.size();
return treemake(nums, 0, n - 1);
}
}; | true |
e5da7ac37545dc533675c0cd0e765632268ae9b4 | C++ | MichaelLafosse99/MathforGames | /MathforGames/MathforGames/Matrix4.cpp | UTF-8 | 2,509 | 3.640625 | 4 | [] | no_license | #include "Matrix4.h"
//This initializes a 3d matrix to have values of 0
Matrix4::Matrix4()
{
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 4; c++)
{
data[r][c] = 0.0f;
identityMatrix[r][c] = 0.0f;
}
}
}
Matrix4::Matrix4(float xx, float xy, float xz, float xw, float yx, float yy, float yz, float yw, float zx, float zy, float zz, float zw, float wx, float wy, float wz, float ww)
{
float* ptr = &xx;
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 4; c++)
{
data[r][c] = *ptr;
identityMatrix[r][c] = *ptr++;
}
}
}
//The "definitions" for rotating the x, y, and z axes:
void Matrix4::setRotateX(float radians)
{
xAxis = Vector4(1.0, 0.0, 0.0, 0.0);
yAxis = Vector4(0.0, cosf(radians), sinf(radians), 0.0);
zAxis = Vector4(0.0, -sinf(radians), cosf(radians), 0.0);
wAxis = Vector4(0.0, 0.0, 0.0, 1.0);
}
void Matrix4::setRotateY(float radians)
{
xAxis = Vector4(cosf(radians), 0.0, -sinf(radians), 0.0);
yAxis = Vector4(0.0, 1.0, 0.0, 0.0);
zAxis = Vector4(sinf(radians), 0.0, cosf(radians), 0.0);
wAxis = Vector4(0.0, 0.0, 0.0, 1.0);
}
void Matrix4::setRotateZ(float radians)
{
xAxis = Vector4(cosf(radians), sinf(radians), 0.0, 0.0);
yAxis = Vector4(-sinf(radians), cosf(radians), 0.0, 0.0);
zAxis = Vector4(0.0, 0.0, 1.0, 0.0);
wAxis = Vector4(0.0, 0.0, 0.0, 1.0);
}
//Functions that rotate the x, y, and z axes:
void Matrix4::rotateX(float radians)
{
Matrix4 matrix;
matrix.setRotateX(radians);
*this = *this * matrix;
}
void Matrix4::rotateY(float radians)
{
Matrix4 matrix;
matrix.setRotateY(radians);
*this = *this * matrix;
}
void Matrix4::rotateZ(float radians)
{
Matrix4 matrix;
matrix.setRotateZ(radians);
*this = *this * matrix;
}
//Multiplying a vector by a matrix
Matrix4 Matrix4::operator*(const Matrix4 & otherMatrix) const
{
Matrix4 result;
//in the case for rows and columns, "r" would be for row,
//and "c" would be for column.
for (int r = 0; r < 4; r++)
{
for (int c = 0; c < 4; c++)
{
result.data[c][r] = data[0][r] * otherMatrix.data[c][0] +
data[1][r] * otherMatrix.data[c][1] +
data[2][r] * otherMatrix.data[c][2] +
data[3][r] * otherMatrix.data[c][3];
}
}
return result;
}
//Multiplying a vector by a matrix
Vector4 Matrix4::operator*(Vector4 vector)
{
Vector4 result;
for (int r = 0; r < 3; r++)
{
result[r] = data[0][r] * vector[0] +
data[1][r] * vector[1] +
data[2][r] * vector[2];
}
return result;
}
Matrix4::operator float*()
{
return data[0];
}
| true |
836694f74ee4f0ec3d3211ceaf2303dff22f6a4c | C++ | 18ivan18/ArtificialIntelligence | /descisionTree/Solver.h | UTF-8 | 503 | 2.609375 | 3 | [] | no_license | #ifndef SOLVER
#define SOLVER
#include <string>
#include <vector>
using std::string;
using std::vector;
class Solver
{
private:
const int DEFAULT_FOLD = 5;
std::vector<std::string> split(std::string &, const std::string &);
vector<vector<string>> input;
int fold;
void readInput(const string &);
vector<int> getShuffledIndexes(int);
double fractionToPercentage(double);
public:
Solver(const string &);
void setFold(int);
void solve();
~Solver();
};
#endif
| true |
e127f849f0fef3a39709b512e018404877e1f226 | C++ | CR0N00S/lab13_2561_2 | /lab13_1.cpp | UTF-8 | 893 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
template <typename T>
void swap(T d[],int x,int y){
T temp = d[x];
d[x] = d[y];
d[y] = temp;
}
template <typename T>
void insertionSort(T d[],int N){
int x=0,i=1;
for(int i=1;i<N;i++){
int x=i;
for(int f=0;f<N;f++){
if(f==x) cout<<"[";
cout<<d[f];
if(f==x) cout<<"]";
cout<<" ";
}
cout<<"=> ";
for(int z=i-1;z>=0;z--){
if(d[x]>d[z]){
swap(d,x,z);
x=z;
}
}
for(int f=0;f<N;f++){
if(f==x) cout<<"[";
cout<<d[f];
if(f==x) cout<<"]";
cout<<" ";
}
cout<<"\n";
}
}
int main(){
int a[10] = {12,25,30,44,2,0,4,7,55,25};
cout << "Input Array:";
for(int i = 0; i < 10; i++) cout << a[i] << " ";
cout << "\n\n";
insertionSort(a,10);
cout << "\nSorted Array:";
for(int i = 0; i < 10; i++) cout << a[i] << " ";
} | true |
beeaa4884351b4145cb23932a035c3be1ba15ea3 | C++ | DIYMAN-CSHOP/DIYMAN_ArduinoProjects | /Automatic Alcohol Dispenser - Rua tay tu dong.ino | UTF-8 | 1,380 | 2.6875 | 3 | [] | no_license | #define inPin 12
#define LedStand 13
#define LedPump 11
#define Buzzer 10
#define OutPump 9
#define TimeToBegin 500
#define TimeToPump 300
int val1, val2=-1;
char buf[10];
int count = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("HELLO");
pinMode(inPin, INPUT);
pinMode(LedPump, OUTPUT);
pinMode(LedStand, OUTPUT);
pinMode(Buzzer, OUTPUT);
pinMode(OutPump, OUTPUT);
digitalWrite(Buzzer, LOW);
digitalWrite(LedPump, LOW);
digitalWrite(LedStand, HIGH);
digitalWrite(OutPump, HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
val1 = digitalRead(inPin);
if(val1!=val2)
{
val2 = val1;
sprintf(buf, "Value = %d", val2);
Serial.println(buf);
count = 0;
//if(val2 == 1) count = 0;
}
if(val2 == 0)
count++;
if(count >= TimeToBegin/10 && count < (TimeToPump+TimeToBegin)/10)
{
digitalWrite(LedPump, HIGH);
digitalWrite(LedStand, LOW);
digitalWrite(Buzzer, HIGH);
digitalWrite(OutPump, LOW); //Pump out
//Serial.println(count);
}
if(count >= (TimeToPump+TimeToBegin)/10 || val2 == 1)
{
digitalWrite(LedPump, LOW);
digitalWrite(LedStand, HIGH);
digitalWrite(Buzzer, LOW);
digitalWrite(OutPump, HIGH); //Pump off
Serial.println(count);
//count = 0;
//val2 = -1;
}
delay(10);
}
| true |
db958e5471fc3d50dce5fc7f141071dcaaa7ad98 | C++ | ahmadtc1/LineFollowingRobot | /line_Follower.ino | UTF-8 | 2,702 | 3.015625 | 3 | [] | no_license | const int LeftmotorPin1 = 12; // Assign Digital pin 12 of Arduino to Left Motor Pin1
const int LeftmotorPin2 = 11; // Assign Digital pin 11 of Arduino to Left Motor Pin2
const int RightmotorPin3 = 10; // Assign Digital pin 10 of Arduino to Right Motor Pin3
const int RightmotorPin4 = 9; // Assign Digital pin 9 of Arduino to Right Motor Pin4
#define Rightsensor 2 // Assign Digital pin 2 of Arduino to Right Sensor
#define Leftsensor 3 // Assign Digital pin 3 of Arduino to Left Sensor
byte i;
void setup()
{
// set the sensor pins as an input:
pinMode(Leftsensor,INPUT);
pinMode(Rightsensor,INPUT);
// set all the other pins you're using as outputs:
pinMode(LeftmotorPin1, OUTPUT);
pinMode(LeftmotorPin2, OUTPUT);
pinMode(RightmotorPin3, OUTPUT);
pinMode(RightmotorPin4, OUTPUT);
Serial.begin(9600);
}
void loop()
{
Serial.println(digitalRead(Leftsensor));
Serial.println(digitalRead(Rightsensor));
delay(5);
// if both sensors are 0, Left motor will turn forward and Right motor will turn forward:
if (digitalRead(Leftsensor) == LOW && digitalRead(Rightsensor) == LOW) {
digitalWrite(LeftmotorPin1, LOW); // set leg 1 of the H-bridge low
digitalWrite(LeftmotorPin2, HIGH); // set leg 2 of the H-bridge high
digitalWrite(RightmotorPin3, LOW); // set leg 1 of the H-bridge low
digitalWrite(RightmotorPin4, HIGH); // set leg 2 of the H-bridge high
}
// if Left sensor is 1 and Right sensor is 0, Left motor will turn forward and Right motor will stop:
else if (digitalRead(Leftsensor) == HIGH && digitalRead(Rightsensor) == LOW){
digitalWrite(LeftmotorPin1, LOW); // set leg 1 of the H-bridge low
digitalWrite(LeftmotorPin2, HIGH); // set leg 2 of the H-bridge low
digitalWrite(RightmotorPin3, LOW); // set leg 1 of the H-bridge low
digitalWrite(RightmotorPin4, LOW); // set leg 2 of the H-bridge high
delay(20);
}
// if Left sensor is 0 and Right sensor is 1, Left motor will stop and Right motor will turn forward:
else if (digitalRead(Leftsensor) == LOW && digitalRead(Rightsensor) == HIGH){
digitalWrite(LeftmotorPin1, LOW); // set leg 1 of the H-bridge low
digitalWrite(LeftmotorPin2, LOW); // set leg 2 of the H-bridge low
digitalWrite(RightmotorPin3, LOW); // set leg 1 of the H-bridge low
digitalWrite(RightmotorPin4, HIGH); // set leg 2 of the H-bridge high
delay(20);
}
// if Left sensor is 1 and Right sensor is 1, the motors will stop:
else if (digitalRead(Leftsensor) == HIGH && digitalRead(Rightsensor) == HIGH){
digitalWrite(LeftmotorPin1, LOW); // set leg 1 of the H-bridge low
digitalWrite(LeftmotorPin2, LOW); // set leg 2 of the H-bridge low
digitalWrite(RightmotorPin3, LOW); // set leg 1 of the H-bridge low
digitalWrite(RightmotorPin4, LOW); // set leg 2 of the H-bridge high
}
}
| true |
f4423ae53c5ca86d02bace0295c09f0a5ec7e15d | C++ | anmolgup/Competitive-programming-code | /Codeforces/26/B.cpp | UTF-8 | 394 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
string s;
cin>>s;
stack<char> a;
ll l=s.length();
for(ll i=0;i<l;i++)
{
if(a.empty())
{
a.push(s[i]);
}
else if(s[i]==')')
{
if(a.top()=='(')
{
a.pop();
}
else
{
a.push(s[i]);
}
}
else
{
a.push(s[i]);
}
}
cout<<l-a.size()<<endl;
} | true |
e37c84500f6fb44b630194cefadbdb33ecf44de3 | C++ | manparvesh/coursera-ds-algorithms | /2. Data Structures/Programming-Assignment-4/is_bst/is_bst.cpp | UTF-8 | 1,489 | 3.6875 | 4 | [
"MIT"
] | permissive | #include <algorithm>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
struct Node {
int key;
int left;
int right;
Node() : key(0), left(-1), right(-1) {}
Node(int key_, int left_, int right_) : key(key_), left(left_), right(right_) {}
};
vector<Node> tree;
void inorder_traversal(vector<int> &result, int root) {
if (root == -1) return;
inorder_traversal(result, tree[root].left);
result.push_back(tree[root].key);
inorder_traversal(result, tree[root].right);
}
vector <int> in_order(const vector<Node>& tree) {
vector<int> result;
// Finish the implementation
// You may need to add a new recursive method to do that
inorder_traversal(result, 0);
return result;
}
bool IsBinarySearchTree(const vector<Node>& tree) {
// Implement correct algorithm here
if (tree.size() > 1) {
vector <int> v = in_order(tree);
for (int i = 1; i < v.size(); i++) {
if (v[i] < v[i - 1]) return false;
}
}
return true;
}
int main() {
int nodes;
cin >> nodes;
for (int i = 0; i < nodes; ++i) {
int key, left, right;
cin >> key >> left >> right;
tree.push_back(Node(key, left, right));
}
if (IsBinarySearchTree(tree)) {
cout << "CORRECT" << endl;
} else {
cout << "INCORRECT" << endl;
}
return 0;
}
| true |
7b1325fe673c2875b9c8b23b41adc0b25d44a4c4 | C++ | raysloks/Project3 | /DynamicState.cpp | UTF-8 | 464 | 2.703125 | 3 | [] | no_license | #include "DynamicState.h"
bool DynamicState::operator==(const DynamicState& rhs) const
{
return !(*this != rhs);
}
bool DynamicState::operator!=(const DynamicState& rhs) const
{
if (scissor.offset.x != rhs.scissor.offset.x)
return true;
if (scissor.offset.y != rhs.scissor.offset.y)
return true;
if (scissor.extent.width != rhs.scissor.extent.width)
return true;
if (scissor.extent.height != rhs.scissor.extent.height)
return true;
return false;
}
| true |
5388c76ecdd654948d9c9b018000c5a31096973e | C++ | LivingFray/SpaceCOOP | /SpaceCOOP/src/client/HUD.cpp | UTF-8 | 780 | 2.75 | 3 | [] | no_license | #include "HUD.h"
#include "Client.h"
#include <string>
HUD::HUD() {
font.loadFromFile("assets/cour.ttf");
health.setFont(font);
health.setCharacterSize(24);
health.setPosition(sf::Vector2f(10.0f, 10.0f));
health.setFillColor(sf::Color(255, 255, 255));
}
HUD::~HUD() {
}
void HUD::draw(sf::RenderTarget& target, sf::RenderStates states) const {
target.setView(HUDView);
target.draw(health, states);
}
void HUD::resize(unsigned int width, unsigned int height) {
HUDView = sf::View(sf::FloatRect(0.0f, 0.0f, static_cast<float>(width), static_cast<float>(height)));
}
void HUD::update() {
if (client->getShip()) {
std::string str = "Health: " + std::to_string(client->getShip()->getHealth());
health.setString(str);
} else {
health.setString("Health: 0");
}
}
| true |
2b10dd31b62007dd2dbe603d377fb4504ec6a16e | C++ | Summer-16/arduino-codes | /count_persion_in_roon_IR/count_persion_in_roon_IR.ino | UTF-8 | 1,323 | 2.625 | 3 | [] | no_license | int s1 = 0;
int s2 = 0;
int a = 0;
int a1 = 0;
int b = 0;
int c = 0;
int num = 0;
void setup()
{
Serial.begin(9600);
pinMode(A4, INPUT);
pinMode(A5, INPUT);
pinMode(13, OUTPUT);
}
void loop()
{
s1 = digitalRead(A4);
s2 = digitalRead(A5);
if (s1 == HIGH)
{
b = 1;
if ((s1 == HIGH) && (b == 1))
{
while (digitalRead(A4) == HIGH)
;
delay(100);
b = 2;
}
if ((s2 == HIGH) && (b == 2))
{
while (digitalRead(A5) == HIGH)
;
/*Serial.println("someone enter in room");
//Serial.print("total no of person in room is");
Serial.print(a);*/
b = 0;
delay(100);
a++;
}
}
s1 = digitalRead(A4);
s2 = digitalRead(A5);
c = 2;
if (s2 == HIGH)
{
c = 2;
if ((s2 == HIGH) && (c == 2))
{
while (digitalRead(A5) == HIGH)
;
c = 3;
delay(100);
}
if ((s1 == HIGH) && (c == 3))
{
while (digitalRead(A4) == HIGH)
;
//Serial.println("\nsomeone lefted the room");
//Serial.print("\n");
//Serial.print("total no of person in room is");
//Serial.print(a1);
delay(100);
a1++;
c = 2;
}
}
num = a - a1;
Serial.println("total no of person in room is");
Serial.println(a);
Serial.println(a1);
Serial.println(num);
}
| true |
d959108e3e42ef7a0431b2b3ac0bae4c93bcb7d6 | C++ | oursuccess/cplusplus_primer_practices | /12.26.cpp | GB18030 | 701 | 3.1875 | 3 | [] | no_license | #include<iostream>
#include<memory>
#include<string>
using std::string;
using std::cin;
using std::allocator;
using std::cout;
using std::uninitialized_copy;
using std::uninitialized_fill_n;
int main()
{
string s;
cin >> s;
//wrong elem below
//allocator<string> allos;
//wrong the same?
//correct need to update the arguement of q
allocator<char> allos;
auto p = allos.allocate(s.size() * 2);
auto q = uninitialized_fill_n(p,s.size(),'s');
//1ӡcharתΪstd::initializer_list<_Elem>
//string ӦΪchar allocatorģܵĶϢӦΪchar
uninitialized_copy(s.begin(), s.end(), q);
cout << p ;
system("pause");
return 0;
}
| true |
22d3427016b83a8b784e64eef6d7547a5f405319 | C++ | manraj23s/Data-Structures-Algorithms | /Lab 5-HashTableADTs/TestPlan1Table.cpp | UTF-8 | 5,693 | 3.53125 | 4 | [] | no_license | /*
//========================================================================
//
// Laboratory 10 Test Plan 1 Test10.cpp
//
// Name: Lab 10 test compilation
// Version #: 1
// Date Originally Written: 04/08/2021
// Date Last Modified: 04/10/2021
// Authors's Names: Manraj Singh (Programming & Documentation) &
// Corey Shimshock (Documentation & Programming)
// Purpose: Class declarations for the implementation of test plan 1 to test
// implementation of Hash Table ADT with user commands and display.
//
//=========================================================================
#include <iostream>
#include <string>
#include "TableHash.cpp"
using namespace std;
//=========================================================================
//class for data of test
class DataTest {
public:
//constructor
DataTest();
//set key function setter
void setKey(const string& newKey);
//get key function getter
string getKey() const;
//get value function getter
int getValue() const;
//hash table function
static unsigned int hash(const string& str);
private:
//key string
string loginKey;
//key value
int value;
//key count
static int count;
};
//count intially 0
int DataTest::count = 0;
//=========================================================================
///Preconditions: Table must be valid and declared
///Postconditions: Table has value initialized with 0 count
///Inputs: No input
///Outputs: No output
DataTest::DataTest() : value(++count) {
}
//=========================================================================
///Preconditions: Table must be valid and declared
///Postconditions: Table has key instantiated
///Inputs: User input of key
///Outputs: Key for table to output
void DataTest::setKey(const string& newKey) {
loginKey = newKey;
}
//=========================================================================
///Preconditions: Table must be valid and declared and key is set
///Postconditions: Get key for table to output and store
///Inputs: User input of key is then received for table in getter
///Outputs: Key returned
string DataTest::getKey() const {
return loginKey;
}
//=========================================================================
///Preconditions: Table must be valid and declared
///Postconditions: Table has key value instantiated
///Inputs: User input of key
///Outputs: Key for table to output
int DataTest::getValue() const {
return value;
}
//=========================================================================
///Preconditions: Table must be valid and declared
///Postconditions: Value is equated to string
///Inputs: User input of key value
///Outputs: Outputted value returned for table
unsigned int DataTest::hash(const string& str) {
//value instantiated as 0
unsigned int val = 0;
//for every index of string's length, instantiate to val
for (int i = 0; i < str.length(); ++i)
val += str[i];
//return val
return val;
}
//=========================================================================
void print_help() {
cout << endl << "Commands:" << endl;
cout << "**===================================================**" << endl;
cout << "*= H : Help (displays this message) =*" << endl;
cout << "=* +x : Insert (or update) data item with key x *=" << endl;
cout << "*= -x : Remove the data element with the key x =*" << endl;
cout << "=* ?x : Retrieve the data element with the key x *=" << endl;
cout << "*= E : Empty table? =*" << endl;
cout << "=* C : Clear the table *=" << endl;
cout << "*= Q : Quit the test program =*" << endl;
cout << "**===================================================**" << endl;
}
//=========================================================================
int main(int argc, char** argv) {
//table has length of 7
TableHash<DataTest, string> table(7);
print_help();
//while user does not exit
do {
//ask for user command
cout << endl << "Command: ";
char cmd;
cin >> cmd;
//if command is + or ? or -, use string for key
DataTest item;
if (cmd == '+' || cmd == '?' || cmd == '-') {
string key;
cin >> key;
item.setKey(key);
}
//switch for commands
switch (cmd) {
//output structure
case 'H':
case 'h':
print_help();
break;
//+ = insert
case '+':
table.addValue(item);
cout << "Inserted data item with key ("
<< item.getKey() << ") and value ("
<< item.getValue() << ")" << endl;
break;
//- = remove
case '-':
if (table.deleteValue(item.getKey())) {
cout << "Removed data item with key ("
<< item.getKey() << ")" << endl;
}
else {
cout << "Could not remove data item with key ("
<< item.getKey() << ")" << endl;
}
break;
//? = retrieve
case '?':
if (table.fetchValue(item.getKey(), item)) {
cout << "Retrieved data item with key ("
<< item.getKey() << ") and value ("
<< item.getValue() << ")" << endl;
}
else {
cout << "Could not retrieve data item with key ("
<< item.getKey() << ")" << endl;
}
break;
//c = clear table
case 'C':
case 'c':
cout << "Clear the hash table" << endl;
table.wipeClear();
break;
//e = empty table bool ask
case 'E':
case 'e':
cout << "Hash table is "
<< (table.isTableEmpty() ? "" : "NOT")
<< " empty" << endl;
break;
//q = exit program
case 'Q':
case 'q':
return 0;
default:
cout << "Invalid command!" << endl;
}
} while (1);
return 0;
}
//=========================================================================
*/ | true |
5d667713a59647faf725eb87bffacfc53347c912 | C++ | Z02X/TermPomodoro | /src/main.cpp | UTF-8 | 1,675 | 3.46875 | 3 | [
"BSD-3-Clause"
] | permissive | #include <iostream>
#include <unistd.h>
#include <SFML/Audio.hpp>
int main() {
//This is the intager that stores the users input
int input;
//This is the audio file that plays when the timer is up
sf::Music music;
if (!music.openFromFile("./files/sound.wav"))
//TODO this error triggers due to a permission error but it works anyway :/?
std::cout << "This error sometimes triggers due to a harmless permission error?!.. If it triggers for another reason well your fucked I guess :D";
while(1) {
//Clears screen
std::cout << "\x1B[2J\x1B[H";
//Asks the user what they would like to do
std::cout << "\nHow long would you want to take a break for or work for?\n\n1. Work for 25 mins\n2. Take a break for 5 mins\n3. Take a break for 10 mins\n\n:";
std::cin >> input;
//Checks the Input starting with 3 since we all know you are lazy
if(input == 3) {
std::cout << "\nTaking a break for 10 mins\n";
sleep(600);
std::cout << "Time is up!\n";
music.play();
sleep(10);
music.stop();
} else if (input == 2) {
std::cout << "\nTaking a break for 5 mins\n";
sleep(300);
std::cout << "Time is up!\n";
music.play();
sleep(10);
music.stop();
//Note invaild input will trigger this
} else {
std::cout << "\nWorking for 25 mins\n";
sleep(1500);
std::cout << "Time is up!\n";
music.play();
sleep(10);
music.stop();
}
}
}
| true |
4e51b8be78d1bc92195cbda303d255558a01e716 | C++ | zyxrrr/LeetCode | /494-Target Sum/Solution.cpp | UTF-8 | 1,042 | 2.96875 | 3 | [] | no_license | class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
if (nums.empty()){return 0;}
return find(nums,0,S);
/*
queue<int> q;
queue<int> tmp;
int cnt = 0;
if (nums.empty()){
return cnt;
}
q.push(nums[0]);
q.push(-nums[0]);
for (int i = 1; i < nums.size(); i++){
while (!q.empty()){
int val = q.front();
q.pop();
tmp.push(val + nums[i]);
tmp.push(val - nums[i]);
}
q.swap(tmp);
}
while (!q.empty()){
if (q.front() == S){
cnt++;
}
q.pop();
}
return cnt;
*/
}
int find(vector<int> &nums,int idx,int S){
if (idx == nums.size()){
if (S == 0){return 1;}
else{return 0;}
}else{
return find(nums,idx + 1, S - nums[idx]) + find(nums,idx + 1, S + nums[idx]);
}
}
};
| true |
15277f2e7f93d8515123c7b5b6d11aa78dead84a | C++ | seth1002/antivirus-1 | /include/klava/klavstl/allocator.h | UTF-8 | 3,038 | 2.59375 | 3 | [] | no_license | // allocator.h
//
#ifndef allocator_h_INCLUDED
#define allocator_h_INCLUDED
#include <stdlib.h>
#include <string.h>
#include <kl_types.h>
#ifdef KLAVA
// NB: in order to prevent definition conflict, a link may not include <new>, either directly, or indirectly
inline void* operator new (size_t size, void* ptr) throw() { return ptr; }
inline void* operator new[](size_t size, void* ptr) throw() { return ptr; }
inline void operator delete (void* ptr, void*) throw() {}
inline void operator delete[](void* ptr, void*) throw() {}
#else // KLAVA
# include <new>
#endif // KLAVA
#ifdef _MSC_VER
# pragma intrinsic (memcpy,memset)
#endif
#ifdef _WIN32_WCE // by ArtemK
#if (_WIN32_WCE <= 400) && !defined(_STLP_INTERNAL_CONSTRUCT_H) // WinCCe.NET does not need it
inline void *__cdecl operator new (size_t, void *p) { return (p); }
#else
void * operator new (size_t, void *p);
#endif
#endif
namespace klavstl
{
////////////////////////////////////////////////////////////////
// some base algorithms
#ifdef min
# undef min
#endif // min
#ifdef max
# undef max
#endif // max
template <class T>
inline void swap (T& a, T& b)
{ T tmp = a; a = b; b = tmp; }
template <class T>
inline const T& min (const T& a, const T& b)
{ return (b < a) ? b : a; }
template <class T>
inline const T& max (const T& a, const T& b)
{ return (a < b) ? b : a; }
////////////////////////////////////////////////////////////////
// standard malloc-based allocator implementation
class malloc_allocator
{
public:
uint8_t * alloc (size_t size)
{ return (uint8_t *)::malloc (size); }
uint8_t * realloc (void *p, size_t nsz)
{ return (uint8_t *)::realloc (p, nsz); }
void free (void *p)
{ ::free (p); }
};
typedef ptrdiff_t distance_type;
extern "C"
void memmove (void *dst, const void *src, size_t);
#define DECLARE_STD_TYPEDEFS(T) \
typedef Allocator allocator_type; \
typedef size_t size_type; \
typedef ptrdiff_t difference_type; \
typedef T * pointer; \
typedef const T * const_pointer; \
typedef T& reference; \
typedef const T& const_reference; \
typedef T value_type; \
typedef pointer iterator; \
typedef const_pointer const_iterator;
#define DECLARE_PARENT_TYPEDEFS(Parent) \
typedef typename Parent::allocator_type allocator_type; \
typedef typename Parent::size_type size_type; \
typedef typename Parent::difference_type difference_type; \
typedef typename Parent::pointer pointer; \
typedef typename Parent::const_pointer const_pointer; \
typedef typename Parent::reference reference; \
typedef typename Parent::const_reference const_reference; \
typedef typename Parent::value_type value_type; \
typedef typename Parent::iterator iterator; \
typedef typename Parent::const_iterator const_iterator;
} // namespace klavstl
#endif // allocator_h_INCLUDED
| true |
fe2f24144c3aa521cdca0495cb2f7f9dafeb6d45 | C++ | jihoon-ko/AlgorithmStorage | /treeStructure/Splay.cpp | UTF-8 | 5,529 | 2.84375 | 3 | [] | no_license | #include<cstdio>
#include<algorithm>
#define lnode now_node->l
#define rnode now_node->r
using namespace std;
struct node{
int val;
node *p,*l,*r;
int cnt;
long long sum,mini,maxi;
bool rev;
}tree[300002];
node *root = &tree[0];
int n,q;
void preorder(node *now_node){
if(!now_node) return;
if(now_node->rev){
if(lnode) lnode->rev = !(lnode->rev);
if(rnode) rnode->rev = !(rnode->rev);
node *tmp = lnode; lnode = rnode; rnode = tmp;
now_node->rev = false;
}
//printf("push (%d,%d,%d)\n",now_node->val, now_node->cnt, now_node->rev);
preorder(lnode);
if(now_node->val >=1 && now_node->val <= n) printf("%d ",now_node->val);
//printf("pop left\n");
preorder(rnode);
//printf("pop right\n");
}
void Update(node *now_node){
now_node->cnt = 1;
now_node->sum = now_node->val;
now_node->mini = now_node->val;
now_node->maxi = now_node->val;
if(lnode){
now_node->cnt += lnode->cnt;
now_node->sum += lnode->sum;
now_node->mini = min(now_node->mini, lnode->mini);
now_node->maxi = max(now_node->maxi, lnode->maxi);
}
if(rnode){
now_node->cnt += rnode->cnt;
now_node->sum += rnode->sum;
now_node->mini = min(now_node->mini, rnode->mini);
now_node->maxi = max(now_node->maxi, rnode->maxi);
}
}
void Rotate(node *now_node){
node *p = now_node->p;
node *tmp;
if(p->rev){
if(p->l) p->l->rev = !(p->l->rev);
if(p->r) p->r->rev = !(p->r->rev);
tmp = p->l; p->l = p->r; p->r = tmp;
p->rev = false;
}
if(now_node->rev){
if(lnode) lnode->rev = !(lnode->rev);
if(rnode) rnode->rev = !(rnode->rev);
tmp = lnode; lnode = rnode; rnode = tmp;
now_node->rev = false;
}
node *moved_node;
if(p->l == now_node){
moved_node = now_node->r;
p->l = moved_node;
now_node->r = p;
}else{
moved_node = now_node->l;
p->r = moved_node;
now_node->l = p;
}
now_node->p = p->p;
p->p = now_node;
if(moved_node) moved_node->p = p;
if(now_node->p){
if(p == now_node->p->l) now_node->p->l = now_node;
else now_node->p->r = now_node;
}else{
root = now_node;
}
Update(p);
Update(now_node);
}
void Lazy(node *now_node){
if(now_node->rev){
node *tmp = lnode;
lnode = rnode;
rnode = tmp;
if(lnode) lnode->rev = !(lnode->rev);
if(rnode) rnode->rev = !(rnode->rev);
now_node->rev = false;
}
}
void Splay(node *now_node){
while(now_node->p){
node *p = now_node->p;
node *g = p->p;
if(g){
if((g->l == p) ^ (p->l == now_node)) Rotate(now_node);
else Rotate(p);
}
Rotate(now_node);
}
}
void find_kth(int k){
node *now_node = root;
while(1){
Lazy(now_node);
int lcnt = (lnode) ? lnode->cnt : 0;
//printf("(%d,%d)\n",now_node->val,lcnt);
if(lcnt == k) break;
else if(lcnt < k){
k -= (lcnt + 1);
now_node = rnode;
}else{
now_node = lnode;
}
//preorder(root);
}
Splay(now_node);
//preorder(root);
}
void insertNode(int x){
node *now_node = root;
while(rnode) now_node = rnode;
rnode = &tree[x];
tree[x] = {x, now_node, NULL, NULL, 1, x, x, x, false};
Splay(&tree[x]);
}
void setInterval(int ll,int rr){
find_kth(ll-1);
//printf("\nStep #1\n\n");
//preorder(root);
node *ori_root = root;
root = root->r;
root->p = NULL;
//printf("\nStep #2\n\n");
//preorder(root);
find_kth(rr - ll + 1);
root->p = ori_root;
ori_root->r = root;
root = ori_root;
//printf("\nStep #3\n\n");
//preorder(root);
}
int main(){
scanf("%d%d",&n,&q);
tree[0] = {0,NULL,NULL,NULL,1,0,0,0,false};
for(int i=1;i<=n+1;i++){
insertNode(i);
}
//preorder(root);
for(int i=0;i<q;i++){
int mode, aa, bb, cc;
scanf("%d",&mode);
if(mode == 1){
scanf("%d%d",&aa,&bb);
setInterval(aa,bb);
node *now_node = root->r->l;
printf("%lld %lld %lld\n",now_node->mini, now_node->maxi, now_node->sum);
now_node->rev = !(now_node->rev);
}else if(mode == 2){
scanf("%d%d%d",&aa,&bb,&cc);
setInterval(aa,bb);
node *now_node = root->r->l;
printf("%lld %lld %lld\n",now_node->mini, now_node->maxi, now_node->sum);
int mod;
if(cc >= 0){
mod = (cc % (bb-aa+1));
}else{
mod = ((bb-aa+1) - ((-cc) % (bb-aa+1))) % (bb-aa+1);
}
if(mod){
now_node->rev = !(now_node->rev);
setInterval(aa,aa+mod-1);
node *now_node = root->r->l;
now_node->rev = !(now_node->rev);
setInterval(aa+mod,bb);
now_node = root->r->l;
now_node->rev = !(now_node->rev);
}
}else if(mode == 3){
scanf("%d",&aa);
find_kth(aa);
printf("%d\n",root->val);
}else{
scanf("%d",&aa);
Splay(&tree[aa]);
printf("%d\n",(&tree[aa])->l->cnt);
//printf("\n");
}
//printf("\n\nFINAL\n");
//preorder(root);
//printf("\n");
}
preorder(root);
}
| true |
e3f211fb2091f4cd5e3ee2895f310d621116fdd7 | C++ | nik3122/Trolled | /Source/Trolled/Items/FoodItem.cpp | UTF-8 | 2,259 | 2.671875 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "FoodItem.h"
#include "Trolled/MainCharacter.h"
#include "Trolled/Player/TrolledPlayerController.h"
#include "Trolled/Components/InventoryComponent.h"
// namespace used for language localization
#define LOCTEXT_NAMESPACE "FoodItem"
// set default food properties
UFoodItem::UFoodItem()
{
HealAmount = 5.f;
StaminaAmount = 5.f;
HungerAmount = 5.f;
ThirstAmount = 5.f;
UseActionText = LOCTEXT("ItemUseActionText", "Consume");
}
void UFoodItem::Use(class AMainCharacter* Character)
{
// if character valid
if (Character)
{
// find health, stamina, hunger and thirst recovery amount
const float ActualHealedAmount = Character->ModifyHealth(HealAmount);
const float ActualStaminaAmount = Character->ModifyStamina(StaminaAmount);
const float ActualHungerAmount = Character->ModifyHunger(HungerAmount);
const float ActualThirstAmount = Character->ModifyThirst(ThirstAmount);
// check if didnt recovered any stats
const bool bHealed = !FMath::IsNearlyZero(ActualHealedAmount);
const bool bStamina = !FMath::IsNearlyZero(ActualStaminaAmount);
const bool bHunger = !FMath::IsNearlyZero(ActualHungerAmount);
const bool bThirst = !FMath::IsNearlyZero(ActualThirstAmount);
// if not the server, display a message that the food was consumed
if (!Character->HasAuthority())
{
if (ATrolledPlayerController* PC = Cast<ATrolledPlayerController>(Character->GetController()))
{
if (bHealed || bStamina || bHunger || bThirst)
{
PC->ClientShowNotification(FText::Format(LOCTEXT("ConsumeText", "Ate {FoodName}, healed {HealAmount} health."), ItemDisplayName, ActualHealedAmount));
}
else
{
PC->ClientShowNotification(FText::Format(LOCTEXT("FullHealthText", "No need to eat {FoodName}, health is already full."), ItemDisplayName, ActualHealedAmount));
}
}
}
// if food used, remove from inventory on client so the use is instant
if (bHealed || bStamina || bHunger || bThirst)
{
if (UInventoryComponent* Inventory = Character->PlayerInventory)
{
Inventory->ConsumeQuantity(this, 1);
}
}
}
}
#undef LOCTEXT_NAMESPACE | true |
95b8200330f50daa1311ae3d2ef7ee2123fb982c | C++ | ChuckBolin/TwistedTunes | /include/cgamestatescore.h | UTF-8 | 1,257 | 2.5625 | 3 | [] | no_license | //CGameStateScore.h
#ifndef GAME_STATE_SCORE_H
#define GAME_STATE_SCORE_H
#include "CGameStateObject.h"
#include "CTimer.h"
#include "CGraphics.h"
#include <iostream>
#include <windows.h>
#include "CGameData.h"
#include "keystatus.h"
#include "CConfigData.h"
struct HIGH_SCORE{
std::string name;
int score;
};
class CGameStateScore : public CGameStateObject{
public:
CGameStateScore(void);
~CGameStateScore(void);
void Initialize();
void Activate();
CGameStateObject* Update(double timeDifference, CGameData &data, CConfigData &cfg, CGraphics &con);
int Render(CGraphics &con, CGameData &data, CConfigData &cfg);
void Deactivate();
void Resume();
void Pause();
void Save();
void AddTransitionEvent(int event, CGameStateObject* p_Next);
private:
std::vector<TRANSITION_EVENT> m_TE; //stores all transition events
int m_event;
CTimer m_timer;
int m_selection;
//used for fading
int m_red;
int m_green;
int m_blue;
//prevents ENTER key bleed through to other states
bool m_bActivated;
CTimer m_enableTimer;
CMouse m_mouse;
int m_width;
int m_height;
std::vector<HIGH_SCORE> m_HighScore;
std::string convertInteger(int num);
};
#endif
| true |
f76e64ae4009a2e5182e0ec5cc46cb237a862bef | C++ | ArthurGoodman/violet | /source/ast/nodes/variabledefinitionnode.cpp | UTF-8 | 924 | 2.8125 | 3 | [] | no_license | #include "variabledefinitionnode.h"
#include "icontext.h"
#include "common.h"
VariableDefinitionNode::VariableDefinitionNode(Variant::Type type, list<pair<string, Node *>> definitions, bool isConst)
: type(type), definitions(definitions), isConst(isConst) {
}
VariableDefinitionNode::~VariableDefinitionNode() {
for (auto &def : definitions)
delete def.second;
}
Variant VariableDefinitionNode::eval(IContext *context) {
for (auto &def : definitions) {
if (context->hasLocal(def.first)) {
context->error("variable '" + def.first + "' is already defined");
return context->getVoid();
}
Variant value = def.second ? def.second->eval(context) : context->constant(0);
if (type != Variant::Undefined)
value = context->cast(value, type);
context->defineLocal(def.first, value, isConst);
}
return context->getVoid();
}
| true |
6921e1d6dc7135b588c3437e7a01fd0a0b30f9be | C++ | BekzhanKassenov/olymp | /acmp.ru/101...200/192/192.cpp | UTF-8 | 774 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;
int n, p[10010];
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &p[i]);
}
int pos = n - 1;
while (pos >= 0 && p[pos] > p[pos + 1]) {
pos--;
}
if (pos == 0) {
for (int i = 1; i <= n; i++) {
printf("%d%c", i, " \n"[i == n]);
}
return 0;
}
int pos1 = n;
while (p[pos] > p[pos1]) {
pos1--;
}
swap(p[pos], p[pos1]);
reverse(p + pos + 1, p + n + 1);
for (int i = 1; i <= n; i++) {
printf("%d%c", p[i], " \n"[i == n]);
}
return 0;
}
| true |
1f77fdbd39057ca36420e2b2576bf2ec4eee3d09 | C++ | spfrood/CPP-references | /Chapters/Assignment_11/Menu_Assn_5_Ch_13_Ch_14/Worker.cpp | UTF-8 | 1,064 | 3.171875 | 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: Worker.cpp
* Author: scott_r_parker
*
* Created on May 3, 2017, 10:16 AM
*/
#include "Worker.h"
Worker::Worker() {
name="";
idNum=0;
dept="";
postn="";
}
void Worker::setVals() {
string n, d, p;
int num;
cout<<"Enter the employee name: ";
getline(cin, n);
cout<<"Enter the employee ID number: ";
cin>>num;
cin.ignore(256, '\n');
cout<<"Enter the department: ";
getline(cin, d);
cout<<"Enter the position: ";
getline(cin, p);
name=n;
idNum=num;
dept=d;
postn=p;
}
void Worker::setVals(string n, int num, string d, string p) {
name=n;
idNum=num;
dept=d;
postn=p;
}
void Worker::dWorker () {
cout<<"Employee name: "<<getName()<<endl;
cout<<"ID Number: "<<getNum()<<endl;
cout<<"Department: "<<getDept()<<endl;
cout<<"Position: "<<getPost()<<endl;
} | true |
cb64c13b011ae35a26d39a766007de87be022bfa | C++ | FrizzleFur/iOSDevLevelingUp | /ReadingBooks/《Objective-C 高级编程》学习笔记/ProObjcBookDemo/BlockDemo/BlockImplementaionDemo/BlockImplementaionDemo/main6.cpp | UTF-8 | 2,022 | 2.59375 | 3 | [] | no_license |
struct __block_impl {
void *isa;
int Flags;
int Reserved;
void *FuncPtr;
};
//_______________________________ 作为全局变量的 block _______________________________________________
struct __globalBlcok_block_impl_0 {
struct __block_impl impl;
struct __globalBlcok_block_desc_0* Desc;
__globalBlcok_block_impl_0(void *fp, struct __globalBlcok_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteGlobalBlock; // 全局变量的 block 属于_NSConcreteGlobalBlock 类
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static void __globalBlcok_block_func_0(struct __globalBlcok_block_impl_0 *__cself) {
}
static struct __globalBlcok_block_desc_0 {
size_t reserved;
size_t Block_size;
} __globalBlcok_block_desc_0_DATA = { 0, sizeof(struct __globalBlcok_block_impl_0)};
static __globalBlcok_block_impl_0 __global_globalBlcok_block_impl_0((void *)__globalBlcok_block_func_0, &__globalBlcok_block_desc_0_DATA);
// 全局变量 block 的转换
void(*globalBlcok)() = ((void (*)())&__global_globalBlcok_block_impl_0);
//_______________________________ 作为局部变量的 block ,但是不捕获自动变量_______________________________________________
struct __main_block_impl_0 {
struct __block_impl impl;
struct __main_block_desc_0* Desc;
__main_block_impl_0(void *fp, struct __main_block_desc_0 *desc, int flags=0) {
impl.isa = &_NSConcreteStackBlock;
impl.Flags = flags;
impl.FuncPtr = fp;
Desc = desc;
}
};
static int __main_block_func_0(struct __main_block_impl_0 *__cself, int a) {
return a;
}
static struct __main_block_desc_0 {
size_t reserved;
size_t Block_size;
} __main_block_desc_0_DATA = { 0, sizeof(struct __main_block_impl_0)};
int main() {
int (*stackBlock)(int) = ((int (*)(int))&__main_block_impl_0((void *)__main_block_func_0, &__main_block_desc_0_DATA));
((int (*)(__block_impl *, int))((__block_impl *)stackBlock)->FuncPtr)((__block_impl *)stackBlock, 1);
return 0;
}
| true |
12bd64760c4905374f3cf773412706b1171a5ae3 | C++ | rgsouza/MultimediaBox | /cpp/Groupe.cpp | UTF-8 | 860 | 3.390625 | 3 | [] | no_license | //
// Groupe.cpp for create a group of multimedia files.
// Rayanne Souza - 10/2015
//
#include "Groupe.h"
Groupe::Groupe( const string name, ptr_multimedia object):list()
{
this->name = name;
this->push_back(object);
}
Groupe::Groupe():list(){ this->name = "Undefined name"; }
Groupe::~Groupe()
{
cout<<"Object Groupe is destroyed"<<endl<<endl;
}
string Groupe::get_GroupeName() const
{
return this->name;
}
void Groupe :: set_GroupeName( const string name )
{
this->name = name;
}
void Groupe::output(ostream &cout) const
{
cout<<"-----------------"<<this->get_GroupeName()<<"-----------------"<<endl<<endl;
// Traverse the list and call the method output from multimedia objects.
for (list<ptr_multimedia>::const_iterator i = this->begin(); i != this->end(); ++i)
{
(*i)->output(cout);
}
}
| true |
1ef8ab11dc0f0d9f103eb67223678a6b172f7323 | C++ | jmsplmr/CS345_week10_PageReplacementLab | /prSecond.h | UTF-8 | 1,679 | 2.625 | 3 | [] | no_license | /***********************************************************************
* Component:
* Page Replacement Second Chance
* Author:
* James Palmer
* Summary:
* This is the DERRIVED class to implement Second
************************************************************************/
#pragma once
#include "pr.h" // for the PageReplacementAlgorithm base-class
/****************************************************
* Second Chance
* The least-recently-used Approximation page replacement
* algorithm known as Second Chance
***************************************************/
class PageReplacementSecond : public PageReplacementAlgorithm
{
public:
/*****************************************************
* CONSTRUCTOR
* initialize the data structures specific to Second
*****************************************************/
PageReplacementSecond (int);
/****************************************************
* RUN
* Implement the LRU algorithm here. Thus function will get
* called several times, each time requesting "pageNumber"
* from memory. You are to assign that page to a "pageFrame"
* and then call the base-class to record the results.
***************************************************/
void run (int);
private:
//////////////////// YOUR CODE HERE //////////////////////
std::vector<int> references;
int page;
void findVictim ();
bool pageInFrameAndReferenced (int);
void setPageInPageFrame (int);
void advancePageRefSlot ();
void addReferenceToPage (int);
void clearReferenceToSlot ();
bool pagesHaveReferences ();
bool isPageInFrame (int, int);
};
| true |
9991574afafbd85e6bd0431f3ca2303e39c16cab | C++ | Daguerreo/Azul | /image.h | UTF-8 | 360 | 2.53125 | 3 | [] | no_license | #ifndef IMAGE_H
#define IMAGE_H
#include <QImage>
#include <opencv2/core/core.hpp>
using namespace cv;
class Image
{
public:
Image();
~Image();
Mat getMat() const;
void setMat(const Mat &image);
QImage getQImage() const;
void setQImage(const QImage &image);
private:
Mat mMatImage;
QImage mQImage;
};
#endif // IMAGE_H
| true |
caa7d908c30594f62048bb25de8afe13d138c04a | C++ | saw1998/Computional_Geometry | /src/computational_geometry/circle.cpp | UTF-8 | 1,294 | 3.15625 | 3 | [] | no_license | //
// Created by sachin on 14/01/20.
//
#include <cmath>
#include "circle.h"
#include "point.h"
namespace {
#define EPS 1e-9
#define PI std::acos(-1)
}
namespace cg {
template<typename T>
circle<T>::circle(point<T> _p, double rad) {
p = _p;
r = rad;
}
template<typename T>
circle<T>::circle(T x, T y, double rad) {
point<T> pt(x, y);
circle(pt, rad);
}
template<typename T>
circle<T>::circle() {
p = point<T>();
r = 1;
}
template<typename T>
bool circle<T>::inside_circle(point<T> &pt) const {
double d = this->p.dist(pt);
return (d < this->r);
}
template<typename T>
bool circle<T>::on_circle(point<T> &pt) const{
double d = this->p.dist(pt);
return (d - this->r) < EPS;
}
template<typename T>
bool circle<T>::out_circle(point<T> &pt) const{
double d = this->p.dist(pt);
return (d > this->r);
}
template<typename T>
double circle<T>::area() const{
return (PI * this->r * this->r);
}
template<typename T>
double circle<T>::peri() const{
return (PI * this->r * 2);
}
template<typename T>
point<T> circle<T>::centre() const {
return (this->p);
}
template<typename T>
point<T> circle<T>::center() const {
return (this->p);
}
template<typename T>
double circle<T>::radius() const {
return (this->r);
}
} //namespace | true |
b6e91f3b432843f16e7d22c7d54fae7c0332ea07 | C++ | marioanloru/Fundamentos-de-la-Programacion | /sesion13/ejercicio4.cpp | UTF-8 | 7,875 | 3.828125 | 4 | [] | no_license | /* EJERCICIO4: Programa que realiza estadísticas sobre datos meteorológicos
*
* Autor: Mario Antonio López Ruiz
* 1ºD
*/
#include <iostream>
using namespace std;
class Meteo{
private:
static const int FILAS = 90;
static const int COLUMNAS = 3;
int datos[FILAS][COLUMNAS];
int amplitudes[FILAS];
int util_fil;
int util_col;
int util_amplitudes;
public:
Meteo(){
util_fil = 0;
util_col = 0;
util_amplitudes = 0;
}
//Rellena una fila con datos
void AniadeMedida(int fila, int columna, int dato){
datos[fila][columna] = dato;
if(columna == 2)
util_fil++;
}
//Calcula la amplitud de temperaturas de un dia
int CalculaAmplitud(int fila){
int amplitud;
if(fila <= util_fil)//util_fil = 90
amplitud = datos[fila][1] - datos[fila][0];//Segunda columna menos la primera
else
cout << "\nLa fila introducida no es válida. " << endl;
return amplitud;
}
//rellena el vector de amplitudes
void CalculaAmplitudes(){
for(int i = 0; i < FILAS; i++){
amplitudes[util_amplitudes] = CalculaAmplitud(i);
util_amplitudes++;
}
}
//Muestra la matriz de datos
void MuestraMatriz(){
for(int i = 0; i < FILAS; i++){
for(int j = 0; j < COLUMNAS; j++){
cout << datos[i][j] << " ";
}
cout << endl;
}
}
//Muestra el vector de amplitudes
void MuestraAmplitudes(){
for(int i = 0; i < util_amplitudes; i++)
cout << amplitudes[i] << " ";
}
//Valor medio mensual de una columna(dato)
int MediaMensual(int columna, int inicio, int fin){
int media, suma = 0, i ;
for(i = inicio; i < fin; i++){
suma += datos[i][columna];
}
media = suma/i;
return media;
}
//Valor medio mensual de amplitud
int MediaMensualAmplitud(int inicio, int fin){
int media, suma = 0, i;
for(i = inicio; i < fin; i++){
suma += amplitudes[i];
}
media = suma/i;
return media;
}
//Valor maximo mensual de una columna(dato)
int MaxMensual(int columna, int inicio, int fin){
int maximo = -9999, i=0;
for(i = inicio; i < fin; i++){
if(datos[i][columna] > maximo)
maximo = datos[i][columna];
}
return maximo;
}
//Valor maximo mensual de una columna(dato)
int MaxMensualAmplitud(int inicio, int fin){
int maximo = -9999, i=0;
for(i = inicio; i < fin; i++){
if(amplitudes[i] > maximo)
maximo = amplitudes[i];
}
return maximo;
}
//Valor minimo mensual de una columna(dato)
int MinMensual(int columna, int inicio, int fin){
int minimo = 9999, i=0;
for(i = inicio; i < fin; i++){
if(datos[i][columna] < minimo)
minimo = datos[i][columna];
}
return minimo;
}
//Valor maximo mensual de una columna(dato)
int MinMensualAmplitud(int inicio, int fin){
int min = 9999, i=0;
for(i = inicio; i < fin; i++){
if(amplitudes[i] < min)
min = amplitudes[i];
}
return min;
}
};
int main(){
Meteo meteo;
const int COTA1 = 0, COTA2 = 30, COTA3 = 60, COTA4 = 90;
const int FILAS = 90, COLUMNAS = 3;
double amplitudes[FILAS], util_amplitud = 0;
int temperatura7, temperatura13, precipitaciones, amplitud;
int dato, prueba;
int valor_medio_temp7_1, valor_medio_temp7_2, valor_medio_temp7_3;
int valor_medio_temp13_1, valor_medio_temp13_2, valor_medio_temp13_3;
int valor_medio_prec_1, valor_medio_prec_2, valor_medio_prec_3;
int valor_medio_ampl_1, valor_medio_ampl_2, valor_medio_ampl_3;
int max_temp7_1, max_temp7_2, max_temp7_3;
int max_temp13_1, max_temp13_2, max_temp13_3;
int max_prec_1, max_prec_2, max_prec_3;
int max_ampl_1, max_ampl_2, max_ampl_3;
int min_temp7_1, min_temp7_2, min_temp7_3;
int min_temp13_1, min_temp13_2, min_temp13_3;
int min_prec_1, min_prec_2, min_prec_3;
int min_ampl_1, min_ampl_2, min_ampl_3;
cout << "Introduzca los datos:(temp 07:00, temp 13:00, precipitaciones) ";
for(int i = 0; i < 90; i++){
for(int j = 0; j < 3; j++){
cin >> dato;
meteo.AniadeMedida(i,j, dato);
}
amplitudes[i] = meteo.CalculaAmplitud(i);
util_amplitud++;
}
meteo.CalculaAmplitudes();
//meteo.MuestraAmplitudes();
//meteo.MuestraMatriz();
//columna = 0 -> temperatura7 | columna = 1 -> temperatura13 | columna = 2 -> precipitaciones
//Calculo valores medios mensuales para cada medida
valor_medio_temp7_1 = meteo.MediaMensual(0,COTA1, COTA2);
valor_medio_temp7_2 = meteo.MediaMensual(0,COTA2, COTA3);
valor_medio_temp7_3 = meteo.MediaMensual(0,COTA3, COTA4);
valor_medio_temp13_1 = meteo.MediaMensual(1,COTA1, COTA2);
valor_medio_temp13_2 = meteo.MediaMensual(1,COTA2, COTA3);
valor_medio_temp13_3 = meteo.MediaMensual(1,COTA3, COTA4);
valor_medio_prec_1 = meteo.MediaMensual(2,COTA1, COTA2);
valor_medio_prec_2 = meteo.MediaMensual(2,COTA2, COTA3);
valor_medio_prec_3 = meteo.MediaMensual(2,COTA3, COTA4);
valor_medio_ampl_1 = meteo.MediaMensualAmplitud(COTA1, COTA2);
valor_medio_ampl_2 = meteo.MediaMensualAmplitud(COTA2, COTA3);
valor_medio_ampl_3 = meteo.MediaMensualAmplitud(COTA3, COTA4);
//Calculo maximos mensuales para cada medida
max_temp7_1 = meteo.MaxMensual(0,COTA1, COTA2);
max_temp7_2 = meteo.MaxMensual(0,COTA2, COTA3);
max_temp7_3 = meteo.MaxMensual(0,COTA3, COTA4);
max_temp13_1 = meteo.MaxMensual(1,COTA1, COTA2);
max_temp13_2 = meteo.MaxMensual(1,COTA2, COTA3);
max_temp13_3 = meteo.MaxMensual(1,COTA3, COTA4);
max_prec_1 = meteo.MaxMensual(2,COTA1, COTA2);
max_prec_2 = meteo.MaxMensual(2,COTA2, COTA3);
max_prec_3 = meteo.MaxMensual(2,COTA3, COTA4);
max_ampl_1 = meteo.MaxMensualAmplitud(COTA1, COTA2);
max_ampl_2 = meteo.MaxMensualAmplitud(COTA2, COTA3);
max_ampl_3 = meteo.MaxMensualAmplitud(COTA3, COTA4);
//Calculo minimos mensuales para cada medida
min_temp7_1 = meteo.MinMensual(0,COTA1, COTA2);
min_temp7_2 = meteo.MinMensual(0,COTA2, COTA3);
min_temp7_3 = meteo.MinMensual(0,COTA3, COTA4);
min_temp13_1 = meteo.MinMensual(1,COTA1, COTA2);
min_temp13_2 = meteo.MinMensual(1,COTA2, COTA3);
min_temp13_3 = meteo.MinMensual(1,COTA3, COTA4);
min_prec_1 = meteo.MinMensual(2,COTA1, COTA2);
min_prec_2 = meteo.MinMensual(2,COTA2, COTA3);
min_prec_3 = meteo.MinMensual(2,COTA3, COTA4);
min_ampl_1 = meteo.MinMensualAmplitud(COTA1, COTA2);
min_ampl_2 = meteo.MinMensualAmplitud(COTA2, COTA3);
min_ampl_3 = meteo.MinMensualAmplitud(COTA3, COTA4);
cout << "\nValores medios de los 3 meses para la temperatura a las 07:00: " << valor_medio_temp7_1 << " " << valor_medio_temp7_1 << " " << valor_medio_temp7_1;
cout << "\nValores medios de los 3 meses para la temperatura a las 13:00: " << valor_medio_temp13_1 << " " << valor_medio_temp7_1 << " " << valor_medio_temp7_1;
cout << "\nValores medios de los 3 meses para las precipitaciones: " << valor_medio_prec_1 << " " << valor_medio_prec_2 << " " << valor_medio_prec_3;
cout << "\nValores medios de la amplitud: " << valor_medio_ampl_1 << " " << valor_medio_ampl_2 << " " << valor_medio_ampl_3 << endl;
cout << "\nValores maximos para la temperatura a las 07:00: " << max_temp7_1 << " " << max_temp7_2 << " " << max_temp7_3;
cout << "\nValores maximos para la temperatura a las 13:00: " << max_temp13_1 << " " << max_temp13_2 << " " << max_temp13_3;
cout << "\nValores maximos para las precipitaciones: " << max_prec_1 << " " << max_prec_2 << " " << max_prec_3;
cout << "\nValores maximos para la amplitud: " << max_ampl_1 << " " << max_ampl_2 << " " << max_ampl_3 << endl;
cout << "\nValores minimos para la temperatura a las 07:00: " << min_temp7_1 << " " << min_temp7_2 << " " << min_temp7_3;
cout << "\nValores minimos para la temperatura a las 13:00: " << min_temp13_1 << " " << min_temp13_2 << " " << min_temp13_3;
cout << "\nValores minimos para las precipitaciones: " << min_prec_1 << " " << min_prec_2 << " " << min_prec_3;
cout << "\nValores minimos para la amplitud: " << min_ampl_1 << " " << min_ampl_2 << " " << min_ampl_3 << endl;
}
| true |
94491d32b027bc3ec969d622bf0fc68f57414eb1 | C++ | abhishek09091/competitive-programming | /Company Wise Practice/Goldman Sachs/special-stack.cpp | UTF-8 | 1,575 | 3.71875 | 4 | [] | no_license | /******
https://www.geeksforgeeks.org/design-and-implement-special-stack-data-structure/
https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/
*******/
#include<iostream>
#include<stack>
using namespace std;
void push(int a);
bool isFull(int n);
bool isEmpty();
int pop();
int getMin();
//This is the STL stack (http://quiz.geeksforgeeks.org/stack-container-adaptors-the-c-standard-template-library-stl/).
stack<int> s;
int main(){
int t;
cin>>t;
while(t--){
int n,a;
cin>>n;
while(!isEmpty()){
pop();
}
while(!isFull(n)){
cin>>a;
push(a);
}
cout<<getMin()<<endl;
}
}
/*This is a function problem.You only need to complete the function given below*/
/*Complete the function(s) below*/
int minElem;
void push(int a){
//add code here.
if(s.empty()){
minElem = a;
s.push(a);
return;
}
if(a < minElem){
s.push(2*a - minElem);
minElem = a;
return;
}
s.push(a);
}
bool isFull(int n){
//add code here.
if(s.size() == n){
return true;
}
return false;
}
bool isEmpty(){
//add code here.
if(s.size() == 0){
return true;
}
return false;
}
int pop(){
//add code here.
if(s.empty()){
return -1;
}
int t = s.top();
s.pop();
if(t < minElem){
minElem = 2 * minElem - t;
return minElem;
}else{
return t;
}
}
int getMin(){
//add code here.
return minElem;
} | true |
41118c4d4b171640386c400047fe55bc8b330b5a | C++ | adams-jon/ja1870341-Projects | /Adams, Jonathan_Proj1_42450_A&Pver2/main.cpp | UTF-8 | 44,125 | 2.890625 | 3 | [] | no_license | /*
* File: main.cpp
* Author: Adams, Jonathan
*
* Created on April 19th, 2014 @ 09:30 AM
*/
#include <iostream>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <fstream>
using namespace std;
//Global Constants
const int asize=4;
//Function Prototypes
void fillary (int[], int, int, int);
float convert (int, float);
void startNE (int, float &, float &);
void startIN (int, float &, float &);
void startFO (int, float &, float &);
void prinTbl (int[], int &, unsigned short &);
void prinAc (float[asize][3], int, float &, float &, short, short, float);
//Execution
int main(int argc, char** argv) {
//Declare Variables
unsigned short choose;
char exit;
//-- 1 Decimal point is sufficient for all calculations
//in this program
cout<<fixed<<setprecision(1)<<showpoint;
//Welcome statement to not be looped
cout<<"Welcome to the Aerospace and Powerplant Maintenance Helper."<<endl;
//Prompt user for number of problem to execute
cout<<endl;
cout<<endl;
do { //MENU DO LOOP BEGIN
cout<<"Choose from the following list"<<endl;
cout<<"1. Re-Calculate Longitudinal CG for new component"<<endl;
cout<<"2. Longitudinal CG Practice"<<endl;
cout<<"3. Load Cargo Simulation Cessna 340A Acft"<<endl;
cout<<"4. Print Torque Table"<<endl;
cout<<"5. Exit Program - All"<<endl;
cin>>choose;
//Catch invalid input choose
while (!(choose>=1 && choose<=5)) {
cin.clear();
cin.ignore();
cout<<"Not an option! Please re-enter: "<<endl;
cin>>choose;
}
//End catch invalid input choose
//Utilize switch to implement the menu
switch(choose) { //Begin switch choose
case 1:{
///////////////////////////////Component Calculator/////////////////////////////
cout<<"Program 1: New Component Longitudinal CG Calculator";
cout<<endl;
do {
//START CODE//////////////////////////////
//Prompt
cout<<setfill('-')<<setw(40)<<"-"<<endl;
cout<<" Welcome to Longitudinal CG Calculator!"<<endl;
cout<<setfill('-')<<setw(40)<<"-"<<endl;
cout<<setfill('-');
cout<<"This CG calculator is meant to aid you in recalculating \n";
cout<<"aircraft empty weight CG when you remove, add or replace \n";
cout<<"a permanent piece of equipment, as defined in the \n";
cout<<"Aircraft Equipment List."<<endl<<endl;
//Prompt for user to select ACFT to modify, or make their own
cout<<"Select which option you would prefer:"<<endl;
cout<<"1. Enter my own aircraft data"<<endl;
cout<<"2. Cessna 172M Profile"<<endl;
//Menu 1 Input Variable
unsigned short menu1;
//User input for menu1
cin>>menu1;
//Catch invalid input menu1
while (!(menu1>=1&&menu1<=2)) {
cin.clear();
cin.ignore();
cout<<"Not an option! Please re-enter: "<<endl;
cin>>menu1;
}
//Catch invalid input menu1
switch (menu1) { /////Menu1 Switch start
//Variables declared for CG calculations
//Planning to turn this into a function later
//Basic Aircraft Weight
float acftW;
//Aircraft moment comes from taking all aircraft longitudinal
//station numbers (in inches) and multiplying their weight by
//their ARM (distance from the DATUM)
float acftMom;
//CG is calculated by dividing aircraft moment by aircraft
//weight. The purpose here is to determine Basic Empty CG.
//So fuel, cargo and passengers are considered to be at 0.
float acftCG;
//Place holder for the weight of an item being removed
float itemOld;
//The location of the item being removed, in reference to
//manufacture specified DATUM point.
float armOld;
//Weight of new item
float itemNew;
//Location of new item, if modified. (EX. longer starter)
float armNew;
//Menu character
char armChoi;
case 1:{
//Retrieve Aircraft Weight
cout<<"Please enter aircraft empty weight, in lbs\n";
cout<<"to 1/10 of a lb accuracy. (xxxx.x)\n";
cout<<"NOTE: Info on acft Type Certificate Data Sheet\n";
cin>>acftW;
//Retrieve Aircraft Moment
cout<<"Please enter aircraft empty moment,\n";
cout<<"to 1/10 accuracy. (xxxx.x)\n";
cout<<"NOTE: Info on acft Type Certificate Data Sheet\n";
cin>>acftMom;
//Calculate CG
acftCG=(acftMom/acftW);
cout<<endl;
//Display CG
cout<<"Current CG is "<<acftCG<<"."<<endl;
//Ask what user wants to do to aircraft
cout<<"Are you adding, removing or replacing an item?\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Type exit to leave or reset CG calculator."<<endl;
string opt1;
cin>>opt1;
do {
//Error catching loop opt1
while (opt1!="removing"&&opt1!="adding"&&opt1!=
"replacing"&&opt1!="exit"){
cin.clear();
cin.ignore();
cout<<"Invalid input, re-enter:"<<endl<<endl;
cout<<"Please type one of the following options: \n";
cout<<"removing \nadding \nreplacing\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Or type exit to leave or reset CG calculator"<<endl;
cin>>opt1;
cout<<endl<<endl;
}
//End error catching loop opt1
//Removing option will only remove an item.
//COUT statements self explanatory
if (opt1=="removing") {
cout<<"You're removing an item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cout<<"of item being removed"<<endl;
cin>>itemNew;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
//Error catch statement for FWD & AWF
//Important that the user has to input this
//because it sets the ARM to positive or negative
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
//end error statement
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
//set ARM to negative if item was FWD of datum
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
//Calculations & Display
acftW=(acftW)-(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom-(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
//Adding an item
if (opt1=="adding") {
cout<<"You're adding an item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cout<<"of item being added"<<endl;
cin>>itemNew;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
//Error catch statement ARM location
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
//End error catch statement
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
//Set ARM to negative if item FWD of datum
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
//Calculations & display
acftW=(acftW)+(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom+(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
//Replacing an item
if (opt1=="replacing") {
cout<<"You're replacing an item"<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
//Error catching statement
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
//End error catching statement
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
//Set ARM to negative if FWD of Datum
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
cout<<"Was the ARM moved forward or aft?\n";
cout<<"Y for Yes, any other key for No:"<<endl;
cin>>armChoi;
armNew=armOld;
if (armChoi=='y'||armChoi=='Y') {
do {
cout<<"Forward, or Aft?"<<endl;
cout<<"F for FWD, A for AFT"<<endl;
cin>>armChoi;
if (armChoi=='f'||armChoi=='F') {
cout<<"Enter distance moved in inches\n";
cin>>armNew;
armOld=armOld-armNew;
}
else if (armChoi=='a'||armChoi=='A') {
cout<<"Enter distance moved in inches\n";
cin>>armNew;
armOld=armOld+armNew;
}
else {
cout<<"Error.";
}
} while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A');
}
armOld=armNew;
cout<<"Enter the item's original weight"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cin>>itemOld;
acftMom=(acftMom)+(-itemOld*armOld)+.01;
cout<<"Acft mom="<<acftMom<<endl;
cout<<"Enter weight of new item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cin>>itemNew;
acftW=(acftW-itemOld)+(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom+(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
if (opt1!="exit") {
cout<<"Are you adding, removing or replacing another item?"<<endl;
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Type exit to leave or reset CG calculator."<<endl;
cin>>opt1;
while (opt1!="removing"&&opt1!="adding"&&opt1!=
"replacing"&&opt1!="exit"){
cin.clear();
cin.ignore();
cout<<"Invalid input, re-enter:"<<endl<<endl;
cout<<"Please type one of the following options: \n";
cout<<"removing \nadding \nreplacing\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Or type exit to leave or reset CG calculator"<<endl;
cin>>opt1;
cout<<endl<<endl; }
}
} while (opt1!="exit");
break;
} // end case 1
case 2:{
//Retrieve Aircraft Weight
cout<<"Cessna 172M Basic Empty Weight: "<<endl;
acftW=1588;
cout<<acftW<<" lbs"<<endl;
//Retrieve Aircraft Moment
cout<<"Cessna 172M Basic Empty Moment: "<<endl;
acftMom=61316.6;
cout<<acftMom<<endl;
//Calculate CG
cout<<"NOTE: Cessna 172M DATUM is located on the\n";
cout<<"Front Face of Cockpit Firewall"<<endl;
acftCG=(acftMom/acftW);
cout<<endl;
cout<<"Current CG is "<<acftCG<<"."<<endl;
cout<<"Are you adding, removing or replacing an item?\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Type exit to leave or reset CG calculator."<<endl;
string opt1;
cin>>opt1;
do {
//Error catching loop opt1
while (opt1!="removing"&&opt1!="adding"&&opt1!=
"replacing"&&opt1!="exit"){
cin.clear();
cin.ignore();
cout<<"Invalid input, re-enter:"<<endl<<endl;
cout<<"Please type one of the following options: \n";
cout<<"removing \nadding \nreplacing\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Or type exit to leave or reset CG calculator"<<endl;
cin>>opt1;
cout<<endl<<endl;
}
//End error catching loop opt1
if (opt1=="removing") {
cout<<"You're removing an item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cout<<"of item being removed"<<endl;
cin>>itemNew;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
acftW=(acftW)-(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom-(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
if (opt1=="adding") {
cout<<"You're adding an item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cout<<"of item being added"<<endl;
cin>>itemNew;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
acftW=(acftW)+(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom+(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
if (opt1=="replacing") {
cout<<"You're replacing an item"<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A') {
cout<<"Error! Invalid Input!"<<endl<<endl;
cout<<"Determining ARM: Is the item located\n";
cout<<"FWD or AFT of Acft Datum?"<<endl;
cout<<"F for FWD, A for AFT: ";
cin>>armChoi;
}
cout<<"Enter ARM (distance from Datum in inches)\n";
cout<<"of item being removed, to 1/10th of an inch"<<endl;
cin>>armOld;
if (armChoi=='f'||armChoi=='F') armOld=(armOld*-1);
cout<<"Was the ARM moved forward or aft?\n";
cout<<"Y for Yes, any other key for No:"<<endl;
cin>>armChoi;
armNew=armOld;
if (armChoi=='y'||armChoi=='Y') {
do {
cout<<"Forward, or Aft?"<<endl;
cout<<"F for FWD, A for AFT"<<endl;
cin>>armChoi;
if (armChoi=='f'||armChoi=='F') {
cout<<"Enter distance moved in inches\n";
cin>>armNew;
armOld=armOld-armNew;
}
else if (armChoi=='a'||armChoi=='A') {
cout<<"Enter distance moved in inches\n";
cin>>armNew;
armOld=armOld+armNew;
}
else {
cout<<"Error.";
}
} while (armChoi!='f'&&armChoi!='F'
&&armChoi!='a'&&armChoi!='A');
}
armOld=armNew;
cout<<"Enter the item's original weight"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cin>>itemOld;
acftMom=(acftMom)+(-itemOld*armOld)+.01;
cout<<"Acft mom="<<acftMom<<endl;
cout<<"Enter weight of new item"<<endl;
cout<<"Enter weight, in lbs to 1/10 lb accuracy\n";
cin>>itemNew;
acftW=(acftW-itemOld)+(itemNew)+.01;
cout<<setw(20)<<left<<"New Acft Weight: ";
cout<<setw(20)<<right<<acftW<<endl;
acftMom=acftMom+(itemNew*armOld)+.01;
cout<<setw(20)<<left<<"New Acft Mom: ";
cout<<setw(20)<<right<<acftMom<<endl;
acftCG=(acftMom/acftW)+.01;
cout<<setw(20)<<left<<"New Acft CG is: ";
cout<<setw(20)<<right<<acftCG<<endl<<endl;
}
if (opt1!="exit") {
cout<<"Are you adding, removing or replacing another item?"<<endl;
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Type exit to leave or reset CG calculator."<<endl;
cin>>opt1;
while (opt1!="removing"&&opt1!="adding"&&opt1!=
"replacing"&&opt1!="exit"){
cin.clear();
cin.ignore();
cout<<"Invalid input, re-enter:"<<endl<<endl;
cout<<"Please type one of the following options: \n";
cout<<"removing \nadding \nreplacing\n";
cout<<"Type in option above in lowercase letters"<<endl;
cout<<"Or type exit to leave or reset CG calculator"<<endl;
cin>>opt1;
cout<<endl<<endl; }
}
} while (opt1!="exit");
}
} ////////Menu 1 Switch End
//FINISH CODE/////////////////////////////
cout<<"\n\n";
cout<<"CG Calculator is reset."<<endl;
cout<<"Would you like to run calculator again?"<<endl;
cout<<"Type N for No and to return to main menu."<<endl;
cout<<"Press any other key to run calculator again."<<endl;
cin>>exit;
} while ((exit!='n')&&(exit!='N')); /////////do while loop
cout<<endl;
cout<<endl;
cout<<"End Program 1"<<endl;break;
} //End option 1
case 2:{
////////////////////////////////PROBLEM 2///////////////////////////////////////
cout<<"Welcome to CG Practice.";
cout<<endl;
do {
//START CODE//////////////////////////////
//Randomly choose a sequence start
float acftW=0; //weight
float acftMom=0; //moment
float acftCG=0; //mom/weight
float testVal=0; //user input of new CG
unsigned short itemW=0; //weight of new item
unsigned short itemArm=0; //location of new item
srand(static_cast<unsigned int>(time(0))); // time seed for rand
cout<<"Aircraft Weight: "<<endl; //display weight of 1000 to 1049
acftW=rand()%900+2000;
cout<<acftW<<" lbs"<<endl;
cout<<"Aircraft Moment: "<<endl; //display mom of 30000 to 30999
acftMom=rand()%1000+60000;
cout<<acftMom<<endl;
cout<<"Starting CG is: "<<endl;
cout<<acftMom/acftW<<endl<<endl;
itemW=rand()%9+150; //display starting CG and create itemW 20-29
cout<<"Item added weighs:"<<endl;
cout<<itemW<<" lbs"<<endl;
itemArm=rand()%9+50; //display item location 2-11
cout<<"Located "<<itemArm<<" inches aft of Datum"<<endl;
cout<<"Enter new aircraft CG: (to 1 decimal point)"<<endl;
//User inputs their calculation
cin>>testVal;
//Computer calculation for new CG
acftMom=acftMom+(itemW*itemArm); //Add new items moment
acftW=acftW+(itemW); // add new items weight
acftCG=acftMom/acftW; //new cg
cout<<"Correct new CG is: "<<endl; //output to user
cout<<acftCG<<endl;
//FINISH CODE/////////////////////////////
cout<<"\n\n";
cout<<"Would you like to run again? N for No."<<endl;
cout<<"Press any other key to run again."<<endl;
cin>>exit;
} while ((exit!='n')&&(exit!='N'));
cout<<endl;
cout<<endl;
cout<<"End problem 2"<<endl;break;
} //End option 2
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
case 3: {
float acftMom=0, acftW=0, carW=0;
float acftCar[4][3]={{0,0,0},{0,0,0},{0,0,0},{0,0,0}};
int size=4;
short row=-1, col=-1;
char choice, rowCho;
ifstream fin;
fin.open("C340.dat");
fin>>acftW>>acftMom;
cout<<"Cargo Loading Simulation"<<endl;
cout<<"A Cessna 340's Data has been loaded for "<<endl;
cout<<"the simulation."<<endl;
cout<<"In the future, you will be able to load your own"<<endl;
cout<<"aircraft profile from a file"<<endl<<endl;
cout<<"There are 12 Cargo Locations on the acft: "<<endl<<endl;
prinAc(acftCar, size, acftW, acftMom, row, col, carW);
do {
//Reset inputs
row=-1, col=-1, carW=0;
//Print out current state of the array
//Fetch row #
cout<<"What row would you like to load cargo onto?"<<endl;
do {
cout<<"A, B, C or D?"<<endl;
cin>>rowCho;
if (rowCho=='A'||rowCho=='a') row=0;
else if (rowCho=='B'||rowCho=='b') row=1;
else if (rowCho=='C'||rowCho=='c') row=2;
else if (rowCho=='D'||rowCho=='d') row=3;
else cout<<"Invalid Choice!"<<endl;
} while (rowCho!='A'&&rowCho!='a'&&rowCho!='B'&&rowCho!='b'&&
rowCho!='C'&&rowCho!='c'&&rowCho!='D'&&rowCho!='d');
//Fetch column #
cout<<"Station 1, 2 or 3? Enter number for station (1-3)"<<endl;
cin>>col;
while (col>3||col<0) {
cout<<"Invalid input. Input 1, 2 or 3!"<<endl;
cin>>col;
}
//Set column # to appropriate index for array
col=(col-1);
//Now ask for weight
cout<<"Enter weight of cargo: "<<endl;
cin>>carW;
prinAc(acftCar, size, acftW, acftMom, row, col, carW);
//Run again??
cout<<"Would you like to load more cargo?"<<endl;
cout<<"Y for Yes, N for No"<<endl;
cin>>choice;
} while ((choice!='n')&&(choice!='N'));
fin.close();
//Return to menu
break;
}
////////////////////////////////////////////////////////////////////////////////
//This is primarily just to practice with arrays
case 4: {
//Declare an array that can accommodate up to 1000 units of int
//I know a vector would be better here, but I am more comfortable
//with arrays for now.
int tableS[1000], increm=1, size, startV;
//tableS is the maximum size of the array
//increm is how many values the user would like to
//increment the rows.
//size is how large the user would like to make the array, up to 1000
//startV is the value of the first row, first column
unsigned short dataC;
//dataC is a user menu choice holder
cout<<"Print A Custom Shop Use Torque Value Conversion Table"<<endl<<endl;
cout<<"User can print a table up to 1000 values"<<endl;
cout<<"User chooses Torque Data needed (column 1)"<<endl;
cout<<"---Either, Newton Meters, Foot Pounds, or Inch Pounds"<<endl<<endl;
cout<<"Table will print out with corresponding values of the"<<endl;
cout<<"other two data types, so the user can use any kind of"<<endl;
cout<<"torque wrench!"<<endl<<endl;
cout<<"User can choose how many values to print, and how to "<<endl;
cout<<"increment those values!"<<endl<<endl;
cout<<"What data type would you like column 1 to be?"<<endl;
cout<<"(this should be the type you're commonly asked"<<endl;
cout<<" for in tech data)"<<endl;
cout<<"Press 1 for Newton Meters"<<endl;
cout<<"Press 2 for Inch Pounds"<<endl;
cout<<"Press 3 for Foot Pounds"<<endl;
cin>>dataC;
//Error catch
while (dataC!=1&&dataC!=2&&dataC!=3) {
cout<<"Error! Not an option!"<<endl;
cout<<"Press 1 for Newton Meters"<<endl;
cout<<"Press 2 for Inch Pounds"<<endl;
cout<<"Press 3 for Foot Pounds"<<endl;
cin>>dataC;
}
cout<<"Enter how many values you would like the table to go up to: "<<endl;
cout<<"Max is 1000; if printing it is suggested to keep under 75"<<endl;
cin>>size;
while (size>1000) {
cout<<"Too large, re-enter under 1000"<<endl;
cin>>size;
}
while (size<1) {
cout<<"Too small, value must be a whole #"<<endl;
cout<<"above zero and below 1000"<<endl;
cin>>size;
}
cout<<"Enter first value you want the table to start at: "<<endl;
cin>>startV;
cout<<"Enter how you would like the table to be incremented: "<<endl;
cout<<"(Every 1, 2, 5, 10, etc)"<<endl;
cin>>increm;
fillary(tableS, size, increm, startV);
prinTbl(tableS, size, dataC);
cout<<"File: CurrentTable.dat is now available in this"<<endl;
cout<<"directory to print with an appropriate program."<<endl;
break;
}
////////////////////////////////////////////////////////////////////////////////
case 5: {
cout<<"Happy Landings!"<<endl;break;
}
} // switch statement end bracket
////////////////////////////////////////////////////////////////////////////////
} while (choose!=5);
////////////////////////////////////////////////////////////////////////////////
//Exit Stage Right
return 0;
}
void fillary(int array[], int size, int increm, int first) {
int count=1;
for (int index=0; index<size; index++){
array[index]=first;
//cout<<"Array Index "<<count<<" equals "<<first<<endl;
first+=increm;
count++;
}
}
float convert (int origV, float conv1) {
float newVal;
newVal=(origV*conv1);
return newVal;
}
//Function for user choosing to start with newtons
void startNE (int indexV, float &inchLb, float &footLb){
//Multiplication factors to convert newton meters, to foot lbs and inch lbs
float NEWTOIN=8.85074579, NEWTOLB=0.737562149;
inchLb=convert(indexV, NEWTOIN);
footLb=convert(indexV, NEWTOLB);
}
//Function for user choosing inch pounds to start
void startIN (int indexV, float &footLb, float &newtMe){
//Multiplication factors to convert inch lbs, to foot lbs and newton meters
float INTONEW=0.112984829, INTOLB=0.0833;
footLb=convert(indexV, INTOLB);
newtMe=convert(indexV, INTONEW);
}
//Function for user choosing foot pounds to start
void startFO (int indexV, float &inchLb, float &newtMe){
//Multiplication factors to convert inch lbs, to foot lbs and newton meters
float LBTOIN=12, LBTONEW=1.35581795;
inchLb=convert(indexV, LBTOIN);
newtMe=convert(indexV, LBTONEW);
}
//Once completing this function, I realize that a future improvement could be
//re-writing thus function to print just one option, with more input variables.
//Then I can take the menu logic for the data type, and xfer it into main.
void prinTbl (int array[], int &size, unsigned short &choice){
//Columns
float col1=0, col2=0;
//Placeholder
int passVal=0;
//Open out stream to create a text file.
ofstream fout;
fout.open("CurrentTable.dat");
//Set precision for new out stream
fout<<fixed<<setprecision(1)<<showpoint;
//Begin printing table options
//If user selected newtons:
if (choice==1) {
cout<<setw(15)<<left<<"NewtMeters:";
fout<<setw(15)<<left<<"NewtMeters:";
cout<<setw(15)<<left<<"InchPounds:";
fout<<setw(15)<<left<<"InchPounds:";
cout<<setw(15)<<left<<"FootPounds:"<<endl;
fout<<setw(15)<<left<<"FootPounds:"<<endl;
for (int index=0; index<size; index++){
passVal=array[index];
startNE(passVal, col1, col2);
cout<<setw(15)<<left<<array[index];
fout<<setw(15)<<left<<array[index];
cout<<setw(15)<<left<<col1;
fout<<setw(15)<<left<<col1;
cout<<setw(15)<<left<<col2;
fout<<setw(15)<<left<<col2;
cout<<endl;
fout<<endl;
}
}
if (choice==2) {
cout<<setw(15)<<left<<"InchPounds:";
fout<<setw(15)<<left<<"InchPounds:";
cout<<setw(15)<<left<<"FootPounds:";
fout<<setw(15)<<left<<"FootPounds:";
cout<<setw(15)<<left<<"NewtMeters:"<<endl;
fout<<setw(15)<<left<<"NewtMeters:"<<endl;
for (int index=0; index<size; index++){
passVal=array[index];
startIN(passVal, col1, col2);
cout<<setw(15)<<left<<array[index];
fout<<setw(15)<<left<<array[index];
cout<<setw(15)<<left<<col1;
fout<<setw(15)<<left<<col1;
cout<<setw(15)<<left<<col2;
fout<<setw(15)<<left<<col2;
cout<<endl;
fout<<endl;
}
}
if (choice==3) {
cout<<setw(15)<<left<<"FootPounds:";
fout<<setw(15)<<left<<"FootPounds:";
cout<<setw(15)<<left<<"InchPounds:";
fout<<setw(15)<<left<<"InchPounds:";
cout<<setw(15)<<left<<"NewtMeters:"<<endl;
fout<<setw(15)<<left<<"NewtMeters:"<<endl;
for (int index=0; index<size; index++){
passVal=array[index];
startFO(passVal, col1, col2);
cout<<setw(15)<<left<<array[index];
fout<<setw(15)<<left<<array[index];
cout<<setw(15)<<left<<col1;
fout<<setw(15)<<left<<col1;
cout<<setw(15)<<left<<col2;
fout<<setw(15)<<left<<col2;
cout<<endl;
fout<<endl;
}
}
fout.close();
}
void prinAc(float cargo[][3], int size, float &weight, float &moment,
short row, short col, float cargoW){
//Initial declarations and calculations
float acftW=weight, acftCG=(moment/weight), arm=0;
//Tally on new weight
weight=acftW+cargoW;
//Send weight to appropriate location
cargo[row][col]=cargoW;
//Add ARM multiplyer depending on location
//(further back, the higher it is, due to more inches from datum)
if (row==0) {
arm=cargoW*15;
}
else if (row==1) {
arm=cargoW*25;
}
else if (row==2) {
arm=cargoW*35;
}
else if (row==3) {
arm=cargoW*45;
}
//Final calculations
moment=moment+arm;
acftCG=(moment/weight);
//Display
cout<<setw(58)<<setfill('*')<<"*"<<endl;
cout<<"A"<<setfill(' ')<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"A"<<endl;
cout<<"1"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[0][0]<<right;
cout<<"2"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[0][1]<<right;
cout<<"3"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[0][2]<<right<<"*"<<endl;
cout<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<endl;
cout<<setfill('*')<<setw(58)<<"*"<<endl;
cout<<"B"<<setfill(' ')<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"B"<<endl;
cout<<"1"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[1][0]<<right;
cout<<"2"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[1][1]<<right;
cout<<"3"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[1][2]<<right<<"*"<<endl;
cout<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<endl;
cout<<setfill('*')<<setw(58)<<"*"<<endl;
cout<<"C"<<setfill(' ')<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"C"<<endl;
cout<<"1"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[2][0]<<right;
cout<<"2"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[2][1]<<right;
cout<<"3"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[2][2]<<right<<"*"<<endl;
cout<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<endl;
cout<<setfill('*')<<setw(58)<<"*"<<endl;
cout<<"D"<<setfill(' ')<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"D"<<endl;
cout<<"1"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[3][0]<<right;
cout<<"2"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[3][1]<<right;
cout<<"3"<<setw(8)<<left<<" LB= "<<setw(10)<<left<<cargo[3][2]<<right<<"*"<<endl;
cout<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<setw(19)<<"*"<<endl;
cout<<setfill('*')<<setw(58)<<"*"<<endl;
cout<<setfill(' ');
cout<<"Current: "<<endl;
cout<<setw(29)<<left<<"Acft Gross Weight: "<<setw(29)<<left;
cout<<"CG: "<<endl<<endl;
cout<<setw(10)<<left<<weight<<setw(19)<<left<<" pounds";
cout<<setw(10)<<left<<acftCG<<setw(29)<<left<<" inches"<<endl<<endl;
} | true |
da98644f0316354dc946d1e09c1d51ac0bc3e516 | C++ | vsierrabonich/udemy_C | /3.31.cpp | UTF-8 | 1,343 | 3.578125 | 4 | [] | no_license | //
// Created by Vicenç Sierra on 08/12/2018.
//
// Udemy - 3.31. Cajero automático con menú
//
#include <iostream>
using namespace std;
int main(){
int opc;
float saldo = 2500, ret, ing;
cout << "\n--- Bienvenido a tu cuenta bancaria ---\n\nTu saldo actual es de: " << saldo << " €.\n";
cout << "\n--- ¿Qué quieres hacer? ---\n\t1.\tSacar dinero.\n\t2.\tIngresar dinero.\n\t3.\tSalir.\n";
cin >> opc;
switch(opc){
case 1:
cout << "\nCantidad a retirar: "; cin >> ret;
if(ret > saldo) cout << "\nNo tiene tanto saldo disponible.";
else {
saldo -= ret;
cout << "\nHa retirado " << ret << "€.\nTu saldo actual es de: " << saldo << "€.";
}
cout << "\n\nGracias por usar nuestros servicios.\n\n";
break;
case 2:
cout << "\nCantidad a ingresar: "; cin >> ing;
saldo += ing;
cout << "\nHa ingresado " << ing << "€.\nTu saldo actual es de: " << saldo << "€.";
cout << "\n\nGracias por usar nuestros servicios.\n\n";
break;
case 3:
cout << "\n\nGracias por usar nuestros servicios.\n\n"; break;
default:
cout << "\n\nERROR! Vuelve a entrar en la aplicación.\n\n"; break;
}
return 0;
} | true |
9ea23c0e469a37ee0c00137e736599d35148af9b | C++ | BenThurber/Graphics-Assignment-1 | /Assignment1/tesla_boat.cpp | UTF-8 | 3,159 | 2.875 | 3 | [] | no_license | //
// tesla_boat.cpp
// Assignment1
//
// Created by Benjamin Gorham Thurber on 10/04/20.
// Copyright (c) 2020 Benjamin Gorham Thurber. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <GL/freeglut.h>
#include "tesla_boat.h"
#include "loadOFF.h"
#include "main.h"
// Change these to global variables?
#define SPEED 0.2 // Animation Speed
#define A 15 // Size of figure of 8 motion
#define BOB_FREQUENCY 4.8
#define BOB_AMPLITUDE 0.3
static GLuint light;
static double x = 0; // Boat's x coord
static double theta = -90; // Boat's angle along the curve
static float delta_y = 0; // The amount the boat 'bobs' up and down
static int x_direction = 1;
// Draw the headlight opn the boat
void boat_spotlight()
{
const float y=4.3, z=1.5;
float light1_dir[] = {0, -1, 1, 0}; //light1 direction
float light1_pos[] = {0, y, z, 1}; //light1 position
// Draw a cube to mark where the light source is (for testing)
glPushMatrix();
glTranslatef(0, y, z);
// glutSolidCube(1);
glPopMatrix();
glLightfv(light, GL_SPOT_DIRECTION, light1_dir);
glLightfv(light, GL_POSITION, light1_pos);
}
//----- Draws the boat from a model file that is loaded in "main.cpp" ------
void tesla_boat(Model* boat)
{
glDisable(GL_TEXTURE_2D);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 25);
glColor3f(0.4500, 0.3098, 0.0); // Bronze colour
const float size = 1;
const float height = 3;
double z = x_direction * (x * sqrt(pow(A,2) - pow(x,2))) / A;
// std::cout << delta_y << "\n";
glPushMatrix();
glTranslated(x, height + delta_y, z);
glRotatef(theta, 0, 1, 0);
boat_spotlight();
glScalef(size, size, size);
drawModel(boat);
glPopMatrix();
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);
}
// Move the boat to its next animation frame. This should be called in each loop of a glutTimerFunc
// Increment and Decrement x between -1 and 1
void boat_next_frame() {
// Derrivative of the figure of 8 equation
long double dx = (pow(A,2) - 2*pow(x,2)) / (A*sqrt(pow(A,2) - pow(x,2)));
double speed = 0.00001 + SPEED / (1.6 * fmaxl(fabsl(dx), 1.0));
// The angle of the curve is the angle of the tangent vector
theta = DEG((-1) * x_direction * atan(dx)) + x_direction*90;
// Bob the boat up and down a little
static int phi = 0;
phi++;
delta_y = BOB_AMPLITUDE * cos(RAD(fmod(BOB_FREQUENCY * phi, 360.0)));
if ((x + (x_direction * speed)) > A) {
x_direction = -1;
}
else if ((x + (x_direction * speed)) < -A) {
x_direction = 1;
}
x = x + (x_direction * speed);
}
// This goes in intitalize function in main
void boat_init_light(GLuint boat_light)
{
glEnable(GL_LIGHTING);
light = boat_light;
glEnable(light);
// Define light 1's properties
glLightfv(light , GL_AMBIENT, grey);
glLightfv(light, GL_DIFFUSE, white);
glLightfv(light, GL_SPECULAR, white);
glLightf(light, GL_SPOT_CUTOFF, 30.0);
glLightf(light, GL_SPOT_EXPONENT, 50);
}
| true |
5ccbd9c2ccdfdf3e73512b479535706e5c793442 | C++ | akshaynathr/Competitive-Programming | /GRAPH/TREES/sumTree.cpp | UTF-8 | 743 | 3.765625 | 4 | [] | no_license | // Given a binary tree find the sum of all the elements
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* right ;
struct Node* left ;
Node(int data)
{
this ->data = data;
right=left=NULL;
}
};
int addTree(struct Node * node)
{
if(node== NULL)
return 0;
else
return ( node -> data +addTree(node->left) + addTree(node->right));
}
int main()
{
struct Node *root= new Node(1);
root->left = new Node(2);
root -> right = new Node(3);
root -> left -> left = new Node(4);
root -> left -> right = new Node(5);
cout<<"Sum of elements:"<<endl;
int sum ;
sum = addTree(root);
cout<<sum;
return 0;
}
| true |
45d0aeff8a5aa8d50e87179a90ffc389557bc65b | C++ | sidrusiya/CP-AlgorithmsSol | /spmat.cpp | UTF-8 | 666 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
#include<vector>
void spmat(int n){
vector <vector<int>> A(n,vector<int>(n));
int p1,p2,k=1;
for(int l=0;l<n;l++){
if(l%2==0){
p1=l/2;p2=l/2;
while(p1+p2<=2*(n-1-(l)/2)){
A[p1][p2]=k++;
if(p2<n-1-(l)/2)p2++;
else p1++;
}
}
else{
p1=n-1-(l)/2; p2=n-1-(l+1)/2;
while(p1+p2>=l){
A[p1][p2]=k++;
if(p2>=(l+1)/2)p2--;
else p1--;
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
cout<<A[i][j]<<" ";
cout<<endl;
}
}
int main(){
int n;
cin>>n;
spmat(n);
}
| true |
ea036faaca56a91c06b3c6a857798de115cd7a87 | C++ | chaeyeonhan1225/TIL | /알고리즘/MergeSort.cpp | UHC | 1,216 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
void merge(int a[], int left, int mid, int right)
{
int i = left; // κ ù° ε
int j = mid + 1; // κ ù° ε
int *temp = new int[right-left + 1]; // ӽù迭
int k = 0;
while (i <= mid && j <= right) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
}
else {
temp[k++] = a[j++];
}
}
if (i > mid) {
while (j <= right) {
temp[k++] = a[j++];
}
}
else {
while (i <= mid) {
temp[k++] = a[i++];
}
}
k = 0;
for (int h = left; h <= right; ++h) {
cout << temp[k] << " ";
a[h] = temp[k++];
}
cout << endl;
delete[] temp;
}
void mergesort(int a[], int left, int right)
{
if (left < right) {
int mid = (left + right) / 2;
mergesort(a, left, mid);
mergesort(a, mid + 1, right);
merge(a, left, mid, right);
}
}
int main(void)
{
int n;
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
mergesort(a, 0, n - 1);
for (int i = 0; i < n; ++i) {
cout << a[i] << " ";
}
cout << endl;
delete[] a;
system("pause");
return 0;
} | true |
b0ab81f2e9bc90badd69ff07eaf784b7ab1cbca1 | C++ | gabrielmaneru/Ray-Tracing-Model-SDF | /Raytracer/src/utils/math_utils.h | ISO-8859-10 | 1,398 | 2.890625 | 3 | [] | no_license | /* Start Header -------------------------------------------------------
Copyright (C) 2019 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior written consent of
DigiPen Institute of Technology is prohibited.
File Name: math_utils.h
Purpose: Some mathematical utils
Author: Gabriel Maeru - gabriel.m
- End Header --------------------------------------------------------*/
#ifndef min
template <typename T>
T min(const T& a, const T& b)
{
return (a < b) ? a : b;
}
#endif // !min
#ifndef max
template <typename T>
T max(const T& a, const T& b)
{
return (a > b) ? a : b;
}
#endif // !max
template <typename T>
void swap(const T& a, const T& b)
{
T t = a;
a = b;
b = t;
}
template <typename T>
T lerp(const T& min, const T& max, const float& coef)
{
return static_cast<T>(min + (max - min) * coef);
}
template <typename T>
float coef(const T & min, const T & max, const T & value)
{
return static_cast<float>(value - min) / static_cast<float>(max - min);
}
template<typename T, typename R>
R map(T value, T in_min, T in_max, R out_min, R out_max)
{
return lerp(out_min, out_max, coef(in_min, in_max, value));
}
int round_float(const float & value);
int floor_float(const float & value);
float random_float(float min, float max);
#include <glm/glm.h>
quat lerp(const quat& min, const quat& max, const float& coef);
vec3 rand_ball(float rad); | true |
7536d6205bdb8344aa098b65f59f6c334946f7c2 | C++ | minkipro/dungreed | /DX_FrameWork/MosaicShader.h | UHC | 362 | 2.515625 | 3 | [] | no_license | #pragma once
//pass 0:mosaicShader(mosaicSize) ũ Է
class MosaicShader final :public Shader
{
public:
MosaicShader();
virtual ~MosaicShader();
virtual void ShaderReady(RenderInfo* render) override;
void SetMosaicSize(Point size) { assert(size.x && size.y); this->mosaicSize = size; }
private:
Point mosaicSize;
}; | true |
8ac101a176ac30081ef66dac8c8359d0fe177fff | C++ | AlbinChang/Nanyang-Institute-of-Technology-ACM | /房间安排/源.cpp | UTF-8 | 432 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
int T;
cin >> T;
int time_space[256];
int A, B, C;
int N;
while (T--)
{
cin >> N;
fill_n(time_space, 256, 0);
int MAX = 0;
while (N--)
{
cin >> A >> B >> C;
for (int i = B; i < B + C; i++)
{
time_space[i] += A;
if (time_space[i] > MAX)
MAX = time_space[i];
}
}
cout << MAX << endl;
}
} | true |
02d20e935e0091f3c2561d4134a707ae30e8d783 | C++ | pravirtual/Leetcode | /nandincpp/Merge Intervals.cpp | UTF-8 | 662 | 2.78125 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals)
{
vector<vector<int>> ans;
if(!intervals.size())
return ans;
sort(intervals.begin(), intervals.end()); //sorting
vector<int> temp = intervals[0];
for(auto i : intervals)
{
if(i[0] <= temp[1])
temp[1] = max(temp[1], i[1]);
else
{
ans.push_back(temp);
temp = i;
}
}
ans.push_back(temp);
return ans;
}
}; | true |
c96e9eb2b930fcc925e89f9c492a351937629fb5 | C++ | JacobigWong/rtmp_media | /audiooutsdl.cpp | UTF-8 | 2,600 | 2.609375 | 3 | [] | no_license | #include "audiooutsdl.h"
#include "dlog.h"
#include "timeutil.h"
namespace LQF {
static void fill_audio_pcm(void *udata, Uint8 *stream, int len)
{
static int64_t s_pre_time = TimesUtil::GetTimeMillisecond();
AudioOutSDL *audio_out = (AudioOutSDL *)udata;
int64_t cur_time = TimesUtil::GetTimeMillisecond();
LogInfo("callback fill audio t:%ld", cur_time - s_pre_time);
s_pre_time = cur_time;
audio_out->lock_.lock();
if(audio_out->ring_buffer_->getLength() < len) // 数据读取完毕
{
LogError("getLength() < len, buf_size:%d", audio_out->ring_buffer_->getLength());
audio_out->lock_.unlock();
return;
}
SDL_memset(stream, 0, len);
int ret = audio_out->ring_buffer_->read((char *)stream, len); //
LogError("size:%d, read:%d, buf_size:%d", len, ret, audio_out->ring_buffer_->getLength());
audio_out->lock_.unlock();
}
AudioOutSDL::AudioOutSDL()
{
}
AudioOutSDL::~AudioOutSDL()
{
LogInfo("~AudioOutSDL()");
if(ring_buffer_)
{
SDL_PauseAudio(1);
// 关闭清理
// 关闭音频设备
SDL_CloseAudio();
SDL_Quit();
delete ring_buffer_;
}
}
RET_CODE AudioOutSDL::Init(const Properties &properties)
{
sample_rate_ = properties.GetProperty("sample_rate", 48000);
sample_fmt_ = properties.GetProperty("sample_fmt", AUDIO_S16SYS);
channels_ = properties.GetProperty("channels", 2);
ring_buffer_ = new RingBuffer(1024 * 4 * 40); // 最多存储4帧数据
//SDL initialize
if(SDL_Init(SDL_INIT_AUDIO)) // 支持AUDIO
{
LogError("Could not initialize SDL - %s\n", SDL_GetError());
return RET_FAIL;
}
// 音频参数设置SDL_AudioSpec
spec.freq = sample_rate_; // 采样频率
spec.format = sample_fmt_; // 采样点格式
spec.channels = channels_; // 2通道
spec.silence = 0;
spec.samples = 1024; // 每次读取的采样数量
spec.callback = fill_audio_pcm; // 回调函数
spec.userdata = this;
//打开音频设备
if(SDL_OpenAudio(&spec, NULL))
{
LogError("Failed to open audio device, %s\n", SDL_GetError());
return RET_FAIL;
}
//play audio
SDL_PauseAudio(0);
return RET_OK;
}
RET_CODE AudioOutSDL::Output(const uint8_t *pcm_buf, const uint32_t size)
{
lock_.lock();
int ret = ring_buffer_->write((char *)pcm_buf, size);
if(ret != size)
{
// LogError("size:%d, write:%d", size, ret);
}
lock_.unlock();
return RET_OK;
}
void AudioOutSDL::Release()
{
}
}
| true |
32f63196a02e35d840c6ec862c43cce684480430 | C++ | Sookmyung-Algos/2021algos | /algos_assignment/team_pratice/ucpc/team7/week1/2876.cpp | UTF-8 | 841 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, a, b;
cin >> n;
vector<int> A;
vector<int> B;
for (int i = 0; i < n; i++)
{
cin >> a >> b;
A.push_back(a);
B.push_back(b);
}
int min_grade = 0;
int max_students = 0;
for (int g = 1; g <= 5; g++) //같은 grade가 연속으로 있는 학생의 최대 수 구하기
{
int students = 0;
for (int i = 0; i < n; i++)
{
if (g == A[i] || g == B[i])
students++;
else //초기화 시켜서 연속된 grade만 색칠할 수 있게 함
students = 0;
if (students > max_students)
{
max_students = students;
min_grade = g;
}
}
}
cout << max_students << " " << min_grade << endl;
return 0;
}
| true |
172eb79e256b3f4ca5bf960438145408192ca38a | C++ | quanmingyao/FaNCL-parallel | /code/tools.cpp | UTF-8 | 2,446 | 2.75 | 3 | [] | no_license | #include <algorithm>
#include "mkl.h"
#include "tools.h"
using namespace std;
// used for sorting
template <class type> class comIdx
{
public:
comIdx() :m_val(0), m_idx(0) {}
comIdx(const type val, const long long idx):m_val (val), m_idx(idx){}
bool operator < (const comIdx <type>& input)
{
return m_val < input.m_val;
}
type m_val;
long long m_idx;
};
void SortIdx(long long* val, const long long length, long long *idx)
{
vector<comIdx<long long>> data(length);
for (long long i = 0; i < length; i++)
{
data[i].m_val = val[i];
data[i].m_idx = i;
}
sort(data.begin(), data.end());
for (long long i = 0; i < length; i++)
{
val[i] = data[i].m_val;
idx[i] = data[i].m_idx;
}
}
// rearrange elements in val based on positions given by idx
void SwapIdx(const long long* idx, const long long length, long long* val)
{
long long* tpVal = new long long[length];
for (long long i = 0; i < length; i++)
{
tpVal[i] = val[idx[i]];
}
for (long long i = 0; i < length; i++)
{
val[i] = tpVal[i];
}
delete[] tpVal;
}
void SwapIdx(const long long* idx, const long long length, double* val)
{
double* tpVal = new double[length];
for (long long i = 0; i < length; i++)
{
tpVal[i] = val[idx[i]];
}
for (long long i = 0; i < length; i++)
{
val[i] = tpVal[i];
}
delete[] tpVal;
}
vector<pair<long long, long long>> LinearSplit(const long long length, const long long splits)
{
// one base indexing
vector <pair<long long, long long>> rst(splits);
const long long rowJmp = (long long) floor(length / splits);
for (long long s = 0; s < splits; s++)
{
long long sta = s;
long long end = s + 1;
sta = sta * rowJmp + 1;
if (end == splits)
{
end = length;
}
else
{
end = end * rowJmp;
}
rst[s] = pair<long long, long long>(sta, end);
}
return rst;
}
double ZScoreNorm(double* val, const long long length)
{
long long incx = 1;
double mean = 0;
for (long long i = 0; i < length; i++)
{
mean = mean + val[i];
}
mean = mean / length;
for (long long i = 0; i < length; i++)
{
val[i] = val[i] - mean;
}
double nm = dnrm2(&length, val, &incx) / sqrt(length);
for (long long i = 0; i < length; i++)
{
val[i] = val[i] / nm;
}
nm = 0;
for (long long i = 0; i < length; i++)
{
nm = nm + val[i];
}
return nm;
} | true |
1cdb59cd5de2b634b9067eb2ea252a1e076e486d | C++ | jhernandez68/Ejercicios. | /Punteros_Ejercicio1.cpp | UTF-8 | 558 | 3.703125 | 4 | [] | no_license | //Comprobar si un numero es par o impar con punteros y mostrar su direccion de memoria xd
#include <iostream>
using namespace std;
int main(){
int numero, *direccion_numero;
cout<<"Digite un numero \n";
cin>>numero;
direccion_numero=№
if(*direccion_numero%2==0){
cout<<"El numero: "<<*direccion_numero<<" es par"<<endl;
cout<<"Direccion de memoria: "<<direccion_numero;
}
else{
cout<<"El numero: "<<*direccion_numero<<" es impar"<<endl;
cout<<"Direccion de memoria: "<<direccion_numero;
}
return 0;
}
| true |
972dce1ce4b5ec311ee0ffdb57a4ebdcc41799ba | C++ | barunpuri/study | /c++ hw/8-50/q29 - 요일 계산하기.cpp | UTF-8 | 1,505 | 3.5625 | 4 | [] | no_license | #include <iostream>
#include <fstream>
void q29(std::ifstream& fin);
bool isLeapYear(int year);
int yearsToDays(int year);
int monthsToDays(int month, bool isLeapYear) ;
int detDate(int days);
int main()
{
std::ifstream fin;
int numTestCase;
fin.open("input.txt");
fin >> numTestCase;
for(int i=0; i<numTestCase; ++i)
q29(fin);
fin.close();
return 0;
}
void q29(std::ifstream& fin)
{
int sumDays = 0;
int year, month, day;
fin >> year >> month >> day;
sumDays += yearsToDays(year);
sumDays += monthsToDays(month, isLeapYear(year));
sumDays += day;
std::cout << detDate(sumDays) << std::endl;
}
bool isLeapYear(int year)
{
if( (year%400==0)||( (year%100!=0)&&(year%4==0) ) )
return true;
else
return false;
}
int yearsToDays(int year)
{
int standY = 1582;
int days=0;
for(int i=standY; i<year; ++i)
{
if( (i%400==0)||( (i%100!=0)&&(i%4==0) ) )
days += 366;
else
days += 365;
}
return days;
}
int monthsToDays(int month, bool isLeapYear)
{
int standM = 1;
int days=0;
for(int i=standM; i<month; ++i)
{
if(i==2)
{
if(isLeapYear)
days += 29;
else
days += 28;
}
else if( (i==4)||(i==6)||(i==9)||(i==11) )
days += 30;
else
days += 31;
}
return days;
}
int detDate(int days)
{
if( days%7 == 3)
return 0;
else if( days%7 == 4)
return 1;
else if( days%7 == 5)
return 2;
else if( days%7 == 6)
return 3;
else if( days%7 == 0)
return 4;
else if( days%7 == 1)
return 5;
else
return 6;
}
| true |
3564418ba4a21e849759c5d88bcf39b6254b8f14 | C++ | igorbragaia/algorithms | /leetcode/938.cpp | UTF-8 | 613 | 3.46875 | 3 | [] | no_license | /**
* 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:
int rangeSumBST(TreeNode* root, int L, int R) {
int ans=0;
rec(root,L,R,ans);
return ans;
}
private:
void rec(TreeNode*root, int L, int R, int&ans){
if(root == NULL)
return;
if(root->val >= L and root->val <= R)
ans += root->val;
rec(root->left, L,R,ans);
rec(root->right, L,R,ans);
}
}; | true |
35b74a89f0eb06feb6913ef97308d08a0f8a672b | C++ | Dosx001/mini-RPG | /spike/TestInput.cpp | UTF-8 | 939 | 2.578125 | 3 | [] | no_license | #include <gtest/gtest.h>
#include <iostream>
#include <fstream>
int readUserInput(std::istream& input)
{
std::string value;
std::cout << "Enter a number: ";
getline(input, value);
//input >> value;
return std::stoi(value);
}
TEST(Some, Test) {
std::ifstream ifs;
ifs.open("spike/input.txt", std::ifstream::in);
//std::cout << "readUserInput from std::cin: " << readUserInput(std::cin) << std::endl;
std::cout << "readUserInput from ifs: " << readUserInput(ifs) << std::endl;
std::cout << "readUserInput from ifs: " << readUserInput(ifs) << std::endl;
ifs.close();
testing::internal::CaptureStdout();
std::cout << "test\n";
std::string output = testing::internal::GetCapturedStdout();
if (output == "test\n") {
std::cout << "work\n";
}
}
int main(int argc, char **argv) {
testing::InitGoogleTest();
return RUN_ALL_TESTS();
}
| true |
8231dcf09d581a0ffe552aac42a2a7e18328ea68 | C++ | antonkov/UniversityCourses | /cg/tests/segment_intersect.cpp | UTF-8 | 2,869 | 2.640625 | 3 | [] | no_license | #include <gtest/gtest.h>
#include "cg/operations/segment_intersect.h"
#include <cg/primitives/segment.h>
#include "random_utils.h"
TEST(segment_intersect, test1)
{
cg::segment_2 seg1(cg::point_2(0, 1), cg::point_2(1, 0));
cg::segment_2 seg2(cg::point_2(1, 1), cg::point_2(0, 0));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test2)
{
cg::segment_2 seg1(cg::point_2(0, 0), cg::point_2(0, 2));
cg::segment_2 seg2(cg::point_2(0, 1), cg::point_2(0, 3));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test3)
{
cg::segment_2 seg1(cg::point_2(0, 0), cg::point_2(0, 1));
cg::segment_2 seg2(cg::point_2(0, 2), cg::point_2(0, 3));
EXPECT_FALSE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test4)
{
cg::segment_2 seg1(cg::point_2(1, 2), cg::point_2(3, 6));
cg::segment_2 seg2(cg::point_2(2, 4), cg::point_2(4, 8));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test5)
{
cg::segment_2 seg1(cg::point_2(1, 2), cg::point_2(3, 6));
cg::segment_2 seg2(cg::point_2(2, 4), cg::point_2(-100, 21));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test6)
{
cg::segment_2 seg1(cg::point_2(1, 2), cg::point_2(3, 6));
cg::segment_2 seg2(cg::point_2(1, -1), cg::point_2(2, -2));
EXPECT_FALSE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test7)
{
cg::segment_2 seg1(cg::point_2(1, 2), cg::point_2(12, 54));
cg::segment_2 seg2(cg::point_2(1, 2), cg::point_2(-12, -54));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test8)
{
cg::segment_2 seg1(cg::point_2(1, 2), cg::point_2(12, 54));
cg::segment_2 seg2(cg::point_2(20, 102), cg::point_2(30, 154));
EXPECT_FALSE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test9)
{
cg::segment_2 seg1(cg::point_2(1, 1), cg::point_2(1, 1));
cg::segment_2 seg2(cg::point_2(0, 0), cg::point_2(12, 12));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test10)
{
cg::segment_2 seg1(cg::point_2(1, 1), cg::point_2(200, 4));
cg::segment_2 seg2(cg::point_2(8, 8), cg::point_2(8, 8));
EXPECT_FALSE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test11)
{
cg::segment_2 seg1(cg::point_2(1, 1), cg::point_2(1, 1));
cg::segment_2 seg2(cg::point_2(1, 1), cg::point_2(1, 1));
EXPECT_TRUE(cg::segments_intersected(seg1, seg2));
}
TEST(segment_intersect, test12)
{
cg::segment_2 seg1(cg::point_2(1, 1), cg::point_2(1, 1));
cg::segment_2 seg2(cg::point_2(1, 2), cg::point_2(1, 2));
EXPECT_FALSE(cg::segments_intersected(seg1, seg2));
}
int main(int argc, char ** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| true |
735b85d3654fd154e454784b76695c885623491c | C++ | Lijian1122/SF_PollServer | /Base/ThreadPool.h | UTF-8 | 1,444 | 2.765625 | 3 | [] | no_license | /*================================================================
* Copyright (C) 2019 All rights reserved.
*
* 文件名称:ThreadPoll.h
* 创 建 者:lijian
* 创建日期:2019年06月03日
* 描 述:封装linux 和 windows下的线程池的封装,利用C++11的特性
*
#pragma once
================================================================*/
#ifndef THREADPOOL_H_
#define THREADPOOL_H_
#include "ostype.h"
#include "Thread.h"
#include <pthread.h>
#include <list>
using namespace std;
typedef std::function<void()> CTask;
class CWorkerThread
{
public:
CWorkerThread();
~CWorkerThread();
static void* StartRoutine(void* arg);
/*启动线程*/
void Start();
/*执行线程池任务*/
CTask Execute();
/*任务放入任务队列*/
void PushTask(CTask pTask);
/*设置线程唯一标示符*/
void SetThreadIdx(uint32_t idx) {m_thread_idx = idx;}
private:
uint32_t m_thread_idx;
uint32_t m_task_cnt;
pthread_t m_thread_id;
CThreadNotify m_thread_notify;
list<CTask> m_task_list;
};
class CThreadPool
{
public:
CThreadPool();
virtual ~CThreadPool();
/*初始化线程池*/
int Init(uint32_t worker_size);
/*线程池增加任务*/
void AddTask(CTask pTask);
/*销毁线程池*/
void Destory();
private:
uint32_t m_worker_size;
CWorkerThread* m_worker_list;
};
#endif /* THREADPOOL_H_ */
| true |
306711cbf74085fbb891e4eee65a61ed0f524394 | C++ | alchemist366/Homeworks_2 | /List_ 1.cpp | UTF-8 | 1,907 | 3.90625 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Letter{
char l;
Letter *next = NULL;
};
struct LincedList{
Letter *first = NULL;
Letter *last = NULL;
void AddToEnd(char c){
if (first == NULL){
Letter *letter = new Letter;
letter -> l = c;
first = letter;
last = letter;
letter -> next = NULL;
}
else {
Letter *letter = new Letter;
letter -> l = c;
last -> next = letter;
last = letter;
letter -> next = NULL;
}
}
void MakeList(){
cout << "Enter line" << endl;
string s;
getline(cin, s);
for (int i = 0; i < s.length(); i++) {
AddToEnd(s[i]);
}
}
};
bool isChar(char c){
return (( c >= 'a' )&&(c <= 'z')) || ( ( c >= 'A' )&&(c <= 'Z'));
}
LincedList *FindMinWord(LincedList *list, int &k){
Letter *c = list->first;
LincedList *MaxWord = new LincedList();
int leng = 0;
while(c != NULL) {
if (isChar(c -> l) ) {
LincedList *word = new LincedList();
while ((c != NULL) && isChar(c -> l)) {
leng++;
word->AddToEnd(c->l);
c = c->next;
}
if (leng > k) {
k = leng;
MaxWord = word;
}
leng = 0;
}
else {
c = c -> next;
}
}
return MaxWord;
}
void OutPut(LincedList *list, int n){
cout << "Your word is '" ;
Letter *letter = list->first;
while(letter != NULL) {
cout << letter->l;
letter = letter->next;
}
cout << "' and it has " << n << " letters" << endl;
}
int main() {
LincedList list;
list.MakeList();
int k = 0;
LincedList *word = FindMinWord(&list, k);
OutPut(word, k);
} | true |
3ab342c2804f3eeb63018b21d389486441a64ef8 | C++ | isombeg/Morse-Code-Interpreter | /Morse_Code_Interpreter.ino | UTF-8 | 6,624 | 3.078125 | 3 | [] | no_license | #include <stdlib.h>
const int ELEC_INPUT_PIN = 7; //Digital pin 7 will be used to detect electrical input
char *morseStr = " ";
//Letters and corresponding morse code
#define morse_A "01"
#define morse_B "1000"
#define morse_C "1010"
#define morse_D "100"
#define morse_E "0"
#define morse_F "0010"
#define morse_G "110"
#define morse_H "0000"
#define morse_I "00"
#define morse_J "0111"
#define morse_K "101"
#define morse_L "0100"
#define morse_M "11"
#define morse_N "10"
#define morse_O "111"
#define morse_P "0110"
#define morse_Q "1101"
#define morse_R "010"
#define morse_S "000"
#define morse_T "1"
#define morse_U "001"
#define morse_V "0001"
#define morse_W "011"
#define morse_X "1001"
#define morse_Y "1011"
#define morse_Z "1100"
//Classification of different characters and Morse Code:
// Lists of the alphabet:
char *oneInpChar = "ET";
char *twoInpChar = "AIMN";
char *thrInpChar_A = "DGKO";
char *thrInpChar_B = "RSUW";
char *fourInpChar_A = "BCQXYZ";
char *fourInpChar_B = "FHJLPV";
//Lists of lists containing the Morse code for each character above:
const char *oneInpDigits[ 2 ] = {morse_E, morse_T};
const char *twoInpDigits[ 4 ] = {morse_A, morse_I,morse_M, morse_N};
const char *thrInpDigits_A[ 4 ] = {morse_D, morse_G, morse_K, morse_O};
const char *thrInpDigits_B[ 4 ] = {morse_R, morse_S, morse_U, morse_W};
const char *fourInpDigits_A[ 6 ] = {morse_B, morse_C, morse_Q, morse_X, morse_Y, morse_Z};
const char *fourInpDigits_B[ 6 ] = {morse_F, morse_H, morse_J, morse_L, morse_P, morse_V};
int counter(char *code){
int counter = 0;
for (int i = 0; i < 4; i++){ //Loop counts how many 1s and 0s are in the loop
if (code[i] == '0' || code[i] == '1'){
counter++;
}
}
return counter;
}
int dashDotDet(){ //Function determining whether input is a dash or a dot
int powerState = digitalRead(ELEC_INPUT_PIN); //Store whether button is being pushed or not in bool variable
if (powerState == HIGH){ //In the event that button is being pushed, execute following procedure
delay(1000);
powerState = digitalRead(ELEC_INPUT_PIN); //If after a second the button is still down, register a dash
if (powerState == HIGH){
return 1;
}
else if(powerState == LOW){ //If after a second the button isn't still down, register a dot
return 0;
}
}
else if(powerState == LOW){ //If the button was never pressed in the first place, recur
dashDotDet();
}
}
int chngCharDet(){ //Function determining whether or not the user will being inputting code for a different character
if (digitalRead(ELEC_INPUT_PIN) == LOW){ //If button is unpressed
int initTime = millis(); //Time elapsed in millisecs since program started running
while (digitalRead(ELEC_INPUT_PIN) == LOW && millis() - initTime < 2000){ //while button remains unpressed and time elapsed since initializing initTime is less than 2000 ms
}
int finalTime = millis();
if ((finalTime - initTime) < 2000){
return 0; //user not changing chars if time between initializing initTime and finalTime is lesser than 2000
}
else if (finalTime - initTime >= 2000){
return 1; //user changing chars if time between initializing initTime and finalTime is greater than or equal to 2000
}
}
else{
chngCharDet();
}
} //If the button remains unpressed for more than 2 seconds, the software established that the user will input Morse code for a new character
char *linkDashDot(){ //Function that will link dashes and dots belonging to the Morse code for a certain character together
char dashDotStr[] = {NULL,NULL,NULL,NULL,'\0'}; //Initialize pointer with 4 chars
int chngState;
int index = -1;
//Serial.println("Commencing recording of dash and dots\n");
do{
if (digitalRead(ELEC_INPUT_PIN) == LOW){
index++;
// Serial.print("index: ");
// Serial.println(index);
if (chngCharDet() == 0){
// Serial.println("Recording conditions cleared");
dashDotStr[index] = (char) (dashDotDet() + 48);
chngState = 0;
// Serial.print("dashDotStr: ");
// Serial.println(dashDotStr);
// Serial.println("\n");
}
else{
//Serial.println("Recording conditions not cleared");
chngState = 1;
}
}
} while (chngState == 0 && index < 3); //while user doesn't intend to change char and index is lesser than 3
// Serial.println("Terminating the recording process\n");
return dashDotStr;
}
char charDet(char *morseCode, int arrSize){ //function to find character corresponding to morse code
int indexNum = -1;
switch(arrSize){
case 1 :
while (morseCode != oneInpDigits[indexNum] && indexNum <= 1){
indexNum++;
}
return oneInpChar[indexNum];
break;
case 2 :
//Serial.println("Case 2 satisfied");
while (morseCode != twoInpDigits[indexNum] && indexNum <= 4){
indexNum++;
}
//Serial.print("indexNum: ");
//Serial.println(indexNum);
return twoInpChar[indexNum];
break;
case 3 :
//Serial.println("Case 3 satisfied");
if (morseCode[0] == '1'){ //Procedure If morse code begins with 1
while (morseCode != thrInpDigits_A[indexNum] && indexNum <= 4){
indexNum++;
}
return thrInpChar_A[indexNum];
}
else if (morseCode[0] == '0'){ //Procedure if morse code begins with 0
while (morseCode != thrInpDigits_B[indexNum] && indexNum <= 4){
indexNum++;
}
return thrInpChar_B[indexNum];
}
break;
case 4 :
//Serial.println("Case 4 satisfied");
if (morseCode[0] == '1'){ //Procedure If morse code begins with 1
while (morseCode != fourInpDigits_A[indexNum] && indexNum <= 6){
indexNum++;
}
return fourInpChar_A[indexNum];
}
else if (morseCode[0] == '0'){ //Procedure if morse code begins with 0
while (morseCode != fourInpDigits_B[indexNum] && indexNum <= 6){
indexNum++;
}
return fourInpChar_B[indexNum];
}
break;
}
}
void setup() {
Serial.begin(9600);
pinMode(ELEC_INPUT_PIN, INPUT);
Serial.println("Commencing recording process. Please begin inputting.\n");
}
void loop() {
morseStr = linkDashDot();
Serial.print(charDet(morseStr, counter(morseStr)));
Serial.print('-');
*morseStr = " ";
}
| true |
ca6e3884f8969137a450c17a1878b2c3f321cf2c | C++ | gleensande/PLM | /Gant/graph.cpp | UTF-8 | 4,091 | 3.28125 | 3 | [] | no_license | #include "graph.hpp"
// конструктор графа по количеству вершин
CListGraph::CListGraph(size_t vertices_count) {
edges.resize(vertices_count);
tasks.resize(vertices_count);
visited.resize(vertices_count, false);
}
// добавление связи между вершиной номер v1 и номер v2
void CListGraph::AddEdge(int v1, int v2) {
edges[v1].push_back(v2);
}
// получение всех вершин, связанных с данной
vector<int> CListGraph::GetConnectedVertices(int vertex) const {
vector<int> vertices = edges[vertex];
return vertices;
}
// получение количества всех вершин графа
int CListGraph::getVerticesCount() const {
return edges.size();
}
Task CListGraph::get_task(int i) {
return tasks[i];
}
void CListGraph::set_task(int i, Task t) {
tasks[i] = t;
}
void CListGraph::print_graph() {
for (int i = 0; i < tasks.size(); i++) {
std::cout << i << " ";
tasks[i].print();
}
}
void CListGraph::DFS(/*int start, int finish*/) {
stack<int> s;
int strat_v = 0;
s.push(strat_v);
while (!s.empty()) {
int vertex = s.top();
s.pop();
cout << vertex << endl;
int out_count = 0;
for (int i = 0; i < edges[vertex].size(); i++) {
if (visited[edges[vertex][i]] == false) {
s.push(edges[vertex][i]);
visited[edges[vertex][i]] = true;
out_count++;
}
}
if (out_count == 0)
topological.push_back(vertex);
}
}
// обход графа
int CListGraph::BFS(int start_vertex, int stop_vertex) {
queue<int> q;
vector<bool> visited(VerticesCount(), false);
vector<int> s(VerticesCount(), INT_MAX);
vector<int> p(VerticesCount(), 0);
q.push(start_vertex);
visited[start_vertex] = true;
s[start_vertex] = -tasks[start_vertex].get_weight();
p[start_vertex] = -1;
int current = start_vertex;
while(!q.empty()) {
current = q.front();
q.pop();
vector<int> neighbours = GetConnectedVertices(current);
for (int i = 0; i < neighbours.size(); i++) {
int neighbour = neighbours[i];
if (visited[neighbour] == false) {
int weight = -((tasks[neighbour].get_start_time() - tasks[current].get_end_time()) + tasks[neighbour].get_weight());
if (s[current] + weight < s[neighbour]) {
p[neighbour] = p[current];
s[neighbour] = s[current] + weight;
q.push(neighbour);
}
}
}
visited[current] = true;
}
return s[stop_vertex];
}
// обход графа
vector<int> CListGraph::BFS_path(int start_vertex, int stop_vertex) {
queue<int> q;
vector<bool> visited(VerticesCount(), false);
vector<int> s(VerticesCount(), INT_MAX);
vector<int> p(VerticesCount(), 0);
q.push(start_vertex);
visited[start_vertex] = true;
s[start_vertex] = tasks[start_vertex].get_weight();
p[start_vertex] = -1;
int current = start_vertex;
while(!q.empty()) {
current = q.front();
q.pop();
vector<int> neighbours = GetConnectedVertices(current);
for (int i = 0; i < neighbours.size(); i++) {
int neighbour = neighbours[i];
if (visited[neighbour] == false) {
int weight = (tasks[neighbour].get_start_time() - tasks[current].get_end_time()) + tasks[neighbour].get_weight();
if (s[current] + weight < s[neighbour]) {
p[neighbour] = current;
s[neighbour] = s[current] + weight;
q.push(neighbour);
}
}
}
visited[current] = true;
}
vector<int> path;
if (!visited[stop_vertex])
return {-1};
else {
for (int v = stop_vertex; v != -1; v = p[v]) {
path.push_back(v);
}
}
return path;
} | true |
124f36e453b09aae4f6dfc4280cb18fc6b479a80 | C++ | fpelliccioni/Honeycomb | /Honeycomb/src/common/Honey/Physics/Physics.cpp | UTF-8 | 1,358 | 2.515625 | 3 | [
"BSL-1.0"
] | permissive | // Honeycomb, Copyright (C) 2013 Daniel Carter. Distributed under the Boost Software License v1.0.
#pragma hdrstop
#include "Honey/Physics/Physics.h"
namespace honey
{
template<class Real>
Real Physics_<Real>::travelTime(Real dist, Real accel, Real velMin, Real velMax)
{
if (accel <= 0 || velMax <= 0)
{
if (velMin <= 0)
return 0;
else
return dist / velMin;
}
//Calc time to accelerate and reach dest, starting at min speed, ignoring max speed
//This is derived from the quadratic formula of d=vt+1/2at^2
Real accelToDestTime = (-velMin + Alge::sqrt(Alge::sqr(velMin) + ((dist*accel)*2))) / accel;
//Calc time to achieve max speed
Real accelTime = (velMax-velMin) / accel;
if (accelToDestTime > accelTime)
{
//Calc dist travelled from start until we hit max speed
Real accelDist = velMin*accelTime + ((accel*Alge::sqr(accelTime))/2);
//Calc dist we must travel at max speed
Real maxSpeedDist = dist - accelDist;
//Final time is the time it takes to accelerate to max speed plus time it takes to reach dest at max speed
accelToDestTime = accelTime + (maxSpeedDist / velMax);
}
return accelToDestTime;
}
template class Physics_<Float>;
template class Physics_<Double>;
}
| true |
2615ffaf52324c99d6749e7c587aee2ff235f028 | C++ | vordhosbnbg/simple2dgameengine | /VS2015/NeuralNetTester/GSRenderer.cpp | UTF-8 | 766 | 2.53125 | 3 | [] | no_license | #include "GSRenderer.h"
GSRenderer::GSRenderer(shared_ptr<GSWindow> window) : renderer_handle(SDL_CreateRenderer(window->GetRawHandle(), - 1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC), sdl_deleter())
{
}
GSRenderer::~GSRenderer()
{
}
void GSRenderer::Clear()
{
SDL_RenderClear(renderer_handle.get());
}
void GSRenderer::Draw(shared_ptr<GSDrawable> drawable)
{
SDL_RenderCopyEx(renderer_handle.get(), drawable->GetTexture()->GetRawHandle(), drawable->GetSrcRect()->GetRawRect(), drawable->GetDstRect()->GetRawRect(), drawable->GetDrawableRotation(), NULL, SDL_FLIP_NONE);
}
void GSRenderer::RenderPresent()
{
SDL_RenderPresent(renderer_handle.get());
}
SDL_Renderer * GSRenderer::GetRawHandle()
{
return renderer_handle.get();
}
| true |
7c725873087854c526d41bdc93540bcd7a99edb7 | C++ | forspy/share | /test_c++_transfer string.cpp | GB18030 | 955 | 3.703125 | 4 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
void display(string* str, int n);
int main()
{
const int Size = 3;
char kk[200];
cin >> kk;
cout << kk << endl;;
//cin.clear();ֻcinĴ״̬
cin.getline(kk,100);//ۣʹcin.getlineסʣµַ,൱
cout << kk << endl;;
char str[100];
cin.getline(str, 100);//cin.getlineֻܸcharֵcin.getlineiostreamģgetlineֻܸstringֵΪgetlinestring
string name[Size];//stringͶַ鷽
for (int i = 0; i < Size; i++)
{
getline(cin,name[i]);//ʹcin.getline(name[i],100]Ϊstringֵ
}
display(name, Size);//nameУnameһַ
}
void display(string* str, int n)//stringͺcharʹ÷ʽһ
{
for (int i = 0; i < n; i++)
{
cout << str[i] << endl;
}
} | true |
cfc890c7408f48e02d3ebcb3867ddd17ab21a968 | C++ | NiharsGIT/LandingGearMechanism | /LandingGearNano/LandingGearNano.ino | UTF-8 | 1,327 | 2.84375 | 3 | [] | no_license |
#include <Servo.h>
Servo servo1;
Servo servo2;
int pos = 180;
int Thr=20;
int state; // 0:Open 1:Moving 2:Closed
long duration,cm;
int trigPin = A3;
int echoPin = A4;
unsigned long prevMillis = 0;
unsigned long currentMillis = 0;
void setup()
{
servo1.attach(A1);
servo2.attach(A2);
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
state = 0; //Open
}
void loop()
{
currentMillis = millis();
if(currentMillis - prevMillis >= 250)
{
measureDist();
prevMillis = currentMillis;
}
if(cm>5 && cm<Thr) //Near Ground => Open
{
if(state == 0)
pos = 180;
else
{
if(pos == 180)
state = 0;
else
pos++;
}
}
else if(cm>Thr) //Away from Ground
{
if(state == 2) //closed
pos = 0;
else // closing
{
if(pos == 0)
state = 2;
else
pos--;
}
}
servo1.write(pos);
servo2.write(pos);
delayMicroseconds(15);
}
void measureDist()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
cm = (duration/2) / 29.1;
Serial.print("****measuring**** cm");
Serial.print(cm);
Serial.println();
}
| true |
ac2c62d34851929db30cda215c85c2d63544e9f9 | C++ | kbrian187/Warhammer_Casualty_Tracker | /Source_Files/Game.h | UTF-8 | 495 | 2.625 | 3 | [] | no_license | /*
* Game.h
*
* Created on: Apr 13, 2014
* Author: Brian
*/
#include<string>
#include<iostream>
#include"Unit.h"
#include"Army.h"
#include"Model.h"
using namespace std;
#ifndef GAME_H_
#define GAME_H_
class Game
{
public:
Game(Army*, Army*);
~Game();
string unitCasualties(Army*, Army*);
bool unitDead(int);
string turn(int);
string displayGameResult();
string unitReport(Army*, Army*);
//variables
Army FirstArmy;
Army SecondArmy;
int turnNum;
string gameResult;
};
#endif | true |
a31c04798842e6bb511fcfccfc376813b678e0d2 | C++ | apaek1204/Megaman | /deliverable/healthbar.h | UTF-8 | 1,616 | 3 | 3 | [] | no_license | #ifndef HEALTHBAR_H
#define HEALTHBAR_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include "LTexture.h"
#include <vector>
class healthbar{
public:
healthbar(float=500, float=400);
~healthbar();
bool loadSprite();
void render(float, float, int);
const SDL_Rect getHitBox();
void shoot(int);
void setX(int);
void setY(int);
private:
vector < LTexture* > gEnemyTexture;
float enemyX_vel, enemyY_vel;
float enemyX, enemyY;
int health;
};
healthbar::healthbar(float xCoord, float yCoord)
{
LTexture* tmp = NULL;
for( int i = 0; i < 10; i++ ){
if(i==0)
tmp = new LTexture(20,30);
else
tmp = new LTexture(i*20,30);
gEnemyTexture.push_back(tmp);
}
enemyX = xCoord;
health = 10;
enemyY = yCoord;
}
healthbar::~healthbar()
{
for( int i = 0; i<10; i++)
delete gEnemyTexture[i];
}
bool healthbar::loadSprite()
{
bool success = true;
for( int i = 0; i<10; i++){
if( !gEnemyTexture[i]->loadFromFile("./../assets/sprites/megaman/healthbar.png"))
{
printf( "Unable to load enemy texture! \n");
success = false;
}
}
return success;
}
void healthbar::render( float camx, float camy,int health)
{
float newenemyX, newenemyY;
SDL_RendererFlip flip = SDL_FLIP_NONE;
newenemyX = enemyX - camx;
newenemyY = enemyY - camy;
if( health >=0)
gEnemyTexture[health]->render( newenemyX, newenemyY, NULL, 0.0, NULL,flip);
}
void healthbar::setX(int a){
enemyX = a;
}
void healthbar::setY(int a){
enemyY = a;
}
#endif
| true |
d63acec62da575a1641609e1ec5394b7d3597145 | C++ | manalikale/Trees | /IdenticalTrees.cpp | UTF-8 | 1,400 | 4.4375 | 4 | [] | no_license | /*
Algorithm to check if two trees are identical
Algorithm:
sameTree(tree1, tree2)
1. If both trees are empty then return 1.
2. Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively i.e., call sameTree(
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively i.e., call sameTree(
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3 Else return 0 (one is empty and other is not)
Time: O(n)
Sapce: O(n)
*/
#include<iostream>
using namespace std;
struct node{
int data;
node *left;
node *right;
};
node *newnode(int data)
{
node *newnode=new node();
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
int areIdenticalTrees(node *root1, node *root2)
{
//if both trees are empty
if(root1==NULL &&root2==NULL)
{
return 1;
}
//if both are non empty compare them
if(root1!=NULL && root2!=NULL)
{
return (root1->data==root2->data && areIdenticalTrees(root1->left, root2->left) && areIdenticalTrees(root1->right, root2->right));
}
//one tree is empty and another is not
return 0;
}
int main(void)
{
node *root1=newnode(1);
node *root2=newnode(1);
cout<<areIdenticalTrees(root1, root2)<<endl;
return 0;
}
| true |
ea1d7359a5cf8a0f978d1e819c4046d41ca88acb | C++ | smwesten-usgs/Starspan | /src/common.h | UTF-8 | 2,853 | 2.625 | 3 | [
"MIT-Modern-Variant"
] | permissive | //
// starspan common declarations
// Carlos A. Rueda
// $Id: common.h,v 1.10 2008-04-23 00:05:22 crueda Exp $
//
#ifndef starspan_common_h
#define starspan_common_h
#include <string>
#include <sstream>
#include <vector>
#include <cassert>
using namespace std;
/** buffer parameters
*/
struct BufferParams {
/** were given? */
bool given;
/** Distance to be applied.
* If it starts with '@' then it indicates the name of the attribute
* from which this value will be obtained.
*/
string distance;
/** Number of segments to use to approximate a* quadrant of a circle.
* If it starts with '@' then it indicates the name of the attribute
* from which this value will be obtained.
*/
string quadrantSegments;
};
/** Box parameters
*/
struct BoxParams {
/** were given? */
bool given;
double width;
double height;
};
/** Class for duplicate pixel modes. */
struct DupPixelMode {
string code;
double arg;
DupPixelMode(string code, double arg) :
code(code), arg(arg), withArg(true) {
}
DupPixelMode(string code) :
code(code), withArg(false) {
}
string toString() {
ostringstream ostr;
ostr << code;
if ( withArg ) {
ostr << " " << arg;
}
return ostr.str();
}
private:
bool withArg;
};
/**
* vector selection parameters
*/
struct VectorSelectionParams {
/** sql statement */
string sql;
/** where statement */
string where;
/** dialect */
string dialect;
VectorSelectionParams() : sql(""), where(""), dialect("") {}
};
/** Options that might be used by different services.
* This comes in handy while the tool gets more stabilized.
*/
struct GlobalOptions {
bool use_pixpolys;
bool skip_invalid_polys;
double pix_prop;
// vector selection parameters
VectorSelectionParams vSelParams;
/** desired FID */
long FID;
bool verbose;
bool progress;
double progress_perc;
/** param noColRow if true, no col,row fields will be included */
bool noColRow;
/** if true, no x,y fields will be included */
bool noXY;
bool only_in_feature;
/** Style for RID values in output.
* "file" : the simple filename without path
* "path" : exactly as obtained from command line or field in vector
* "none" : no RID is included in output
*/
string RID;
bool report_summary;
/** value used as nodata */
double nodata;
// buffer parameters
BufferParams bufferParams;
// box parameters
BoxParams boxParams;
// miniraster parity
string mini_raster_parity;
/** separation in pixels between minirasters in strip */
int mini_raster_separation;
/** separator for CSV files */
string delimiter;
/** Given duplicate pixel modes. Empty if not given. */
vector<DupPixelMode> dupPixelModes;
};
extern GlobalOptions globalOptions;
#endif
| true |
4250f06eb0347063872709d0f08f298c08e33b2f | C++ | icestudent/ontl | /ntl/win/console.hxx | UTF-8 | 14,319 | 2.625 | 3 | [
"Zlib",
"LicenseRef-scancode-stlport-4.5"
] | permissive | /**\file*********************************************************************
* \brief
* Console support
*
****************************************************************************
*/
#ifndef NTL__WIN_CONSOLE
#define NTL__WIN_CONSOLE
#pragma once
#include "windef.hxx"
#include "handle.hxx"
#include "../nt/peb.hxx"
#include "application.hxx"
#include "stlx/stdstring.hxx"
#include "stlx/streambuf.hxx"
#include "../nt/file.hxx"
namespace ntl {
namespace win {
NTL_EXTERNAPI
boolean __stdcall AllocConsole();
NTL_EXTERNAPI
boolean __stdcall AttachConsole(uint32_t);
NTL_EXTERNAPI
boolean __stdcall FreeConsole();
NTL_EXTERNAPI
boolean __stdcall
WriteConsoleA(
legacy_handle ConsoleOutput,
const void * Buffer,
uint32_t NumberOfCharsToWrite,
uint32_t * NumberOfCharsWritten,
void * Reserved
);
NTL_EXTERNAPI
boolean __stdcall
WriteConsoleW(
legacy_handle ConsoleOutput,
const void * Buffer,
uint32_t NumberOfCharsToWrite,
uint32_t * NumberOfCharsWritten,
void * Reserved
);
NTL_EXTERNAPI
boolean __stdcall
ReadConsoleA(
legacy_handle ConsoleInput,
void* Buffer,
uint32_t NumberOfCharsToRead,
uint32_t* NumberOfCharsReaded,
void* InputControl
);
NTL_EXTERNAPI
boolean __stdcall
ReadConsoleW(
legacy_handle ConsoleInput,
void* Buffer,
uint32_t NumberOfCharsToRead,
uint32_t* NumberOfCharsReaded,
void* InputControl
);
NTL_EXTERNAPI
boolean __stdcall GetConsoleMode(legacy_handle ConsoleHandle, uint32_t* Mode);
NTL_EXTERNAPI
boolean __stdcall SetConsoleMode(legacy_handle ConsoleHandle, uint32_t Mode);
/**\addtogroup console *********** Console support *************************
*@{*/
class console
{
///////////////////////////////////////////////////////////////////////////
public:
enum type {
stdin,
stdout,
stderr
};
enum mode_type {
DefaultMode,
EnableProcessedInput = 0x01,
EnableLineInput = 0x02,
EnableEchoInput = 0x04,
EnableWindowInput = 0x08,
EnableMouseInput = 0x10,
EnableInsertMode = 0x20,
EnableQuickEditMode = 0x40
};
__ntl_bitmask_type(mode_type, friend);
public:
static legacy_handle handle(type t)
{
return *(&nt::peb::instance().ProcessParameters->StandardInput + t); //-V104
}
static bool is_console_handle(legacy_handle h)
{
return (uintptr_t(h) & 0x03) == 0x03;
}
static bool is_console_handle(type t)
{
return is_console_handle(handle(t));
}
static mode_type mode(legacy_handle h)
{
uint32_t m = 0;
GetConsoleMode(h, &m);
return static_cast<mode_type>(m);
}
static mode_type mode(legacy_handle h, mode_type m)
{
uint32_t prev_mode = 0;
GetConsoleMode(h, &prev_mode);
SetConsoleMode(h, m);
return static_cast<mode_type>(prev_mode);
}
static __forceinline
bool alloc()
{
return 0 != AllocConsole();
}
///\note attaches to parent process' console by default
static __forceinline
bool attach(uint32_t process_id = uint32_t(-1))
{
return 0 != AttachConsole(process_id);
}
static __forceinline
bool free()
{
return 0 != FreeConsole();
}
template<typename charT>
static
uint32_t write(const void * buf, uint32_t chars);
template<>
static
uint32_t write<char>(const void * ptr, uint32_t chars)
{
uint32_t written = 0;
const legacy_handle out = nt::peb::instance().ProcessParameters->StandardOutput;
WriteConsoleA(out, ptr, chars, &written, 0);
return written;
}
template<>
static
uint32_t write<wchar_t>(const void * ptr, uint32_t chars)
{
uint32_t written = 0;
const legacy_handle out = nt::peb::instance().ProcessParameters->StandardOutput;
WriteConsoleW(out, ptr, chars, &written, 0);
return written;
}
template<typename charT>
static
uint32_t write(const charT msg[])
{
return write<charT>(msg, static_cast<uint32_t>(std::char_traits<charT>::length(msg)));
}
template<typename charT>
static
uint32_t write(const charT c)
{
return write<charT>(&c, 1);
}
template<typename charT>
static
uint32_t write(const std::basic_string<charT> & s)
{
return write<charT>(s.begin(), s.size() - (s.end()[-1] == '\0'));
}
};//class console
/** \defgroup console_stream Console I/O Streams support
*@{*/
template<typename charT, class traits = std::char_traits<charT> >
class console_buffer:
public std::basic_streambuf<charT, traits>
{
typedef std::streamsize streamsize;
static const size_t buffer_size = 1024;
public:
using typename std::basic_streambuf<charT, traits>::char_type;
using typename std::basic_streambuf<charT, traits>::int_type;
explicit console_buffer(legacy_handle outh, bool is_output = true)
:buffer(), outh(outh), is_console_handle(console::is_console_handle(outh)),
write_only(is_output)
{
if(outh)
init();
}
explicit console_buffer(console::type type, bool is_output = true)
:buffer(), outh(console::handle(type)), is_console_handle(console::is_console_handle(type)),
write_only(is_output)
{
init();
}
~console_buffer()
{
delete[] buffer;
buffer = nullptr;
}
protected:
///\name overloaded members
virtual std::basic_streambuf<charT, traits>* setbuf(char_type* s, streamsize n)
{
if(!s && !n)
// unbuffered io
s = buffer, n = 1;
if(write_only)
this->setp(s, s+n);
else
this->setg(s, s, s);
return this;
}
virtual int sync()
{
if(!outh) return -1;
streamsize size = this->pptr() - this->pbase();
if(size){
size = write(this->pbase(), size);
reset();
}
return static_cast<int>(size);
}
virtual streamsize showmanyc()
{
_assert_msg("not implemented yet");
return 0;
}
virtual int_type underflow()
{
return do_underflow(1);
}
int_type do_underflow(streamsize /*n*/)
{
const int_type eof = traits_type::eof();
if(write_only || !outh)
return eof;
// backup: gptr-eback [begin,pos) (already readed)
// pending: egptr-gptr [pos,end)
streamsize avail = this->egptr() - this->gptr();
if(avail > 0)
// just return it
return traits_type::to_int_type(*this->gptr());
streamsize cb;
char_type* p = this->eback();
if(this->egptr() == p){
// first call
cb = 128;
}else{
avail = this->gptr() - this->eback();
avail = avail > 32 ? 16 : (avail <= 1 ? 0 : 1); // leave 16 characters for backup seq if avail
cb = buffer_size - avail;
if(avail){
traits_type::move(p, this->gptr()-1, avail);
p += avail;
this->setg(buffer, p, p); // temporary set read position to the end of backup
}
}
//if(is_console_handle)
//cb = std::min(n, cb);
avail = read(p, cb);
bool ok = avail > 0;
if(!ok)
return eof;
// [back|pos|readed]
this->setg(this->eback(), p, p+avail);
return traits_type::to_int_type(*this->gptr());
}
virtual streamsize xsgetn(char_type* s, streamsize n)
{
const int_type eof = traits_type::eof();
for (streamsize copied = 0;;){
if(n <= 0)
return copied;
const streamsize ravail = this->gend - this->gnext;
if(ravail <= 0)
{
if(traits_type::eq_int_type(eof, do_underflow(n)))
return copied;
continue;
}
//__assume(n >= 0 && ravail >= 0);
const size_t chunksize = static_cast<size_t>(std::min(n, ravail));
traits_type::copy(s, this->gnext, chunksize);
s += chunksize;
copied += chunksize;
this->gnext += chunksize;
n -= chunksize;
}
}
virtual int_type overflow(int_type c)
{
const int_type eof = traits_type::eof();
const bool eofc = traits_type::eq_int_type(c, traits_type::eof());
if(write_only == false || !outh || (!this->pbase() && eofc))
return eof;
bool ok = true;
if(this->pbase()){
const streamsize pending = this->pptr() - this->pbase();
ok = write(this->pbase(), pending) == pending;
if(ok)
reset();
}
if(ok && !eofc){
const char_type cc = traits_type::to_char_type(c);
ok = write(&cc, 1) == 1;
}
if(!ok)
return eof;
return eofc ? traits_type::not_eof(c) : c;
}
protected:
void init()
{
buffer = new charT[buffer_size];
setbuf(buffer, buffer_size);
//console::mode_type m = console::mode(outh);
//m |= write_only ? console::EnableQuickEditMode : console::EnableInsertMode;
//console::mode(outh, m);
}
void reset()
{
if(write_only)
this->setp(this->pbase(), this->epptr());
else{
char_type* g = this->eback();
this->setg(g, g, g);
}
}
///\name write functions
streamsize console_write(const char* data, streamsize n)
{
uint32_t written = 0;
WriteConsoleA(outh, data, static_cast<uint32_t>(n), &written, 0);
return static_cast<streamsize>(written);
}
streamsize console_write(const wchar_t* data, streamsize n)
{
uint32_t written = 0;
WriteConsoleW(outh, data, static_cast<uint32_t>(n), &written, 0);
return static_cast<streamsize>(written);
}
streamsize file_write(const char_type* data, streamsize n)
{
typedef std::codecvt<char_type,char,traits::state_type> codecvt;
static const codecvt& cvt = std::use_facet<codecvt>(this->getloc());
using std::codecvt_base;
traits::state_type state;
const char_type *from_next, *to = data+n, *from = data;
char buf[1024], *to_next;
const void* p;
streamsize pending = n;
NTL_SUBSYSTEM_NS::file_handler f; f.reset(outh);
__ntl_try {
do{
streamsize chunk_size, write_size;
codecvt_base::result re = cvt.out(state,from,to,from_next,buf,buf+_countof(buf),to_next);
if(re == codecvt_base::error)
break;
else if(re == codecvt_base::noconv)
p = data, chunk_size = to-from, write_size = chunk_size*sizeof(char_type);
else // ok | partial
p = buf, chunk_size = to_next-buf, write_size = chunk_size*sizeof(char);
assert(write_size > 0);
if(!NTL_SUBSYSTEM_NS::success(f.write(p, static_cast<uint32_t>(write_size))))
break;
const streamsize fwritten = static_cast<streamsize>(f.get_io_status_block().Information);
assert(fwritten == write_size);
if(fwritten != write_size)
break;
pending -= chunk_size;
from += chunk_size;
}while(pending > 0);
}
__ntl_catch(...){
f.release();
__ntl_rethrow;
}
f.release();
return n - pending;
}
streamsize write(const char_type* data, streamsize n)
{
return (is_console_handle && known_char_type)
? console_write(data,n)
: file_write(data, n);
}
///\name read functions
streamsize console_read(char* where, streamsize max_size)
{
uint32_t readed = 0;
//console::mode_type mode = console::mode(outh, console::DefaultMode);
ReadConsoleA(outh, where, static_cast<uint32_t>(max_size), &readed, nullptr);
//console::mode(outh, mode);
return readed;
}
streamsize console_read(wchar_t* where, streamsize max_size)
{
uint32_t readed = 0;
//console::mode_type mode = console::mode(outh, console::DefaultMode);
ReadConsoleW(outh, where, static_cast<uint32_t>(max_size), &readed, nullptr);
//console::mode(outh, mode);
return readed;
}
streamsize file_read(char_type* where, streamsize max_size)
{
typedef char fromT;
typedef std::codecvt<char_type,char,traits::state_type> codecvt;
static const codecvt& cvt = std::use_facet<codecvt>(this->getloc());
using std::codecvt_base;
char_type* to_next;
fromT buf[1024];
const fromT *from_next;
streamsize readed = 0;
NTL_SUBSYSTEM_NS::file_handler f; f.reset(outh);
__ntl_try{
for(;;){
streamsize cb = std::min(max_size*sizeof(fromT), _countof(buf));
if(!NTL_SUBSYSTEM_NS::success(f.read(buf, static_cast<uint32_t>(cb))))
break;
streamsize freaded = static_cast<streamsize>(f.get_io_status_block().Information);
assert(freaded > 0);
freaded /= sizeof(fromT);
traits::state_type state;
codecvt_base::result re = cvt.in(state, buf, buf+freaded, from_next, where, where+max_size, to_next);
if(re == codecvt_base::error)
break;
else if(re == codecvt_base::noconv){
readed = freaded;
traits_type::copy(where, reinterpret_cast<const char_type*>(buf), readed);
}else{
readed = to_next-where;
}
break;
}
}
__ntl_catch(...){
f.release();
__ntl_rethrow;
}
f.release();
return readed;
}
streamsize read(char_type* where, streamsize max_size)
{
return (is_console_handle && known_char_type)
? console_read(where,max_size)
: file_read(where, max_size);
}
///\}
private:
char_type* buffer;
legacy_handle outh;
const bool is_console_handle, write_only;
static const bool known_char_type = std::is_same<char_type, char>::value || std::is_same<char_type, wchar_t>::value;
console_buffer(const console_buffer&) __deleted;
console_buffer& operator=(console_buffer&) __deleted;
};
/**@} console_stream */
/**@} console */
}//namespace win
}//namespace ntl
#endif//#ifndef NTL__WIN_CONSOLE
| true |
f6118214604c597b1938ea981a0636bac97ae587 | C++ | CORaisch/Smart-Car | /src/Rendering/Models/Car.cpp | UTF-8 | 3,502 | 2.625 | 3 | [] | no_license | #include "Rendering/Models/Car.h"
using namespace Rendering;
using namespace Models;
Car::Car() {}
Car::~Car() {
//is going to be deleted in Models.cpp
}
void Car::Create() {
GLuint vao;
GLuint vbo;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
//Get Size of Screen to Scale Model
int screen_x, screen_y;
this->camera->getSize(screen_x, screen_y);
//Init Texture
glGenTextures(1, &(this->texID));
glBindTexture(GL_TEXTURE_2D, this->texID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//Load Image using SOIL
unsigned char* image = SOIL_load_image("../data/car.png", &(this->tex_width), &(this->tex_height), 0, SOIL_LOAD_RGBA);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, this->tex_width, this->tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
SOIL_free_image_data(image);
//Load Vertex Data
this->vertices.push_back(VertexFormat(glm::vec4(-screen_x / 64, -screen_y / 24, 0.0, 1.0), glm::vec2(1, 1)));
this->vertices.push_back(VertexFormat(glm::vec4(screen_x / 64, -screen_y / 24, 0.0, 1.0), glm::vec2(1, 0)));
this->vertices.push_back(VertexFormat(glm::vec4(-screen_x / 64, screen_y / 24, 0.0, 1.0), glm::vec2(0, 1)));
this->vertices.push_back(VertexFormat(glm::vec4(-screen_x / 64, screen_y / 24, 0.0, 1.0), glm::vec2(0, 1)));
this->vertices.push_back(VertexFormat(glm::vec4(screen_x / 64, -screen_y / 24, 0.0, 1.0), glm::vec2(1, 0)));
this->vertices.push_back(VertexFormat(glm::vec4(screen_x / 64, screen_y / 24, 0.0, 1.0), glm::vec2(0, 0)));
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(VertexFormat) * 6, &vertices[0], GL_STATIC_DRAW);
glBindVertexArray(0);
//here we assign the values
this->vao = vao;
this->vbos.push_back(vbo);
this->model_matrix = glm::translate(glm::mat4(1.), glm::vec3(float(screen_x / 2), float(screen_y / 2), 0.0f));
this->modelID = glGetUniformLocation(program, "M");
this->viewID = glGetUniformLocation(program, "V");
this->projectID = glGetUniformLocation(program, "P");
}
void Car::Update(float dt) {
//Update Camera
viewMatrix = this->camera->getView();
projectMatrix = this->camera->getProjection();
}
void Car::Draw() {
glUseProgram(program);
glUniformMatrix4fv(this->modelID, 1, GL_FALSE, &this->model_matrix[0][0]);
glUniformMatrix4fv(this->viewID, 1, GL_FALSE, &this->viewMatrix[0][0]);
glUniformMatrix4fv(this->projectID, 1, GL_FALSE, &this->projectMatrix[0][0]);
glBindVertexArray(this->vao);
glBindBuffer(GL_ARRAY_BUFFER, this->vbos[0]);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(offsetof(VertexFormat, VertexFormat::position)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(offsetof(VertexFormat, VertexFormat::color)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(VertexFormat), (void*)(offsetof(VertexFormat, VertexFormat::texcoord)));
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
| true |
1c37e0197e5599b59ff8914b0a1c72876bccc60b | C++ | onewordstudios/sweetspace | /cugl/include/cugl/2d/actions/CUAnimateAction.h | UTF-8 | 12,978 | 2.78125 | 3 | [] | no_license | //
// CUAnimateAction.h
// Cornell University Game Library (CUGL)
//
// This module provides support for filmstrip animation. The animation is
// is represented as a sequence of frames. There is no tweening support
// between animation frames.
//
// This class uses our standard shared-pointer architecture.
//
// 1. The constructor does not perform any initialization; it just sets all
// attributes to their defaults.
//
// 2. All initialization takes place via init methods, which can fail if an
// object is initialized more than once.
//
// 3. All allocation takes place via static constructors which return a shared
// pointer.
//
// CUGL MIT License:
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
// Author: Sophie Huang
// Version: 11/1/16
#ifndef __CU_ANIMATE_ACTION_H__
#define __CU_ANIMATE_ACTION_H__
#include "CUAction.h"
namespace cugl {
/**
* This action represents a sequence of film-strip frames for animation
*
* Each frame in the sequence is given a set amount of time to display. The
* animation will not tween between frames. To do so would require a refactoring
* of the scene graph nodes.
*
* An action contains only the definition of the animation. This can include
* information about the transform to use or the duration of the animation.
* However, it does not contain any attribute of the target. Hence, an action
* can be reapplied to different targets.
*
* By itself, an action does nothing. It only specifies an action that may
* take place. To use an action, it must be passed to the ActionManager. The
* manager will create an action instance and animate that instance. While an
* action may be reused many times, an action instance corresponds to a single
* animation.
*/
class Animate : public Action {
protected:
/** The list of frames to animate */
std::vector<int> _frameset;
/** The amount of time for each frame */
std::vector<float> _timestep;
/** Whether or not the timestep is uniform */
bool _uniform;
public:
#pragma mark Constructors
/**
* Creates an uninitialized animation action.
*
* NEVER USE A CONSTRUCTOR WITH NEW. If you want to allocate an object on
* the heap, use one of the static constructors instead.
*/
Animate() : _uniform(true) {}
/**
* Deletes this action instance, disposing all resources
*/
~Animate() { dispose(); }
/**
* Disposes all of the resources used by this action.
*
* A disposed action can be safely reinitialized.
*/
void dispose();
/**
* Initializes a degenerate animation action.
*
* The animation sequence is empty, meaning no animation takes place.
*
* @return true if initialization was successful.
*/
bool init() { return true; }
/**
* Initializes an animation sequence of frames start to end (inclusive).
*
* The animation sequence has start as its first frame and end as its last.
* Animation will be in frame order, with an equal amount of time spent
* on each frame. The value start must be less than (or equal to) end, as
* this action does not know the filmstrip length.
*
* The repeat argument is optional. It specifies the number of time to
* repeat the animation sequence. The total animation time will include
* all repeats.
*
* @param start The initial frame to animate
* @param end The final frame to animate
* @param time The animation duration
* @param repeat The number of times to repeat the sequence
*
* @return true if initialization was successful.
*/
bool init(int start, int end, float time, int repeat = 1);
/**
* Initializes an animation sequence of uniform speed
*
* The animation sequence is given by the specified vector. The animation
* will spend an equal amount of time on each frame, so that the total time
* spent animating is the one specified.
*
* @param frames The animation sequence
* @param time The animation duration
*
* @return true if initialization was successful.
*/
bool init(const std::vector<int>& frames, float time);
/**
* Initializes an animation sequence of variable speed
*
* The animation sequence is given by the first specified vector. The
* second vector specifies the number of seconds to spend on each frame.
* the overall animation duration is the sum of this vector.
*
* Both vectors must be the same length. They can be empty.
*
* @param frames The animation sequence
* @param time The duration of each frame in the sequences
*
* @return true if initialization was successful.
*/
bool init(const std::vector<int>& frames, const std::vector<float>& time);
#pragma mark Static Constructors
/**
* Returns a newly allocated, degenerate animation action.
*
* The animation sequence is empty, meaning no animation takes place.
*
* @return a newly allocated, degenerate animation action.
*/
static std::shared_ptr<Animate> alloc() {
std::shared_ptr<Animate> result = std::make_shared<Animate>();
return (result->init() ? result : nullptr);
}
/**
* Returns a newly allocated animation sequence of frames start to end (inclusive).
*
* The animation sequence has start as its first frame and end as its last.
* Animation will be in frame order, with an equal amount of time spent
* on each frame. The value start must be less than (or equal to) end, as
* this action does not know the filmstrip length.\
*
* The repeat argument is optional. It specifies the number of time to
* repeat the animation sequence. The total animation time will include
* all repeats.
*
* @param start The initial frame to animate
* @param end The final frame to animate
* @param time The animation duration
* @param repeat The number of times to repeat the sequence
*
* @return a newly allocated animation sequence of frames start to end (inclusive).
*/
static std::shared_ptr<Animate> alloc(int start, int end, float time, int repeat = 1) {
std::shared_ptr<Animate> result = std::make_shared<Animate>();
return (result->init(start,end,time,repeat) ? result : nullptr);
}
/**
* Returns a newly allocated animation sequence of uniform speed
*
* The animation sequence is given by the specified vector. The animation
* will spend an equal amount of time on each frame, so that the total time
* spent animating is the one specified.
*
* @param frames The animation sequence
* @param time The animation duration
*
* @return a newly allocated animation sequence of uniform speed
*/
static std::shared_ptr<Animate> alloc(const std::vector<int>& frames, float time) {
std::shared_ptr<Animate> result = std::make_shared<Animate>();
return (result->init(frames,time) ? result : nullptr);
}
/**
* Returns a newly allocated animation sequence of variable speed
*
* The animation sequence is given by the first specified vector. The
* second vector specifies the number of seconds to spend on each frame.
* the overall animation duration is the sum of this vector.
*
* Both vectors must be the same length. They can be empty.
*
* @param frames The animation sequence
* @param time The duration of each frame in the sequences
*
* @return a newly allocated animation sequence of variable speed
*/
static std::shared_ptr<Animate> alloc(const std::vector<int>& frames, const std::vector<float>& time) {
std::shared_ptr<Animate> result = std::make_shared<Animate>();
return (result->init(frames,time) ? result : nullptr);
}
#pragma mark Atributes
/**
* Returns the frame in the filmstrip to be animated at time index t in [0,1]
*
* @return the frame in the filmstrip to be animated at time index t in [0,1]
*/
int getFrame(float t) const;
/**
* Returns the sequence of frames used in this animation
*
* Changing this value for an actively animating action can have
* undefined effects.
*
* @return the sequence of frames used in this animation
*/
const std::vector<int>& getSequence() const { return _frameset; }
/**
* Returns individual time steps for each frame
*
* If this animation uses a uniform time step for each frame, this set
* will be empty.
*
* Changing this value for an actively animating action can have
* undefined effects.
*
* @return the sequence of frames used in this animation
*/
const std::vector<float>& getTimeSteps() const { return _timestep; }
/**
* Sets the sequence of frames used in this animation
*
* If this set has a different size than the one initial set, this setter
* will keep the overall animation duration, but will revert to a uniform
* time step.
*
* Changing this value for an actively animating action can have
* undefined effects.
*
* @param frames the sequence of frames used in this animation
*/
void setSequence(const std::vector<int>& frames);
/**
* Sets the sequence of frames used in this animation
*
* Both vectors must be the same length. They can be empty.
*
* Changing this value for an actively animating action can have
* undefined effects.
*
* @param frames the sequence of frames used in this animation
* @param time the time to devote animating each frame
*/
void setSequence(const std::vector<int>& frames, const std::vector<float>& time);
/**
* Returns true if this animation uses a uniform time step for all frames
*
* Changing this value for an actively animating action can have
* undefined effects.
*
* @return true if this animation uses a uniform time step for all frames
*/
int isUniform() const { return _uniform; }
/**
* Forces this animation to use a uniform time step for all frames
*
* Changing this value for an actively animating action can have
* undefined effects.
*/
void setUniform();
#pragma mark Animation Methods
/**
* Returns a newly allocated copy of this Action.
*
* @return a newly allocated copy of this Action.
*/
virtual std::shared_ptr<Action> clone() override;
/**
* Prepares a target for action
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
*/
virtual void load(const std::shared_ptr<Node>& target, Uint64* state) override;
/**
* Executes an action on the given target node.
*
* The important state of the target is stored in the given state parameter.
* The semantics of this state is action-dependent.
*
* @param target The node to act on
* @param state The relevant node state
* @param dt The elapsed time to animate.
*/
virtual void update(const std::shared_ptr<Node>& target, Uint64* state, float dt) override;
#pragma mark Debugging Methods
/**
* Returns a string representation of the action for debugging purposes.
*
* If verbose is true, the string will include class information. This
* allows us to unambiguously identify the class.
*
* @param verbose Whether to include class information
*
* @return a string representation of this action for debuggging purposes.
*/
virtual std::string toString(bool verbose = false) const override;
};
}
#endif /* __CU_ANIMATE_ACTION_H__ */
| true |
511163ea4305e095ab992848b137d7e7a9850c6e | C++ | kelompok-oop-sekar/reimagined-octo-funicular | /FarmAnimal/Chicken.cpp | UTF-8 | 1,799 | 2.96875 | 3 | [] | no_license | # include <iostream>
# include <cstdlib>
# include <ctime>
# include "Chicken.h"
using namespace std;
string Chicken::className = "Chicken";
Chicken::Chicken(int _x, int _y) : EggProducingFarmAnimal(_x,_y,true) , MeatProducingFarmAnimal(_x,_y,true) , FarmAnimal(_x,_y)
{
tickDie = 5;
tickHungry = 7;
}
string Chicken::getClassName()
{
return className;
}
void Chicken::moveAnimal() // method pergerakan Chicken
{
int randomVal = 1 + rand() % 4;
switch (randomVal) {
case 1: {
if ((FarmAnimal::x + 1) >= 0 && (FarmAnimal::x + 1 <= 7) && !isObjectExist(x + 1, y)) {
FarmAnimal::x++;
}
}
break;
case 2: {
if ((FarmAnimal::x - 1) >= 0 && (FarmAnimal::x - 1 <= 7) && !isObjectExist(x - 1, y)) {
FarmAnimal::x--;
}
}
break;
case 3: {
if ((FarmAnimal::y + 1) >= 6 && (FarmAnimal::y + 1 <= 7) && !isObjectExist(x, y + 1)) {
FarmAnimal::y++;
}
}
break;
case 4: {
if ((FarmAnimal::y - 1) >= 6 && (FarmAnimal::y - 1 <= 7) && !isObjectExist(x, y - 1)) {
FarmAnimal::y--;
}
}
break;
default: {
// do nothing
}
}
if (tickHungry > 0) {
tickHungry--;
}
if (tickHungry == 0) {
tickDie--;
}
}
bool Chicken::isHungry() // menghasilkan true jika Chicken dalam keadaan lapar
{
return tickHungry==0;
}
void Chicken::eat(LinkedList<Cell*> List)
{
if (tickDie < 5) {
if ((Map[x][y] == '@' || Map[x][y] == '#' || Map[x][y] == '*')) {
FarmAnimal::eat(List);
EggProducingFarmAnimal::egg == true;
tickDie = 5;
tickHungry = 7;
}
}
}
void Chicken::sounding() // menuliskan "Petok.. Petok.." ke layar ketika player melakukan Talk
{
cout << "Petok.. Petok.." << endl;
}
char Chicken::render()
{
if (isHungry()){
return 'i';
} else {
return 'I';
}
}
bool Chicken::isDie() {
return tickDie <= 0;
} | true |
1f3cd2604efbcf1166e050d29d2bd4930a74979d | C++ | DunsanyInteractive/RAD | /DirectX/Guicon.cpp | UTF-8 | 2,410 | 2.515625 | 3 | [] | no_license | /*
* Guicon.cpp
* Rad Adventure Development
*
* Created by Oliver Plunkett
* Copyright 2010 Dunsany Interactive. All rights reserved.
*
*/
#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include "Guicon.h"
#include "../LuaEngine.h"
#ifndef _USE_OLD_IOSTREAMS
using namespace std;
#endif
// maximum mumber of lines the output console should have
static const WORD MAX_CONSOLE_LINES = 500;
const char *LIB_NAME = "print";
#ifdef _DEBUG
void RedirectIOToConsole() {
int hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
ios::sync_with_stdio();
luaopen_myprint(LuaEngine::state);
}
static int l_print(lua_State *L) {
std::string output = lua_tostring(L, 1);
std::cout << "LUA OUTPUT :> " << output.c_str() << std::endl;
return 0;
}
static const struct luaL_Reg winprint[] = {
{"print", l_print},
{NULL, NULL}
};
int luaopen_myprint(lua_State *L) {
luaL_register(L,"winprint", winprint);
luaL_dostring(L, "print = winprint.print");
luaL_dostring(L, "print('Using windows print override for efficent output handeling!')");
return 0;
}
#endif
//End of File
| true |
293cc22fdd50bffc69fdcf871ec7b8d32a78f3a7 | C++ | kyun2024/ProgramSolve | /4375.cpp | UTF-8 | 1,304 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <queue>
#include <memory>
using namespace std;
int main(){
unsigned int input_n{};
int i{},j{},sum{};
int start_index{},coef{},mul_val{};
queue<int> Q;
input_n = 0;
while(true){
cin >> input_n;
if(cin.eof()){
break;
}
if(input_n%2==0 || input_n%5 == 0){
std::cout << -1 << endl;
continue;
}
if(input_n == 1){
std::cout << 1 << endl;
continue;
}
start_index = static_cast<int>(ceil(log10(input_n)));
coef = static_cast<int>(pow(10,start_index))%input_n;
/*
Q.swap(*unique_ptr<decltype(Q),void(*)(decltype(Q)*)>(new decltype(Q)(),[](auto obj){
cout << "Destruct Called" << endl;
delete obj;
}));
*/
Q.swap(*unique_ptr<decltype(Q)>(new decltype(Q)()));
sum = 0;
for(i=0;i<start_index;i++){
sum = sum + static_cast<int>(pow(10,i));
Q.push(pow(10,i));
}
for(i=start_index;sum%input_n!=0;i++){
mul_val = (Q.front() * coef)%input_n;
sum = (sum + mul_val)%input_n;
Q.push(mul_val);
Q.pop();
}
cout << i << endl;
}
} | true |
3a338c91c9165a17666bb83b7367ad946147fb41 | C++ | vladotrocol/bubble_source | /Source Code/DisplayKernel/OgreApplications/RobotSimulation.h | UTF-8 | 2,321 | 2.78125 | 3 | [] | no_license | #ifndef _ROBOT_SCENE_MANAGER_H
#define _ROBOT_SCENE_MANAGER_H
#include "./DisplayKernel/OgreApplications/SimulationManager.h"
class RobotSimulationManager: public SimulationManager{
Ogre::Entity *e;
Ogre::AnimationState* mAnimationState;
public:
std::vector<Ogre::AnimationState*> animations;
RobotSimulationManager(){;}
void createScene(Ogre::SceneManager* scene, Ogre::SceneNode* rootNode){
//This is the very first thing you must do. Moreover if you are planning to use createAxis or createTablePlane
this->rootNode=rootNode;
mSceneMgr=scene;
createTablePlane(5.1,2.8,-1.0, rootNode );//Size and depth of the mask panel
//rootNode->scale(0.2f,0.2f,0.2f);
createAxis();
int even=0;
for(float i=-2.4f;i<2.5f;i+=0.55f)
for(float j=-1.2f;j<1.5f;j+=0.55f){
e=scene->createEntity("robot.mesh");
if(++even%2)
mAnimationState = e->getAnimationState("Idle");
else
mAnimationState = e->getAnimationState("Walk");
mAnimationState->setLoop(true);
mAnimationState->setEnabled(true);
animations.push_back(mAnimationState);
Ogre::SceneNode* robotNode=rootNode->createChildSceneNode();
Ogre::SceneNode* fixedNode=robotNode->createChildSceneNode();
fixedNode->scale(0.012f,0.012f,0.014f);
fixedNode->pitch(Ogre::Radian(1.5708f));
fixedNode->attachObject(e);
robotNode->setPosition(i,j,-1.2f);
}
}
void update(float timeSinceLastFrame){
for(size_t i=0;i<animations.size();i++)
switch(i%3){
case 0:
animations[i]->addTime(timeSinceLastFrame);
break;
case 1:
animations[i]->addTime(1.25f*timeSinceLastFrame);
break;
case 2:
animations[i]->addTime(0.8f*timeSinceLastFrame);
break;
}
}
virtual void keyPressed( const OIS::KeyEvent &arg ){
if( arg.key == OIS::KC_F1)
{
//Translate +0.1 in the Z axis.
rootNode->translate(0,0,0.1);
}
if(arg.key == OIS::KC_F2)
{
//Translate -0.1 in the Z axis.
rootNode->translate(0,0,-0.1);
}
}
virtual void mouseMoved( const OIS::MouseEvent &arg ){
//arg.state.X.rel ->Horizonjtal movement
//arg.state.Y.rel -> Vertical movement
//arg.state.Z.rel -> Wheel movement
if(arg.state.Z.rel==0)
return ;
if(arg.state.Z.rel>0)
rootNode->translate(0,0,0.1);
else
rootNode->translate(0,0,-0.1);
}
};
#endif | true |
a0d2d38795272380a07fd6cb7f1535f5fc8530aa | C++ | Manny500/Sample-Code | /Cloud11Gaming-Alpha/VelocityEngine/StructuralCore/AccessOverride.cpp | UTF-8 | 1,703 | 3.4375 | 3 | [] | no_license | #include "AccessOverride.h"
/**
* @brief AccessOverride::AccessOverride
*/
AccessOverride::AccessOverride(){
this->extraAccesses = new std::vector<Accessible*>;
}
AccessOverride::~AccessOverride(){
removeAllExtraAccesses();
delete this->extraAccesses;
this->playerAccess = NULL;
this->playerGroupAccess = NULL;
this->componentAccess = NULL;
this->locationAccess = NULL;
this->componentStackAccess = NULL;
this->access1 = NULL;
this->access2 = NULL;
this->access3 = NULL;
this->access4 = NULL;
this->extraAccesses = NULL;
}
/**
* @brief AccessOverride::getExtraAccess will get the left over capacity in acess
* @param index is the index to look for space
* @return will return an accessable variable
*/
Accessible* AccessOverride::getExtraAccess(unsigned int index){
return this->extraAccesses->at(index);
}
/**
* @brief AccessOverride::addExtraAccess will add extra space
* @param accessible is the space to be added
* @return will return the size of the new space
*/
unsigned int AccessOverride::addExtraAccess(Accessible* accessible){
this->extraAccesses->push_back(accessible);
return this->extraAccesses->size()-1;
}
/**
* @brief AccessOverride::removeExtraAccessAt will remove any extra spaces
* @param index the space to be removed
*/
void AccessOverride::removeExtraAccessAt(unsigned int index){
this->extraAccesses->at(index) = this->extraAccesses->at(this->extraAccesses->size() - 1);
this->extraAccesses->pop_back();
}
/**
* @brief AccessOverride::removeAllExtraAccesses will remove all extra spaceses
*/
void AccessOverride::removeAllExtraAccesses(){
this->extraAccesses->clear();
}
| true |
3b09310a2c9bc99bc3e1699bf8b7f0b53593d89c | C++ | dendibakh/Algorithm-Tasks | /Coursera class/Coursera Assignments/Seam Carving/Seam Carving/Seam Carving.cpp | UTF-8 | 3,280 | 2.953125 | 3 | [] | no_license | #include "Seam Carving.h"
#include <limits>
pixelsEnergy calcPixelsEnergy(const PicturePixels& pixels)
{
pixelsEnergy pixEnergy(pixels.size(), std::vector<int>(pixels[0].size(), 0));
int height = static_cast<int>(pixels.size());
int width = static_cast<int>(pixels[0].size());
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
if ((i == 0) || (i == height - 1) || (j == 0) || (j == width - 1))
{
pixEnergy[i][j] = 195075; // 255^2 + 255^2 + 255^2
}
else
{
int Rx = pixels[i][j+1][0] - pixels[i][j-1][0];
int Gx = pixels[i][j+1][1] - pixels[i][j-1][1];
int Bx = pixels[i][j+1][2] - pixels[i][j-1][2];
int Ry = pixels[i+1][j][0] - pixels[i-1][j][0];
int Gy = pixels[i+1][j][1] - pixels[i-1][j][1];
int By = pixels[i+1][j][2] - pixels[i-1][j][2];
pixEnergy[i][j] = Rx*Rx + Gx*Gx + Bx*Bx + Ry*Ry + Gy*Gy + By*By;
}
}
}
return pixEnergy;
}
SeamCarver::SeamCarver(const PicturePixels& pixels) : pixels(pixels), pixEnergy(calcPixelsEnergy(pixels))
{
}
int SeamCarver::getWidth()
{
return static_cast<int>(pixEnergy[0].size());
}
int SeamCarver::getHeight()
{
return static_cast<int>(pixEnergy.size());
}
int SeamCarver::getEnergy(int x, int y)
{
return pixEnergy[y][x];
}
DijkstraSP::PathToStack SeamCarver::findHorizontalSeam()
{
DijkstraSP::PathToStack seam;
return seam;
}
DijkstraSP::PathToStack SeamCarver::findVerticalSeam()
{
// build horizontal graph
int height = getHeight();
int width = getWidth();
EWDiGraph graph(height * width + 2);
for (int i = 0; i < height - 1; ++i)
{
for (int j = 0; j < width; ++j)
{
int curVertex = i * width + j;
int belowVertex = (i + 1) * width + j;
if (j > 0)
graph.addEdge(Edge(curVertex, belowVertex - 1, pixEnergy[i][j]));
graph.addEdge(Edge(curVertex, belowVertex, pixEnergy[i][j]));
if (j < width - 1)
graph.addEdge(Edge(curVertex, belowVertex + 1, pixEnergy[i][j]));
}
}
// add source and target vertex to graph
int source = height * width;
int target = height * width + 1;
int lastRowBeginIndex = (height - 1) * width;
for (int i = 0; i < width; ++i)
{
graph.addEdge(Edge(source, i, 0));
graph.addEdge(Edge(lastRowBeginIndex + i, target, 0));
}
// find seam with minimal energy
DijkstraSP::PathToStack seam;
DijkstraSP DSP(graph, source);
if (!DSP.hasPathTo(target))
return seam;
seam = std::move(DSP.pathTo(target));
seam.pop_front(); // remove target
seam.pop_back(); // remove source
return seam;
}
void SeamCarver::removeHorizontalSeam(const DijkstraSP::PathToStack& seam)
{
}
void SeamCarver::removeVerticalSeam(const DijkstraSP::PathToStack& seam)
{
int height = getHeight();
int width = getWidth();
for (auto i = seam.begin(); i != seam.end(); ++i)
{
int toRemove = *i;
int y = toRemove / width;
int x = toRemove % width;
pixels[y].erase((pixels[y].begin() + x));
pixEnergy[y].erase((pixEnergy[y].begin() + x));
}
}
PicturePixels SeamCarver::getPixels()
{
return pixels;
} | true |
16bcc228cd90075504ab2110049b6e82093777bb | C++ | andonghun/portfolio | /SW Expert Academy/swea_6/1249_안동훈.cpp | UTF-8 | 1,270 | 2.546875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int N;
int mmap[102][102];
int hour[102][102];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
void bfs(int x, int y){
queue<pair<int, int>> q;
q.push({x, y});
hour[1][1] = 0;
while(!q.empty()){
auto cur = q.front();
q.pop();
for(int i=0; i<4; i++){
int nx = cur.first + dx[i];
int ny = cur.second + dy[i];
if(mmap[nx][ny] == -1) continue;
if(hour[nx][ny] > mmap[nx][ny] + hour[cur.first][cur.second]){
hour[nx][ny] = mmap[nx][ny] + hour[cur.first][cur.second];
q.push(make_pair(nx, ny));
}
}
}
return;
}
int main(int argc, char** argv)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
int test_case;
int T;
string s;
cin>>T;
for(test_case = 1; test_case <= T; ++test_case)
{
cin >> N;
memset(mmap, -1, sizeof(mmap));
memset(hour, 1000000, sizeof(hour));
for(int i=1; i<=N; i++){
cin >> s;
for(int j=0; j<N; j++){
mmap[i][j+1] = s[j] - 48;
}
}
bfs(1,1);
cout << "#" << test_case << " " << hour[N][N] << '\n';
}
return 0;
} | true |
6b38471e7d561cff436dae69171cf966cc42d8f4 | C++ | k2-fsa/k2 | /k2/python/csrc/torch/v2/doc/any.h | UTF-8 | 61,192 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | /**
* @copyright
* Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang)
*
* @copyright
* See LICENSE for clarification regarding multiple authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef K2_PYTHON_CSRC_TORCH_V2_DOC_ANY_H_
#define K2_PYTHON_CSRC_TORCH_V2_DOC_ANY_H_
namespace k2 {
static constexpr const char *kCreateRaggedTensorDataDoc = R"doc(
Create a ragged tensor with arbitrary number of axes.
Note:
A ragged tensor has at least two axes.
Hint:
The returned tensor is on CPU.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.create_ragged_tensor([ [1, 2], [5], [], [9] ])
>>> a
RaggedTensor([[1, 2],
[5],
[],
[9]], dtype=torch.int32)
>>> a.dtype
torch.int32
>>> b = k2r.create_ragged_tensor([ [1, 3.0], [] ])
>>> b
RaggedTensor([[1, 3],
[]], dtype=torch.float32)
>>> b.dtype
torch.float32
>>> c = k2r.create_ragged_tensor([ [1] ], dtype=torch.float64)
>>> c.dtype
torch.float64
>>> d = k2r.create_ragged_tensor([ [[1], [2, 3]], [[4], []] ])
>>> d
RaggedTensor([[[1],
[2, 3]],
[[4],
[]]], dtype=torch.int32)
>>> d.num_axes
3
>>> e = k2r.create_ragged_tensor([])
>>> e
RaggedTensor([], dtype=torch.int32)
>>> e.num_axes
2
>>> e.shape.row_splits(1)
tensor([0], dtype=torch.int32)
>>> e.shape.row_ids(1)
tensor([], dtype=torch.int32)
>>> f = k2r.create_ragged_tensor([ [1, 2], [], [3] ], device=torch.device('cuda', 0))
>>> f
RaggedTensor([[1, 2],
[],
[3]], device='cuda:0', dtype=torch.int32)
>>> e = k2r.create_ragged_tensor([[1], []], device='cuda:1')
>>> e
RaggedTensor([[1],
[]], device='cuda:1', dtype=torch.int32)
Args:
data:
A list-of sublist(s) of integers or real numbers.
It can have arbitrary number of axes (at least two).
dtype:
Optional. If None, it infers the dtype from ``data``
automatically, which is either ``torch.int32`` or
``torch.float32``. Supported dtypes are: ``torch.int32``,
``torch.float32``, and ``torch.float64``.
device:
It can be either an instance of ``torch.device`` or
a string representing a torch device. Example
values are: ``"cpu"``, ``"cuda:0"``, ``torch.device("cpu")``,
``torch.device("cuda", 0)``.
Returns:
Return a ragged tensor.
)doc";
static constexpr const char *kCreateRaggedTensorStrDoc = R"doc(
Create a ragged tensor from its string representation.
Fields are separated by space(s) **or** comma(s).
An example string for a 2-axis ragged tensor is given below::
[ [1] [2] [3, 4], [5 6 7, 8] ]
An example string for a 3-axis ragged tensor is given below::
[ [[1]] [[]] ]
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.create_ragged_tensor('[ [1] [] [3 4] ]')
>>> a
RaggedTensor([[1],
[],
[3, 4]], dtype=torch.int32)
>>> a.num_axes
2
>>> a.dtype
torch.int32
>>> b = k2r.create_ragged_tensor('[ [[] [3]] [[10]] ]', dtype=torch.float32)
>>> b
[ [ [ ] [ 3 ] ] [ [ 10 ] ] ]
>>> b.dtype
torch.float32
>>> b.num_axes
3
>>> c = k2r.create_ragged_tensor('[[1.]]')
>>> c.dtype
torch.float32
Note:
Number of spaces or commas in ``s`` does not affect the result.
Of course, numbers have to be separated by at least one space or comma.
Args:
s:
A string representation of a ragged tensor.
dtype:
The desired dtype of the tensor. If it is ``None``, it tries
to infer the correct dtype from ``s``, which is assumed to be
either ``torch.int32`` or ``torch.float32``. Supported dtypes are:
``torch.int32``, ``torch.float32``, and ``torch.float64``.
device:
It can be either an instance of ``torch.device`` or
a string representing a torch device. Example
values are: ``"cpu"``, ``"cuda:0"``, ``torch.device("cpu")``,
``torch.device("cuda", 0)``.
Returns:
Return a ragged tensor.
)doc";
static constexpr const char *kCreateRaggedTensorTensorDoc = R"doc(
Create a ragged tensor from a torch tensor.
Note:
It turns a regular tensor into a ragged tensor.
Caution:
The input tensor has to have more than 1 dimension.
That is ``tensor.ndim > 1``.
Also, if the input tensor is contiguous, ``self``
will share the underlying memory with it. Otherwise,
memory of the input tensor is copied to create ``self``.
Supported dtypes of the input tensor are: ``torch.int32``,
``torch.float32``, and ``torch.float64``.
**Example 1**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = torch.arange(6, dtype=torch.int32).reshape(2, 3)
>>> b = k2r.create_ragged_tensor(a)
>>> a
tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> b
RaggedTensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> b.dtype
torch.int32
>>> a.is_contiguous()
True
>>> a[0, 0] = 10
>>> b
RaggedTensor([[10, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> b.values[1] = -2
>>> a
tensor([[10, -2, 2],
[ 3, 4, 5]], dtype=torch.int32)
**Example 2**:
>>> import k2.ragged as k2r
>>> a = torch.arange(24, dtype=torch.int32).reshape(2, 12)[:, ::4]
>>> a
tensor([[ 0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> a.is_contiguous()
False
>>> b = k2r.create_ragged_tensor(a)
>>> b
RaggedTensor([[0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> b.dtype
torch.int32
>>> a[0, 0] = 10
>>> b
RaggedTensor([[0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> a
tensor([[10, 4, 8],
[12, 16, 20]], dtype=torch.int32)
**Example 3**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = torch.arange(24, dtype=torch.float32).reshape(2, 3, 4)
>>> a
tensor([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
[16., 17., 18., 19.],
[20., 21., 22., 23.]]])
>>> b = k2r.create_ragged_tensor(a)
>>> b
RaggedTensor([[[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]], dtype=torch.float32)
Args:
tensor:
An N-D (N > 1) tensor.
Returns:
Return a ragged tensor.
)doc";
static constexpr const char *kRaggedInitFromShapeAndTensorDoc = R"doc(
Create a ragged tensor from a shape and a value.
>>> import torch
>>> import k2.ragged as k2r
>>> shape = k2r.RaggedShape('[ [x x] [] [x x x] ]')
>>> value = torch.tensor([10, 0, 20, 30, 40], dtype=torch.float32)
>>> ragged = k2r.RaggedTensor(shape, value)
>>> ragged
RaggedTensor([[10, 0],
[],
[20, 30, 40]], dtype=torch.float32)
Args:
shape:
The shape of the tensor.
value:
The value of the tensor.
)doc";
static constexpr const char *kRaggedAnyInitDataDeviceDoc = R"doc(
Create a ragged tensor with arbitrary number of axes.
Note:
A ragged tensor has at least two axes.
**Example 1**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [1, 2], [5], [], [9] ])
>>> a
RaggedTensor([[1, 2],
[5],
[],
[9]], dtype=torch.int32)
>>> a.dtype
torch.int32
>>> b = k2r.RaggedTensor([ [1, 3.0], [] ])
>>> b
RaggedTensor([[1, 3],
[]], dtype=torch.float32)
>>> b.dtype
torch.float32
>>> c = k2r.RaggedTensor([ [1] ], dtype=torch.float64)
>>> c
RaggedTensor([[1]], dtype=torch.float64)
>>> c.dtype
torch.float64
>>> d = k2r.RaggedTensor([ [[1], [2, 3]], [[4], []] ])
>>> d
RaggedTensor([[[1],
[2, 3]],
[[4],
[]]], dtype=torch.int32)
>>> d.num_axes
3
>>> e = k2r.RaggedTensor([])
>>> e
RaggedTensor([], dtype=torch.int32)
>>> e.num_axes
2
>>> e.shape.row_splits(1)
tensor([0], dtype=torch.int32)
>>> e.shape.row_ids(1)
tensor([], dtype=torch.int32)
**Example 2**:
>>> k2r.RaggedTensor([ [[1, 2]], [], [[]] ])
RaggedTensor([[[1, 2]],
[],
[[]]], dtype=torch.int32)
>>> k2r.RaggedTensor([ [[1, 2]], [], [[]] ], device='cuda:0')
RaggedTensor([[[1, 2]],
[],
[[]]], device='cuda:0', dtype=torch.int32)
Args:
data:
A list-of sublist(s) of integers or real numbers.
It can have arbitrary number of axes (at least two).
dtype:
Optional. If None, it infers the dtype from ``data``
automatically, which is either ``torch.int32`` or
``torch.float32``. Supported dtypes are: ``torch.int32``,
``torch.float32``, and ``torch.float64``.
device:
It can be either an instance of ``torch.device`` or
a string representing a torch device. Example
values are: ``"cpu"``, ``"cuda:0"``, ``torch.device("cpu")``,
``torch.device("cuda", 0)``.
)doc";
static constexpr const char *kRaggedAnyInitStrDeviceDoc = R"doc(
Create a ragged tensor from its string representation.
Fields are separated by space(s) **or** comma(s).
An example string for a 2-axis ragged tensor is given below::
[ [1] [2] [3, 4], [5 6 7, 8] ]
An example string for a 3-axis ragged tensor is given below::
[ [[1]] [[]] ]
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [1] [] [3 4] ]')
>>> a
RaggedTensor([[1],
[],
[3, 4]], dtype=torch.int32)
>>> a.num_axes
2
>>> a.dtype
torch.int32
>>> b = k2r.RaggedTensor('[ [[] [3]] [[10]] ]', dtype=torch.float32)
>>> b
RaggedTensor([[[],
[3]],
[[10]]], dtype=torch.float32)
>>> b.dtype
torch.float32
>>> b.num_axes
3
>>> c = k2r.RaggedTensor('[[1.]]')
>>> c.dtype
torch.float32
>>> d = k2r.RaggedTensor('[[1.]]', device='cuda:0')
>>> d
RaggedTensor([[1]], device='cuda:0', dtype=torch.float32)
Note:
Number of spaces or commas in ``s`` does not affect the result.
Of course, numbers have to be separated by at least one space or comma.
Args:
s:
A string representation of a ragged tensor.
dtype:
The desired dtype of the tensor. If it is ``None``, it tries
to infer the correct dtype from ``s``, which is assumed to be
either ``torch.int32`` or ``torch.float32``. Supported dtypes are:
``torch.int32``, ``torch.float32``, and ``torch.float64``.
device:
It can be either an instance of ``torch.device`` or
a string representing a torch device. Example
values are: ``"cpu"``, ``"cuda:0"``, ``torch.device("cpu")``,
``torch.device("cuda", 0)``.
)doc";
static constexpr const char *kRaggedAnyInitTensorDoc = R"doc(
Create a ragged tensor from a torch tensor.
Note:
It turns a regular tensor into a ragged tensor.
Caution:
The input tensor has to have more than 1 dimension.
That is ``tensor.ndim > 1``.
Also, if the input tensor is contiguous, ``self``
will share the underlying memory with it. Otherwise,
memory of the input tensor is copied to create ``self``.
Supported dtypes of the input tensor are: ``torch.int32``,
``torch.float32``, and ``torch.float64``.
**Example 1**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = torch.arange(6, dtype=torch.int32).reshape(2, 3)
>>> b = k2r.RaggedTensor(a)
>>> a
tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> b
RaggedTensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> a.is_contiguous()
True
>>> a[0, 0] = 10
>>> b
RaggedTensor([[10, 1, 2],
[3, 4, 5]], dtype=torch.int32)
>>> b.values[1] = -2
>>> a
tensor([[10, -2, 2],
[ 3, 4, 5]], dtype=torch.int32)
**Example 2**:
>>> import k2.ragged as k2r
>>> a = torch.arange(24, dtype=torch.int32).reshape(2, 12)[:, ::4]
>>> a
tensor([[ 0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> a.is_contiguous()
False
>>> b = k2r.RaggedTensor(a)
>>> b
RaggedTensor([[0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> a[0, 0] = 10
>>> b
RaggedTensor([[0, 4, 8],
[12, 16, 20]], dtype=torch.int32)
>>> a
tensor([[10, 4, 8],
[12, 16, 20]], dtype=torch.int32)
**Example 3**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = torch.arange(24, dtype=torch.float32).reshape(2, 3, 4)
>>> a
tensor([[[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]],
[[12., 13., 14., 15.],
[16., 17., 18., 19.],
[20., 21., 22., 23.]]])
>>> b = k2r.RaggedTensor(a)
>>> b
RaggedTensor([[[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]],
[[12, 13, 14, 15],
[16, 17, 18, 19],
[20, 21, 22, 23]]], dtype=torch.float32)
>>> b.dtype
torch.float32
>>> c = torch.tensor([[1, 2]], device='cuda:0', dtype=torch.float32)
>>> k2r.RaggedTensor(c)
RaggedTensor([[1, 2]], device='cuda:0', dtype=torch.float32)
Args:
tensor:
An N-D (N > 1) tensor.
)doc";
static constexpr const char *kRaggedAnyToDeviceDoc = R"doc(
Transfer this tensor to a given device.
Note:
If ``self`` is already on the specified device, return a
ragged tensor sharing the underlying memory with ``self``.
Otherwise, a new tensor is returned.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [2, 3]])
>>> a.device
device(type='cpu')
>>> b = a.to(torch.device('cuda', 0))
>>> b.device
device(type='cuda', index=0)
Args:
device:
The target device to move this tensor.
Returns:
Return a tensor on the given device.
)doc";
static constexpr const char *kRaggedAnyToDeviceStrDoc = R"doc(
Transfer this tensor to a given device.
Note:
If ``self`` is already on the specified device, return a
ragged tensor sharing the underlying memory with ``self``.
Otherwise, a new tensor is returned.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]])
>>> a.device
device(type='cpu')
>>> b = a.to('cuda:0')
>>> b.device
device(type='cuda', index=0)
>>> c = b.to('cpu')
>>> c.device
device(type='cpu')
>>> d = c.to('cuda:1')
>>> d.device
device(type='cuda', index=1)
Args:
device:
The target device to move this tensor.
Note: The device is represented as a string.
Valid strings are: "cpu", "cuda:0", "cuda:1", etc.
Returns:
Return a tensor on the given device.
)doc";
static constexpr const char *kRaggedAnyToDtypeDoc = R"doc(
Convert this tensor to a specific dtype.
Note:
If ``self`` is already of the specified `dtype`, return
a ragged tensor sharing the underlying memory with ``self``.
Otherwise, a new tensor is returned.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [2, 3, 5]])
>>> a.dtype
torch.int32
>>> b = a.to(torch.float64)
>>> b.dtype
torch.float64
Caution:
Currently, only support dtypes ``torch.int32``, ``torch.float32``, and
``torch.float64``. We can support other types if needed.
Args:
dtype:
The `dtype` this tensor should be converted to.
Returns:
Return a tensor of the given `dtype`.
)doc";
static constexpr const char *kRaggedAnyStrDoc = R"doc(
Return a string representation of this tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [2, 3], []])
>>> a
RaggedTensor([[1],
[2, 3],
[]], dtype=torch.int32)
>>> str(a)
'RaggedTensor([[1],\n [2, 3],\n []], dtype=torch.int32)'
>>> b = k2r.RaggedTensor([[1, 2]], device='cuda:0')
>>> b
RaggedTensor([[1, 2]], device='cuda:0', dtype=torch.int32)
)doc";
static constexpr const char *kRaggedAnyToStrSimpleDoc = R"doc(
Convert a ragged tensor to a string representation, which
is more compact than ``self.__str__``.
An example output is given below::
RaggedTensor([[[1, 2, 3], [], [0]], [[2], [3, 10.5]]], dtype=torch.float32)
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1, 2, 3], [], [0]], [[2], [3, 10.5]] ])
>>> a
RaggedTensor([[[1, 2, 3],
[],
[0]],
[[2],
[3, 10.5]]], dtype=torch.float32)
>>> str(a)
'RaggedTensor([[[1, 2, 3],\n [],\n [0]],\n [[2],\n [3, 10.5]]], dtype=torch.float32)'
>>> a.to_str_simple()
'RaggedTensor([[[1, 2, 3], [], [0]], [[2], [3, 10.5]]], dtype=torch.float32)'
)doc";
static constexpr const char *kRaggedAnyGetItemDoc = R"doc(
Select the i-th sublist along axis 0.
Caution:
Support for autograd is to be implemented.
**Example 1**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [[1 3] [] [9]] [[8]] ]')
>>> a
RaggedTensor([[[1, 3],
[],
[9]],
[[8]]], dtype=torch.int32)
>>> a[0]
RaggedTensor([[1, 3],
[],
[9]], dtype=torch.int32)
>>> a[1]
RaggedTensor([[8]], dtype=torch.int32)
**Example 2**:
>>> a = k2r.RaggedTensor('[ [1 3] [9] [8] ]')
>>> a
RaggedTensor([[1, 3],
[9],
[8]], dtype=torch.int32)
>>> a[0]
tensor([1, 3], dtype=torch.int32)
>>> a[1]
tensor([9], dtype=torch.int32)
Args:
i:
The i-th sublist along axis 0.
Returns:
Return a new ragged tensor with one fewer axis. If `num_axes == 2`, the
return value will be a 1D tensor.
)doc";
static constexpr const char *kRaggedAnyGetItemSliceDoc = R"doc(
Slices sublists along axis 0 with the given range. Only support slicing step
equals to 1.
Caution:
Support for autograd is to be implemented.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [[1 3] [] [9]] [[8]] [[10 11]] ]')
>>> a
RaggedTensor([[[1, 3],
[],
[9]],
[[8]],
[[10, 11]]], dtype=torch.int32)
>>> a[0:2]
RaggedTensor([[[1, 3],
[],
[9]],
[[8]]], dtype=torch.int32)
>>> a[1:2]
RaggedTensor([[[8]]], dtype=torch.int32)
Args:
key:
Slice containing integer constants.
Returns:
Return a new ragged tensor with the same axes as original ragged tensor, but
only contains the sublists within the range.
)doc";
static constexpr const char *kRaggedAnyGetItem1DTensorDoc = R"doc(
Slice a ragged tensor along axis 0 using a 1-D torch.int32 tensor.
**Example 1**:
>>> import k2
>>> a = k2.RaggedTensor([[1, 2, 0], [0, 1], [2, 3]])
>>> b = k2.RaggedTensor([[10, 20], [300], [-10, 0, -1], [-2, 4, 5]])
>>> a[0]
tensor([1, 2, 0], dtype=torch.int32)
>>> b[a[0]]
RaggedTensor([[300],
[-10, 0, -1],
[10, 20]], dtype=torch.int32)
>>> a[1]
tensor([0, 1], dtype=torch.int32)
>>> b[a[1]]
RaggedTensor([[10, 20],
[300]], dtype=torch.int32)
>>> a[2]
tensor([2, 3], dtype=torch.int32)
>>> b[a[2]]
RaggedTensor([[-10, 0, -1],
[-2, 4, 5]], dtype=torch.int32)
**Example 2**:
>>> import torch
>>> import k2
>>> a = k2.RaggedTensor([ [[1], [2, 3], [0]], [[], [2]], [[10, 20]] ])
>>> i = torch.tensor([0, 2, 1, 0], dtype=torch.int32)
>>> a[i]
RaggedTensor([[[1],
[2, 3],
[0]],
[[10, 20]],
[[],
[2]],
[[1],
[2, 3],
[0]]], dtype=torch.int32)
Args:
key:
A 1-D torch.int32 tensor containing the indexes to select along
axis 0.
Return:
Return a new ragged tensor with the same number of axes as ``self`` but
only contains the specified sublists.
)doc";
static constexpr const char *kRaggedAnyCloneDoc = R"doc(
Return a copy of this tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2], [3]])
>>> b = a
>>> c = a.clone()
>>> a
RaggedTensor([[1, 2],
[3]], dtype=torch.int32)
>>> b.values[0] = 10
>>> a
RaggedTensor([[10, 2],
[3]], dtype=torch.int32)
>>> c
RaggedTensor([[1, 2],
[3]], dtype=torch.int32)
>>> c.values[0] = -1
>>> c
RaggedTensor([[-1, 2],
[3]], dtype=torch.int32)
>>> a
RaggedTensor([[10, 2],
[3]], dtype=torch.int32)
>>> b
RaggedTensor([[10, 2],
[3]], dtype=torch.int32)
)doc";
static constexpr const char *kRaggedAnyEqDoc = R"doc(
Compare two ragged tensors.
Caution:
The two tensors MUST have the same dtype. Otherwise,
it throws an exception.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]])
>>> b = a.clone()
>>> a == b
True
>>> c = a.to(torch.float32)
>>> try:
... c == b
... except RuntimeError:
... print("raised exception")
Args:
other:
The tensor to be compared.
Returns:
Return ``True`` if the two tensors are equal.
Return ``False`` otherwise.
)doc";
static constexpr const char *kRaggedAnyNeDoc = R"doc(
Compare two ragged tensors.
Caution:
The two tensors MUST have the same dtype. Otherwise,
it throws an exception.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2], [3]])
>>> b = a.clone()
>>> b != a
False
>>> c = k2r.RaggedTensor([[1], [2], [3]])
>>> c != a
True
Args:
other:
The tensor to be compared.
Returns:
Return ``True`` if the two tensors are NOT equal.
Return ``False`` otherwise.
)doc";
static constexpr const char *kRaggedAnyRequiresGradPropDoc = R"doc(
Return ``True`` if gradients need to be computed for this tensor.
Return ``False`` otherwise.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]], dtype=torch.float32)
>>> a.requires_grad
False
>>> a.requires_grad = True
>>> a.requires_grad
True
)doc";
static constexpr const char *kRaggedAnyGradPropDoc = R"doc(
This attribute is ``None`` by default. PyTorch will set it
during ``backward()``.
The attribute will contain the gradients computed and future
calls to ``backward()`` will accumulate (add) gradients into it.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2], [3], [5, 6], []], dtype=torch.float32)
>>> a.requires_grad_(True)
RaggedTensor([[1, 2],
[3],
[5, 6],
[]], dtype=torch.float32)
>>> b = a.sum()
>>> b
tensor([ 3., 3., 11., 0.], grad_fn=<SumFunction>>)
>>> c = b * torch.arange(4)
>>> c.sum().backward()
>>> a.grad
tensor([0., 0., 1., 2., 2.])
)doc";
static constexpr const char *kRaggedAnyRequiresGradMethodDoc = R"doc(
Change if autograd should record operations on this tensor: Set
this tensor's :attr:`requires_grad` attribute **in-place**.
Note:
If this tensor is not a float tensor, PyTorch will throw a
RuntimeError exception.
Caution:
This method ends with an underscore, meaning it changes this tensor
**in-place**.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]], dtype=torch.float64)
>>> a.requires_grad
False
>>> a.requires_grad_(True)
RaggedTensor([[1]], dtype=torch.float64)
>>> a.requires_grad
True
Args:
requires_grad:
If autograd should record operations on this tensor.
Returns:
Return this tensor.
)doc";
static constexpr const char *kRaggedAnySumDoc = R"doc(
Compute the sum of sublists over the last axis of this tensor.
Note:
If a sublist is empty, the sum for it is the provided
``initial_value``.
Note:
This operation supports autograd if this tensor is a float tensor,
i.e., with dtype being torch.float32 or torch.float64.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [[1 2] [] [5]] [[10]] ]', dtype=torch.float32)
>>> a.requires_grad_(True)
RaggedTensor([[[1, 2],
[],
[5]],
[[10]]], dtype=torch.float32)
>>> b = a.sum()
>>> c = (b * torch.arange(4)).sum()
>>> c.backward()
>>> a.grad
tensor([0., 0., 2., 3.])
>>> b
tensor([ 3., 0., 5., 10.], grad_fn=<SumFunction>>)
>>> c
tensor(40., grad_fn=<SumBackward0>)
Args:
initial_value:
This value is added to the sum of each sublist. So when
a sublist is empty, its sum is this value.
Returns:
Return a 1-D tensor with the same dtype of this tensor
containing the computed sum.
)doc";
static constexpr const char *kRaggedAnyLogSumExpDoc = R"doc(
Compute the logsumexp of sublists over the last axis of this tensor.
Note:
It is similar to torch.logsumexp except it accepts a ragged tensor.
See `<https://pytorch.org/docs/stable/generated/torch.logsumexp.html>`_
for definition of logsumexp.
Note:
If a sublist is empty, the logsumexp for it is the provided
``initial_value``.
Note:
This operation only supports float type input,
i.e., with dtype being torch.float32 or torch.float64.
>>> import torch
>>> import k2
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[-0.25, -0.25, -0.25, -0.25], [], [-0.5, -0.5]], dtype=torch.float32)
>>> a.requires_grad_(True)
RaggedTensor([[-0.25, -0.25, -0.25, -0.25],
[],
[-0.5, -0.5]], dtype=torch.float32)
>>> b = a.logsumexp()
>>> b
tensor([1.1363, -inf, 0.1931], grad_fn=<LogSumExpFunction>>)
>>> c = b.sum()
>>> c
tensor(-inf, grad_fn=<SumBackward0>)
>>> c.backward()
>>> a.grad
tensor([0.2500, 0.2500, 0.2500, 0.2500, 0.5000, 0.5000])
>>>
>>> # if a is a 3-d ragged tensor
>>> a = k2r.RaggedTensor([[[-0.25, -0.25, -0.25, -0.25]], [[], [-0.5, -0.5]]], dtype=torch.float32)
>>> a.requires_grad_(True)
RaggedTensor([[[-0.25, -0.25, -0.25, -0.25]],
[[],
[-0.5, -0.5]]], dtype=torch.float32)
>>> b = a.logsumexp()
>>> b
tensor([1.1363, -inf, 0.1931], grad_fn=<LogSumExpFunction>>)
>>> c = b.sum()
>>> c
tensor(-inf, grad_fn=<SumBackward0>)
>>> c.backward()
>>> a.grad
tensor([0.2500, 0.2500, 0.2500, 0.2500, 0.5000, 0.5000])
Args:
initial_value:
If a sublist is empty, its logsumexp is this value.
Returns:
Return a 1-D tensor with the same dtype of this tensor
containing the computed logsumexp.
)doc";
static constexpr const char *kRaggedAnyNumelDoc = R"doc(
Returns:
Return number of elements in this tensor. It equals to
``self.values.numel()``.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [], [3, 4, 5, 6]])
>>> a.numel()
5
>>> b = k2r.RaggedTensor('[ [[1] [] []] [[2 3]]]')
>>> b.numel()
3
>>> c = k2r.RaggedTensor('[[1] [] [3 4 5 6]]')
>>> c.numel()
5
)doc";
static constexpr const char *kRaggedAnyTotSizeDoc = R"doc(
Return the number of elements of an given axis. If axis is 0, it's
equivalent to the property ``dim0``.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [1 2 3] [] [5 8 ] ]')
>>> a.tot_size(0)
3
>>> a.tot_size(1)
5
>>> import k2.ragged as k2r
>>> b = k2r.RaggedTensor('[ [[1 2 3] [] [5 8]] [[] [1 5 9 10 -1] [] [] []] ]')
>>> b.tot_size(0)
2
>>> b.tot_size(1)
8
>>> b.tot_size(2)
10
)doc";
static constexpr const char *kRaggedAnyGetStateDoc = R"doc(
__getstate__(self: k2.RaggedTensor) -> tuple
Requires a tensor with 2 axes or 3 axes. Other number
of axes are not implemented yet.
This method is to support ``pickle``, e.g., used by ``torch.save()``.
You are not expected to call it by yourself.
Returns:
If this tensor has 2 axes, return a tuple containing
(self.row_splits(1), "row_ids1", self.values).
If this tensor has 3 axes, return a tuple containing
(self.row_splits(1), "row_ids1", self.row_splits(1),
"row_ids2", self.values)
Note:
"row_ids1" and "row_ids2" in the returned value is for
backward compatibility.
)doc";
static constexpr const char *kRaggedAnySetStateDoc = R"doc(
__setstate__(self: k2.RaggedTensor, arg0: tuple) -> None
Set the content of this class from ``arg0``.
This method is to support ``pickle``, e.g., used by torch.load().
You are not expected to call it by yourself.
Args:
arg0:
It is the return value from the method ``__getstate__``.
)doc";
static constexpr const char *kRaggedAnyDtypeDoc = R"doc(
Return the dtype of this tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], []])
>>> a.dtype
torch.int32
>>> a = a.to(torch.float32)
>>> a.dtype
torch.float32
>>> b = k2r.RaggedTensor([[3]], dtype=torch.float64)
>>> b.dtype
torch.float64
)doc";
static constexpr const char *kRaggedAnyDeviceDoc = R"doc(
Return the device of this tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]])
>>> a.device
device(type='cpu')
>>> b = a.to(torch.device('cuda', 0))
>>> b.device
device(type='cuda', index=0)
>>> b.device == torch.device('cuda:0')
)doc";
static constexpr const char *kRaggedAnyValuesDoc = R"doc(
Return the underlying memory as a 1-D tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2], [], [5], [], [8, 9, 10]])
>>> a.values
tensor([ 1, 2, 5, 8, 9, 10], dtype=torch.int32)
>>> isinstance(a.values, torch.Tensor)
True
>>> a.values[-2] = -1
>>> a
RaggedTensor([[1, 2],
[],
[5],
[],
[8, -1, 10]], dtype=torch.int32)
>>> a.values[3] = -3
>>> a
RaggedTensor([[1, 2],
[],
[5],
[],
[-3, -1, 10]], dtype=torch.int32)
>>> a.values[2] = -2
>>> a
RaggedTensor([[1, 2],
[],
[-2],
[],
[-3, -1, 10]], dtype=torch.int32)
)doc";
static constexpr const char *kRaggedAnyShapeDoc = R"doc(
Return the shape of this tensor.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [1, 2], [], [3] ])
>>> a.shape
[ [ x x ] [ ] [ x ] ]
>>> type(a.shape)
<class '_k2.ragged.RaggedShape'>
)doc";
static constexpr const char *kRaggedAnyIsCudaDoc = R"doc(
Returns:
Return ``True`` if the tensor is stored on the GPU, ``False``
otherwise.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1]])
>>> a.is_cuda
False
>>> b = a.to(torch.device('cuda', 0))
>>> b.is_cuda
True
)doc";
static constexpr const char *kRaggedAnyNumAxesDoc = R"doc(
Return the number of axes of this tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor('[ [] [] [] [] ]')
>>> a.num_axes
2
>>> b = k2r.RaggedTensor('[ [[] []] [[]] ]')
>>> b.num_axes
3
>>> c = k24.Tensor('[ [ [[] [1]] [[3 4] []] ] [ [[1]] [[2] [3 4]] ] ]')
>>> c.num_axes
4
Returns:
Return number of axes of this tensor, which is at least 2.
)doc";
static constexpr const char *kRaggedAnyDim0Doc = R"doc(
Return number of sublists at axis 0.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [1, 2], [3], [], [], [] ])
>>> a.dim0
5
>>> b = k2r.RaggedTensor('[ [[]] [[] []]]')
>>> b.dim0
2
)doc";
static constexpr const char *kRaggedAnyRemoveAxisDoc = R"doc(
Remove an axis; if it is not the first or last axis, this is done by appending
lists (effectively the axis is combined with the following axis). If it is the
last axis it is just removed and the number of elements may be changed.
Caution:
The tensor has to have more than two axes.
**Example 1**:
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1], [], [0, -1]], [[], [2, 3], []], [[0]], [[]] ])
>>> a
RaggedTensor([[[1],
[],
[0, -1]],
[[],
[2, 3],
[]],
[[0]],
[[]]], dtype=torch.int32)
>>> a.num_axes
3
>>> b = a.remove_axis(0)
>>> b
RaggedTensor([[1],
[],
[0, -1],
[],
[2, 3],
[],
[0],
[]], dtype=torch.int32)
>>> c = a.remove_axis(1)
>>> c
RaggedTensor([[1, 0, -1],
[2, 3],
[0],
[]], dtype=torch.int32)
**Example 2**:
>>> a = k2r.RaggedTensor([ [[[1], [], [2]]], [[[3, 4], [], [5, 6], []]], [[[], [0]]] ])
>>> a.num_axes
4
>>> a
RaggedTensor([[[[1],
[],
[2]]],
[[[3, 4],
[],
[5, 6],
[]]],
[[[],
[0]]]], dtype=torch.int32)
>>> b = a.remove_axis(0)
>>> b
RaggedTensor([[[1],
[],
[2]],
[[3, 4],
[],
[5, 6],
[]],
[[],
[0]]], dtype=torch.int32)
>>> c = a.remove_axis(1)
>>> c
RaggedTensor([[[1],
[],
[2]],
[[3, 4],
[],
[5, 6],
[]],
[[],
[0]]], dtype=torch.int32)
>>> d = a.remove_axis(2)
>>> d
RaggedTensor([[[1, 2]],
[[3, 4, 5, 6]],
[[0]]], dtype=torch.int32)
Args:
axis:
The axis to move.
Returns:
Return a ragged tensor with one fewer axes.
)doc";
static constexpr const char *kRaggedAnyArangeDoc = R"doc(
Return a sub-range of ``self`` containing indexes ``begin``
through ``end - 1`` along axis ``axis`` of ``self``.
The ``axis`` argument may be confusing; its behavior is equivalent to:
.. code-block:: python
for i in range(axis):
self = self.remove_axis(0)
return self.arange(0, begin, end)
Caution:
The returned tensor shares the underlying memory with ``self``.
**Example 1**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1], [], [2]], [[], [4, 5], []], [[], [1]], [[]] ])
>>> a
RaggedTensor([[[1],
[],
[2]],
[[],
[4, 5],
[]],
[[],
[1]],
[[]]], dtype=torch.int32)
>>> a.num_axes
3
>>> b = a.arange(axis=0, begin=1, end=3)
>>> b
RaggedTensor([[[],
[4, 5],
[]],
[[],
[1]]], dtype=torch.int32)
>>> b.num_axes
3
>>> c = a.arange(axis=0, begin=1, end=2)
>>> c
RaggedTensor([[[],
[4, 5],
[]]], dtype=torch.int32)
>>> c.num_axes
3
>>> d = a.arange(axis=1, begin=0, end=4)
>>> d
RaggedTensor([[1],
[],
[2],
[]], dtype=torch.int32)
>>> d.num_axes
2
>>> e = a.arange(axis=1, begin=2, end=5)
>>> e
RaggedTensor([[2],
[],
[4, 5]], dtype=torch.int32)
>>> e.num_axes
2
**Example 2**
>>> a = k2r.RaggedTensor([ [[[], [1], [2, 3]],[[5, 8], [], [9]]], [[[10], [0], []]], [[[], [], [1]]] ])
>>> a.num_axes
4
>>> b = a.arange(axis=0, begin=0, end=2)
>>> b
RaggedTensor([[[[],
[1],
[2, 3]],
[[5, 8],
[],
[9]]],
[[[10],
[0],
[]]]], dtype=torch.int32)
>>> b.num_axes
4
>>> c = a.arange(axis=1, begin=1, end=3)
>>> c
RaggedTensor([[[5, 8],
[],
[9]],
[[10],
[0],
[]]], dtype=torch.int32)
>>> c.num_axes
3
>>> d = a.arange(axis=2, begin=0, end=5)
>>> d
RaggedTensor([[],
[1],
[2, 3],
[5, 8],
[]], dtype=torch.int32)
>>> d.num_axes
2
**Example 3**
>>> a = k2r.RaggedTensor([[0], [1], [2], [], [3]])
>>> a
RaggedTensor([[0],
[1],
[2],
[],
[3]], dtype=torch.int32)
>>> a.num_axes
2
>>> b = a.arange(axis=0, begin=1, end=4)
>>> b
RaggedTensor([[1],
[2],
[]], dtype=torch.int32)
>>> b.values[0] = -1
>>> a
RaggedTensor([[0],
[-1],
[2],
[],
[3]], dtype=torch.int32)
Args:
axis:
The axis from which ``begin`` and ``end`` correspond to.
begin:
The beginning of the range (inclusive).
end:
The end of the range (exclusive).
)doc";
static constexpr const char *kRaggedAnyRemoveValuesEqDoc = R"doc(
Returns a ragged tensor after removing all 'values' that equal a provided
target. Leaves all layers of the shape except for the last one unaffected.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2, 3, 0, 3, 2], [], [3, 2, 3], [3]])
>>> a
RaggedTensor([[1, 2, 3, 0, 3, 2],
[],
[3, 2, 3],
[3]], dtype=torch.int32)
>>> b = a.remove_values_eq(3)
>>> b
RaggedTensor([[1, 2, 0, 2],
[],
[2],
[]], dtype=torch.int32)
>>> c = a.remove_values_eq(2)
>>> c
RaggedTensor([[1, 3, 0, 3],
[],
[3, 3],
[3]], dtype=torch.int32)
Args:
target:
The target value to delete.
Return:
Return a ragged tensor whose values don't contain the ``target``.
)doc";
static constexpr const char *kRaggedAnyRemoveValuesLeqDoc = R"doc(
Returns a ragged tensor after removing all 'values' that are
equal to or less than a provided cutoff.
Leaves all layers of the shape except for the last one unaffected.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 2, 3, 0, 3, 2], [], [3, 2, 3], [3]])
>>> a
RaggedTensor([[1, 2, 3, 0, 3, 2],
[],
[3, 2, 3],
[3]], dtype=torch.int32)
>>> b = a.remove_values_leq(3)
>>> b
RaggedTensor([[],
[],
[],
[]], dtype=torch.int32)
>>> c = a.remove_values_leq(2)
>>> c
RaggedTensor([[3, 3],
[],
[3, 3],
[3]], dtype=torch.int32)
>>> d = a.remove_values_leq(1)
>>> d
RaggedTensor([[2, 3, 3, 2],
[],
[3, 2, 3],
[3]], dtype=torch.int32)
Args:
cutoff:
Values less than or equal to this ``cutoff`` are deleted.
Return:
Return a ragged tensor whose values are all above ``cutoff``.
)doc";
static constexpr const char *kRaggedAnyArgMaxDoc = R"doc(
Return a tensor containing maximum value indexes within each sub-list along the
last axis of ``self``, i.e. the max taken over the last axis, The index is -1
if the sub-list was empty or all values in the sub-list are less
than ``initial_value``.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [3, -1], [], [], [] ])
>>> a.argmax()
tensor([ 0, -1, -1, -1], dtype=torch.int32)
>>> b = a.argmax(initial_value=0)
>>> b
tensor([ 0, -1, -1, -1], dtype=torch.int32)
>>> c = k2r.RaggedTensor([ [3, 0, 2, 5, 1], [], [1, 3, 8, 2, 0] ])
>>> c.argmax()
tensor([ 3, -1, 7], dtype=torch.int32)
>>> d = c.argmax(initial_value=0)
>>> d
tensor([ 3, -1, 7], dtype=torch.int32)
>>> c.values[3], c.values[7]
(tensor(5, dtype=torch.int32), tensor(8, dtype=torch.int32))
>>> c.argmax(initial_value=6)
tensor([-1, -1, 7], dtype=torch.int32)
>>> c.to('cuda:0').argmax(0)
tensor([ 3, -1, 7], device='cuda:0', dtype=torch.int32)
>>> import torch
>>> c.to(torch.float32).argmax(0)
tensor([ 3, -1, 7], dtype=torch.int32)
Args:
initial_value:
A base value to compare. If values in a sublist are all less
than this value, then the ``argmax`` of this sublist is -1.
If a sublist is empty, the ``argmax`` of it is also -1.
If it is ``None``, the lowest value of ``self.dtype`` is used.
Returns:
Return a 1-D ``torch.int32`` tensor. It is on the same device
as ``self``.
)doc";
static constexpr const char *kRaggedAnyMaxDoc = R"doc(
Return a tensor containing the maximum of each sub-list along the last
axis of ``self``. The max is taken over the last axis or ``initial_value``,
whichever was larger.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1, 3, 0], [2, 5, -1, 1, 3], [], []], [[1, 8, 9, 2], [], [2, 4, 6, 8]] ])
>>> a.max()
tensor([ 3, 5, -2147483648, -2147483648, 9,
-2147483648, 8], dtype=torch.int32)
>>> a.max(initial_value=-10)
tensor([ 3, 5, -10, -10, 9, -10, 8], dtype=torch.int32)
>>> a.max(initial_value=7)
tensor([7, 7, 7, 7, 9, 7, 8], dtype=torch.int32)
>>> import torch
>>> a.to(torch.float32).max(-3)
tensor([ 3., 5., -3., -3., 9., -3., 8.])
>>> a.to('cuda:0').max(-2)
tensor([ 3, 5, -2, -2, 9, -2, 8], device='cuda:0', dtype=torch.int32)
Args:
initial_value:
The base value to compare. If values in a sublist are all less
than this value, then the max of this sublist is ``initial_value``.
If a sublist is empty, its max is also ``initial_value``.
Returns:
Return 1-D tensor containing the max value of each sublist.
It shares the same dtype and device with ``self``.
)doc";
static constexpr const char *kRaggedAnyMinDoc = R"doc(
Return a tensor containing the minimum of each sub-list along the last
axis of ``self``. The min is taken over the last axis or ``initial_value``,
whichever was smaller.
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1, 3, 0], [2, 5, -1, 1, 3], [], []], [[1, 8, 9, 2], [], [2, 4, 6, 8]] ], dtype=torch.float32)
>>> a.min()
tensor([ 0.0000e+00, -1.0000e+00, 3.4028e+38, 3.4028e+38, 1.0000e+00,
3.4028e+38, 2.0000e+00])
>>> a.min(initial_value=float('inf'))
tensor([ 0., -1., inf, inf, 1., inf, 2.])
>>> a.min(100)
tensor([ 0., -1., 100., 100., 1., 100., 2.])
>>> a.to(torch.int32).min(20)
tensor([ 0, -1, 20, 20, 1, 20, 2], dtype=torch.int32)
>>> a.to('cuda:0').min(15)
tensor([ 0., -1., 15., 15., 1., 15., 2.], device='cuda:0')
Args:
initial_value:
The base value to compare. If values in a sublist are all larger
than this value, then the minimum of this sublist is ``initial_value``.
If a sublist is empty, its minimum is also ``initial_value``.
Returns:
Return 1-D tensor containing the minimum of each sublist.
It shares the same dtype and device with ``self``.
)doc";
static constexpr const char *kRaggedCatDoc = R"doc(
Concatenate a list of ragged tensor over a specified axis.
**Example 1**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [], [2, 3]])
>>> k2r.cat([a, a], axis=0)
RaggedTensor([[1],
[],
[2, 3],
[1],
[],
[2, 3]], dtype=torch.int32)
>>> k2r.cat((a, a), axis=1)
RaggedTensor([[1, 1],
[],
[2, 3, 2, 3]], dtype=torch.int32)
**Example 2**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1, 3], [], [5, 8], [], [9]])
>>> b = k2r.RaggedTensor([[0], [1, 8], [], [-1], [10]])
>>> c = k2r.cat([a, b], axis=0)
>>> c
RaggedTensor([[1, 3],
[],
[5, 8],
[],
[9],
[0],
[1, 8],
[],
[-1],
[10]], dtype=torch.int32)
>>> c.num_axes
2
>>> d = k2r.cat([a, b], axis=1)
>>> d
RaggedTensor([[1, 3, 0],
[1, 8],
[5, 8],
[-1],
[9, 10]], dtype=torch.int32)
>>> d.num_axes
2
>>> k2r.RaggedTensor.cat([a, b], axis=1)
RaggedTensor([[1, 3, 0],
[1, 8],
[5, 8],
[-1],
[9, 10]], dtype=torch.int32)
>>> k2r.cat((b, a), axis=0)
RaggedTensor([[0],
[1, 8],
[],
[-1],
[10],
[1, 3],
[],
[5, 8],
[],
[9]], dtype=torch.int32)
Args:
srcs:
A list (or a tuple) of ragged tensors to concatenate. They **MUST** all
have the same dtype and on the same device.
axis:
Only 0 and 1 are supported right now. If it is 1, then
``srcs[i].dim0`` must all have the same value.
Return:
Return a concatenated tensor.
)doc";
static constexpr const char *kRaggedAnyUniqueDoc = R"doc(
If ``self`` has two axes, this will return the unique sub-lists
(in a possibly different order, but without repeats).
If ``self`` has 3 axes, it will do the above but separately for each
index on axis 0; if more than 3 axes, the earliest axes will be ignored.
Caution:
It does not completely guarantee that all unique sequences will be
present in the output, as it relies on hashing and ignores collisions.
If several sequences have the same hash, only one of them is kept, even
if the actual content in the sequence is different.
Caution:
Even if there are no repeated sequences, the output may be different
from ``self``. That is, `new2old_indexes` may NOT be an identity map even
if nothing was removed.
**Example 1**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[3, 1], [3], [1], [1], [3, 1], [2]])
>>> a.unique()
(RaggedTensor([[1],
[2],
[3],
[3, 1]], dtype=torch.int32), None, None)
>>> a.unique(need_num_repeats=True, need_new2old_indexes=True)
(RaggedTensor([[1],
[2],
[3],
[3, 1]], dtype=torch.int32), RaggedTensor([[2, 1, 1, 2]], dtype=torch.int32), tensor([2, 5, 1, 0], dtype=torch.int32))
>>> a.unique(need_num_repeats=True)
(RaggedTensor([[1],
[2],
[3],
[3, 1]], dtype=torch.int32), RaggedTensor([[2, 1, 1, 2]], dtype=torch.int32), None)
>>> a.unique(need_new2old_indexes=True)
(RaggedTensor([[1],
[2],
[3],
[3, 1]], dtype=torch.int32), None, tensor([2, 5, 1, 0], dtype=torch.int32))
**Example 2**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[[1, 2], [2, 1], [1, 2], [1, 2]], [[3], [2], [0, 1], [2]], [[], [2, 3], [], [3]] ])
>>> a.unique()
(RaggedTensor([[[1, 2],
[2, 1]],
[[2],
[3],
[0, 1]],
[[],
[3],
[2, 3]]], dtype=torch.int32), None, None)
>>> a.unique(need_num_repeats=True, need_new2old_indexes=True)
(RaggedTensor([[[1, 2],
[2, 1]],
[[2],
[3],
[0, 1]],
[[],
[3],
[2, 3]]], dtype=torch.int32), RaggedTensor([[3, 1],
[2, 1, 1],
[2, 1, 1]], dtype=torch.int32), tensor([ 0, 1, 5, 4, 6, 8, 11, 9], dtype=torch.int32))
>>> a.unique(need_num_repeats=True)
(RaggedTensor([[[1, 2],
[2, 1]],
[[2],
[3],
[0, 1]],
[[],
[3],
[2, 3]]], dtype=torch.int32), RaggedTensor([[3, 1],
[2, 1, 1],
[2, 1, 1]], dtype=torch.int32), None)
>>> a.unique(need_new2old_indexes=True)
(RaggedTensor([[[1, 2],
[2, 1]],
[[2],
[3],
[0, 1]],
[[],
[3],
[2, 3]]], dtype=torch.int32), None, tensor([ 0, 1, 5, 4, 6, 8, 11, 9], dtype=torch.int32))
**Example 3**
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [3], [2]])
>>> a.unique(True, True)
(RaggedTensor([[1],
[2],
[3]], dtype=torch.int32), RaggedTensor([[1, 1, 1]], dtype=torch.int32), tensor([0, 2, 1], dtype=torch.int32))
Args:
need_num_repeats:
If True, it also returns the number of repeats of each sequence.
need_new2old_indexes:
If true, it returns an extra 1-D tensor `new2old_indexes`.
If `src` has 2 axes, this tensor contains `src_idx0`;
if `src` has 3 axes, this tensor contains `src_idx01`.
Caution:
For repeated sublists, only one of them is kept.
The choice of which one to keep is **deterministic** and
is an implementation detail.
Returns:
Returns a tuple containing:
- ans: A ragged tensor with the same number of axes as ``self`` and possibly
fewer elements due to removing repeated sequences on the last axis
(and with the last-but-one indexes possibly in a different order).
- num_repeats: A tensor containing number of repeats of each returned
sequence if ``need_num_repeats`` is True; it is ``None`` otherwise.
If it is not ``None``, ``num_repeats.num_axes`` is always 2.
If ``ans.num_axes`` is 2, then ``num_repeats.dim0 == 1`` and
``num_repeats.numel() == ans.dim0``.
If ``ans.num_axes`` is 3, then ``num_repeats.dim0 == ans.dim0`` and
``num_repeats.numel() == ans.tot_size(1)``.
- new2old_indexes: A 1-D tensor whose i-th element specifies the
input sublist that the i-th output sublist corresponds to.
)doc";
static constexpr const char *kRaggedAnyNormalizeDoc = R"doc(
Normalize a ragged tensor over the last axis.
If ``use_log`` is ``True``, the normalization per sublist is done as follows:
1. Compute the log sum per sublist
2. Subtract the log sum computed above from the sublist and return
it
If ``use_log`` is ``False``, the normalization per sublist is done as follows:
1. Compute the sum per sublist
2. Divide the sublist by the above sum and return the resulting sublist
Note:
If a sublist contains 3 elements ``[a, b, c]``, then the log sum
is defined as::
s = log(exp(a) + exp(b) + exp(c))
The resulting sublist looks like below if ``use_log`` is ``True``::
[a - s, b - s, c - s]
If ``use_log`` is ``False``, the resulting sublist looks like::
[a/(a+b+c), b/(a+b+c), c/(a+b+c)]
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[0.1, 0.3], [], [1], [0.2, 0.8]])
>>> a.normalize(use_log=False)
RaggedTensor([[0.25, 0.75],
[],
[1],
[0.2, 0.8]], dtype=torch.float32)
>>> a.normalize(use_log=True)
RaggedTensor([[-0.798139, -0.598139],
[],
[0],
[-1.03749, -0.437488]], dtype=torch.float32)
>>> b = k2r.RaggedTensor([ [[0.1, 0.3], []], [[1], [0.2, 0.8]] ])
>>> b.normalize(use_log=False)
RaggedTensor([[[0.25, 0.75],
[]],
[[1],
[0.2, 0.8]]], dtype=torch.float32)
>>> b.normalize(use_log=True)
RaggedTensor([[[-0.798139, -0.598139],
[]],
[[0],
[-1.03749, -0.437488]]], dtype=torch.float32)
>>> a.num_axes
2
>>> b.num_axes
3
>>> import torch
>>> (torch.tensor([0.1, 0.3]).exp() / torch.tensor([0.1, 0.3]).exp().sum()).log()
tensor([-0.7981, -0.5981])
Args:
use_log:
It indicates which kind of normalization to be applied.
Returns:
Returns a 1-D tensor, sharing the same dtype and device with ``self``.
)doc";
static constexpr const char *kRaggedAnyAddDoc = R"doc(
Add value scaled by alpha to source ragged tensor over the last axis.
It implements:
dest[...][i][j] = src[...][i][j] + alpha * value[i]
>>> import k2.ragged as k2r
>>> import torch
>>> src = k2r.RaggedTensor([[1, 3], [1], [2, 8]], dtype=torch.int32)
>>> value = torch.tensor([1, 2, 3], dtype=torch.int32)
>>> src.add(value, 1)
RaggedTensor([[2, 4],
[3],
[5, 11]], dtype=torch.int32)
>>> src.add(value, -1)
RaggedTensor([[0, 2],
[-1],
[-1, 5]], dtype=torch.int32)
Args:
value:
The value to be added to the ``self``, whose dimension MUST
equal the number of sublists along the last dimension of ``self``.
alpha:
The number used to scaled value before adding to ``self``.
Returns:
Returns a new RaggedTensor, sharing the same dtype and device with ``self``.
)doc";
static constexpr const char *kRaggedAnyPadDoc = R"doc(
Pad a ragged tensor with 2-axes to a 2-D torch tensor.
For example, if ``self`` has the following values::
[ [1 2 3] [4] [5 6 7 8] ]
Then it returns a 2-D tensor as follows if ``padding_value`` is 0 and
mode is ``constant``::
tensor([[1, 2, 3, 0],
[4, 0, 0, 0],
[5, 6, 7, 8]])
Caution:
It requires that ``self.num_axes == 2``.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[1], [], [2, 3], [5, 8, 9, 8, 2]])
>>> a.pad(mode='constant', padding_value=-1)
tensor([[ 1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1],
[ 2, 3, -1, -1, -1],
[ 5, 8, 9, 8, 2]], dtype=torch.int32)
>>> a.pad(mode='replicate', padding_value=-1)
tensor([[ 1, 1, 1, 1, 1],
[-1, -1, -1, -1, -1],
[ 2, 3, 3, 3, 3],
[ 5, 8, 9, 8, 2]], dtype=torch.int32)
Args:
mode:
Valid values are: ``constant``, ``replicate``. If it is
``constant``, the given ``padding_value`` is used for filling.
If it is ``replicate``, the last entry in a list is used for filling.
If a list is empty, then the given `padding_value` is also used for filling.
padding_value:
The filling value.
Returns:
A 2-D torch tensor, sharing the same dtype and device with ``self``.
)doc";
static constexpr const char *kRaggedAnyToListDoc = R"doc(
Turn a ragged tensor into a list of lists [of lists..].
Hint:
You can pass the returned list to the constructor of :class:`RaggedTensor`.
>>> a = k2r.RaggedTensor([ [[], [1, 2], [3], []], [[5, 6, 7]], [[], [0, 2, 3], [], []]])
>>> a.tolist()
[[[], [1, 2], [3], []], [[5, 6, 7]], [[], [0, 2, 3], [], []]]
>>> b = k2r.RaggedTensor(a.tolist())
>>> a == b
True
>>> c = k2r.RaggedTensor([[1.], [2.], [], [3.25, 2.5]])
>>> c.tolist()
[[1.0], [2.0], [], [3.25, 2.5]]
Returns:
A list of list of lists [of lists ...] containing the same elements
and structure as ``self``.
)doc";
static constexpr const char *kRaggedAnySortDoc = R"doc(
Sort a ragged tensor over the last axis **in-place**.
Caution:
``sort_`` ends with an underscore, meaning this operation
changes ``self`` **in-place**.
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [1, 3, 0], [2, 5, 3], [], [1, 3, 0.] ])
>>> a_clone = a.clone()
>>> b = a.sort_(descending=True, need_new2old_indexes=True)
>>> b
tensor([1, 0, 2, 4, 5, 3, 7, 6, 8], dtype=torch.int32)
>>> a
RaggedTensor([[3, 1, 0],
[5, 3, 2],
[],
[3, 1, 0]], dtype=torch.float32)
>>> a_clone.values[b.long()]
tensor([3., 1., 0., 5., 3., 2., 3., 1., 0.])
>>> a_clone = a.clone()
>>> c = a.sort_(descending=False, need_new2old_indexes=True)
>>> c
tensor([2, 1, 0, 5, 4, 3, 8, 7, 6], dtype=torch.int32)
>>> a
RaggedTensor([[0, 1, 3],
[2, 3, 5],
[],
[0, 1, 3]], dtype=torch.float32)
>>> a_clone.values[c.long()]
tensor([0., 1., 3., 2., 3., 5., 0., 1., 3.])
Args:
descending:
``True`` to sort in **descending** order.
``False`` to sort in **ascending** order.
need_new2old_indexes:
If ``True``, also returns a 1-D tensor, containing the indexes mapping
from the sorted elements to the unsorted elements. We can use
``self.clone().values[returned_tensor]`` to get a sorted tensor.
Returns:
If ``need_new2old_indexes`` is False, returns None. Otherwise, returns
a 1-D tensor of dtype ``torch.int32``.
)doc";
static constexpr const char *kRaggedAnyRaggedIndexDoc = R"doc(
Index a ragged tensor with a ragged tensor.
**Example 1**:
>>> import k2.ragged as k2r
>>> src = k2r.RaggedTensor([[10, 11], [12, 13.5]])
>>> indexes = k2r.RaggedTensor([[0, 1]])
>>> src.index(indexes)
RaggedTensor([[[10, 11],
[12, 13.5]]], dtype=torch.float32)
>>> i = k2r.RaggedTensor([[0], [1], [0, 0]])
>>> src.index(i)
RaggedTensor([[[10, 11]],
[[12, 13.5]],
[[10, 11],
[10, 11]]], dtype=torch.float32)
**Example 2**:
>>> import k2.ragged as k2r
>>> src = k2r.RaggedTensor([ [[1, 0], [], [2]], [[], [3], [0, 0, 1]], [[1, 2], [-1]]])
>>> i = k2r.RaggedTensor([[[0, 2], [1]], [[0]]])
>>> src.index(i)
RaggedTensor([[[[[1, 0],
[],
[2]],
[[1, 2],
[-1]]],
[[[],
[3],
[0, 0, 1]]]],
[[[[1, 0],
[],
[2]]]]], dtype=torch.int32)
Args:
indexes:
Its values must satisfy ``0 <= values[i] < self.dim0``.
Caution:
Its dtype has to be ``torch.int32``.
Returns:
Return indexed tensor.
)doc";
static constexpr const char *kRaggedAnyTensorIndexDoc = R"doc(
Indexing operation on ragged tensor, returns ``self[indexes]``, where
the elements of ``indexes`` are interpreted as indexes into axis ``axis`` of
``self``.
Caution:
``indexes`` is a 1-D tensor and ``indexes.dtype == torch.int32``.
**Example 1**:
>>> import torch
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([[0, 2, 3], [], [0, 1, 2], [], [], [3, -1.25]])
>>> i = torch.tensor([2, 0, 3, 5], dtype=torch.int32)
>>> b, value_indexes = a.index(i, axis=0, need_value_indexes=True)
>>> b
RaggedTensor([[0, 1, 2],
[0, 2, 3],
[],
[3, -1.25]], dtype=torch.float32)
>>> value_indexes
tensor([3, 4, 5, 0, 1, 2, 6, 7], dtype=torch.int32)
>>> a.values[value_indexes.long()]
tensor([ 0.0000, 1.0000, 2.0000, 0.0000, 2.0000, 3.0000, 3.0000, -1.2500])
>>> k = torch.tensor([2, -1, 0], dtype=torch.int32)
>>> a.index(k, axis=0, need_value_indexes=True)
(RaggedTensor([[0, 1, 2],
[],
[0, 2, 3]], dtype=torch.float32), tensor([3, 4, 5, 0, 1, 2], dtype=torch.int32))
**Example 2**:
>>> import k2.ragged as k2r
>>> a = k2r.RaggedTensor([ [[1, 3], [], [2]], [[5, 8], [], [-1], [2]] ])
>>> i = torch.tensor([0, 2, 1, 6, 3, 5, 4], dtype=torch.int32)
>>> a.shape.row_ids(1)[i.long()]
tensor([0, 0, 0, 1, 1, 1, 1], dtype=torch.int32)
>>> b, value_indexes = a.index(i, axis=1, need_value_indexes=True)
>>> b
RaggedTensor([[[1, 3],
[2],
[]],
[[2],
[5, 8],
[-1],
[]]], dtype=torch.int32)
>>> value_indexes
tensor([0, 1, 2, 6, 3, 4, 5], dtype=torch.int32)
>>> a.values[value_indexes.long()]
tensor([ 1, 3, 2, 2, 5, 8, -1], dtype=torch.int32)
Args:
indexes:
Array of indexes, which will be interpreted as indexes into axis ``axis``
of ``self``, i.e. with ``0 <= indexes[i] < self.tot_size(axis)``.
Note that if ``axis`` is 0, then -1 is also a valid entry in ``index``,
-1 as an index, which will result in an empty list (as if it were the index
into a position in ``self`` that had an empty list at that point).
Caution:
It is currently not allowed to change the order on axes less than
``axis``, i.e. if ``axis > 0``, we require:
``IsMonotonic(self.shape.row_ids(axis)[indexes])``.
axis:
The axis to be indexed. Must satisfy ``0 <= axis < self.num_axes``.
need_value_indexes:
If ``True``, it will return a torch.Tensor containing the indexes into
``self.values`` that ``ans.values`` has, as in
``ans.values = self.values[value_indexes]``.
Returns:
Return a tuple containing:
- A ragged tensor, sharing the same dtype and device with ``self``
- ``None`` if ``need_value_indexes`` is False; a 1-D torch.tensor of
dtype ``torch.int32`` containing the indexes into ``self.values`` that
``ans.values`` has.
)doc";
static constexpr const char *kRaggedAnyIndexTensorWithRaggedDoc = R"doc(
Use a ragged tensor to index a 1-d torch tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> i = k2r.RaggedTensor([ [1, 5, 3], [0, 2] ])
>>> src = torch.arange(6, dtype=torch.int32) * 10
>>> src
tensor([ 0, 10, 20, 30, 40, 50], dtype=torch.int32)
>>> k2r.index(src, i)
RaggedTensor([[10, 50, 30],
[0, 20]], dtype=torch.int32)
>>> k = k2r.RaggedTensor([ [[1, 5, 3], [0]], [[0, 2], [1, 3]] ])
>>> k2r.index(src, k)
RaggedTensor([[[10, 50, 30],
[0]],
[[0, 20],
[10, 30]]], dtype=torch.int32)
>>> n = k2r.RaggedTensor([ [1, -1], [-1, 0], [-1] ])
>>> k2r.index(src, n)
RaggedTensor([[10, 0],
[0, 0],
[0]], dtype=torch.int32)
>>> k2r.index(src, n, default_value=-2)
RaggedTensor([[10, -2],
[-2, 0],
[-2]], dtype=torch.int32)
Args:
src:
A 1-D torch tensor.
indexes:
A ragged tensor with dtype ``torch.int32``.
default_value:
Used only when an entry in ``indexes`` is -1, in which case
it returns ``default_value`` as -1 is not a valid index.
If it is ``None`` and an entry in ``indexes`` is -1, 0 is returned.
Return:
Return a ragged tensor with the same dtype and device as ``src``.
)doc";
static constexpr const char *kRaggedAnyIndexAndSumDoc = R"doc(
Index a 1-D tensor with a ragged tensor of indexes, perform
a sum-per-sublist operation, and return the resulting 1-D tensor.
>>> import torch
>>> import k2.ragged as k2r
>>> i = k2r.RaggedTensor([[1, 3, 5], [0, 2, 3]])
>>> src = torch.arange(6, dtype=torch.float32) * 10
>>> src
tensor([ 0., 10., 20., 30., 40., 50.])
>>> k2r.index_and_sum(src, i)
tensor([90., 50.])
>>> k = k2r.RaggedTensor([[1, -1, 2], [-1], [2, 5, -1]])
>>> k2r.index_and_sum(src, k)
tensor([30., 0., 70.])
Args:
src:
A 1-D tensor.
indexes:
A ragged tensor with two axes. Its dtype MUST be ``torch.int32``.
For instance, it can be the arc map returned from the function
``remove_epsilon``. If an index is -1, the resulting sublist
is 0.
Returns:
Return a 1-D tensor with the same dtype and device as ``src``.
)doc";
} // namespace k2
#endif // K2_PYTHON_CSRC_TORCH_V2_DOC_ANY_H_
| true |
b52817a6c3118ffdc2230966de90439f5bea6ec4 | C++ | tgrochow/scene | /source/graphic_exception.cpp | UTF-8 | 480 | 3.171875 | 3 | [] | no_license | #include "../include/graphic_exception.hpp"
namespace graphic
{
// default constructor
Graphic_exception::Graphic_exception() :
message_(std::string("no error message defined"))
{}
// user constructor
Graphic_exception::Graphic_exception(std::string const& message) :
message_(message)
{}
// destructor
Graphic_exception::~Graphic_exception() throw()
{}
// get error message
char const* Graphic_exception::what() const throw()
{
return message_.c_str();
}
}
| true |